File:  [LON-CAPA] / loncom / lond
Revision 1.305.2.1: download - view: text, annotated - select for diffs
Fri Jan 27 23:05:30 2006 UTC (18 years, 3 months ago) by albertel
Branches: version_2_1_X
CVS tags: version_2_1_2
- backport 1.308

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.305.2.1 2006/01/27 23:05:30 albertel Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: #
   11: # LON-CAPA is free software; you can redistribute it and/or modify
   12: # it under the terms of the GNU General Public License as published by
   13: # the Free Software Foundation; either version 2 of the License, or 
   14: # (at your option) any later version.
   15: #
   16: # LON-CAPA is distributed in the hope that it will be useful,
   17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   19: # GNU General Public License for more details.
   20: #
   21: # You should have received a copy of the GNU General Public License
   22: # along with LON-CAPA; if not, write to the Free Software
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: 
   28: 
   29: # http://www.lon-capa.org/
   30: #
   31: 
   32: use strict;
   33: use lib '/home/httpd/lib/perl/';
   34: use LONCAPA::Configuration;
   35: 
   36: use IO::Socket;
   37: use IO::File;
   38: #use Apache::File;
   39: use Symbol;
   40: use POSIX;
   41: use Crypt::IDEA;
   42: use LWP::UserAgent();
   43: use GDBM_File;
   44: use Authen::Krb4;
   45: use Authen::Krb5;
   46: use lib '/home/httpd/lib/perl/';
   47: use localauth;
   48: use localenroll;
   49: use localstudentphoto;
   50: use File::Copy;
   51: use File::Find;
   52: use LONCAPA::ConfigFileEdit;
   53: use LONCAPA::lonlocal;
   54: use LONCAPA::lonssl;
   55: use Fcntl qw(:flock);
   56: 
   57: my $DEBUG = 0;		       # Non zero to enable debug log entries.
   58: 
   59: my $status='';
   60: my $lastlog='';
   61: 
   62: my $VERSION='$Revision: 1.305.2.1 $'; #' stupid emacs
   63: my $remoteVERSION;
   64: my $currenthostid="default";
   65: my $currentdomainid;
   66: 
   67: my $client;
   68: my $clientip;			# IP address of client.
   69: my $clientname;			# LonCAPA name of client.
   70: 
   71: my $server;
   72: my $thisserver;			# DNS of us.
   73: 
   74: my $keymode;
   75: 
   76: my $cipher;			# Cipher key negotiated with client
   77: my $tmpsnum = 0;		# Id of tmpputs.
   78: 
   79: # 
   80: #   Connection type is:
   81: #      client                   - All client actions are allowed
   82: #      manager                  - only management functions allowed.
   83: #      both                     - Both management and client actions are allowed
   84: #
   85: 
   86: my $ConnectionType;
   87: 
   88: my %hostid;			# ID's for hosts in cluster by ip.
   89: my %hostdom;			# LonCAPA domain for hosts in cluster.
   90: my %hostip;			# IPs for hosts in cluster.
   91: my %hostdns;			# ID's of hosts looked up by DNS name.
   92: 
   93: my %managers;			# Ip -> manager names
   94: 
   95: my %perlvar;			# Will have the apache conf defined perl vars.
   96: 
   97: #
   98: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
   99: #    Each element of the hash contains a reference to an array that contains:
  100: #          A reference to a sub that executes the request corresponding to the keyword.
  101: #          A flag that is true if the request must be encoded to be acceptable.
  102: #          A mask with bits as follows:
  103: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
  104: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
  105: #
  106: my $CLIENT_OK  = 1;
  107: my $MANAGER_OK = 2;
  108: my %Dispatcher;
  109: 
  110: 
  111: #
  112: #  The array below are password error strings."
  113: #
  114: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
  115: my @passwderrors = ("ok",
  116: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
  117: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
  118: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
  119: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
  120: 		   "pwchange_failure - lcpasswd User does not exist.",
  121: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
  122: 		   "pwchange_failure - lcpasswd Unable to su to root.",
  123: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
  124: 		   "pwchange_failure - lcpasswd Username has invalid characters",
  125: 		   "pwchange_failure - lcpasswd Invalid characters in password",
  126: 		   "pwchange_failure - lcpasswd User already exists", 
  127:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
  128: 		   "pwchange_failure - lcpasswd Password mismatch",
  129: 		   "pwchange_failure - lcpasswd Error filename is invalid");
  130: 
  131: 
  132: #  The array below are lcuseradd error strings.:
  133: 
  134: my $lastadderror = 13;
  135: my @adderrors    = ("ok",
  136: 		    "User ID mismatch, lcuseradd must run as user www",
  137: 		    "lcuseradd Incorrect number of command line parameters must be 3",
  138: 		    "lcuseradd Incorrect number of stdinput lines, must be 3",
  139: 		    "lcuseradd Too many other simultaneous pwd changes in progress",
  140: 		    "lcuseradd User does not exist",
  141: 		    "lcuseradd Unable to make www member of users's group",
  142: 		    "lcuseradd Unable to su to root",
  143: 		    "lcuseradd Unable to set password",
  144: 		    "lcuseradd Usrname has invalid characters",
  145: 		    "lcuseradd Password has an invalid character",
  146: 		    "lcuseradd User already exists",
  147: 		    "lcuseradd Could not add user.",
  148: 		    "lcuseradd Password mismatch");
  149: 
  150: 
  151: 
  152: #
  153: #   Statistics that are maintained and dislayed in the status line.
  154: #
  155: my $Transactions = 0;		# Number of attempted transactions.
  156: my $Failures     = 0;		# Number of transcations failed.
  157: 
  158: #   ResetStatistics: 
  159: #      Resets the statistics counters:
  160: #
  161: sub ResetStatistics {
  162:     $Transactions = 0;
  163:     $Failures     = 0;
  164: }
  165: 
  166: #------------------------------------------------------------------------
  167: #
  168: #   LocalConnection
  169: #     Completes the formation of a locally authenticated connection.
  170: #     This function will ensure that the 'remote' client is really the
  171: #     local host.  If not, the connection is closed, and the function fails.
  172: #     If so, initcmd is parsed for the name of a file containing the
  173: #     IDEA session key.  The fie is opened, read, deleted and the session
  174: #     key returned to the caller.
  175: #
  176: # Parameters:
  177: #   $Socket      - Socket open on client.
  178: #   $initcmd     - The full text of the init command.
  179: #
  180: # Implicit inputs:
  181: #    $thisserver - Our DNS name.
  182: #
  183: # Returns:
  184: #     IDEA session key on success.
  185: #     undef on failure.
  186: #
  187: sub LocalConnection {
  188:     my ($Socket, $initcmd) = @_;
  189:     Debug("Attempting local connection: $initcmd client: $clientip me: $thisserver");
  190:     if($clientip ne "127.0.0.1") {
  191: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
  192: 		 ."$clientip ne $thisserver </font>");
  193: 	close $Socket;
  194: 	return undef;
  195:     }  else {
  196: 	chomp($initcmd);	# Get rid of \n in filename.
  197: 	my ($init, $type, $name) = split(/:/, $initcmd);
  198: 	Debug(" Init command: $init $type $name ");
  199: 
  200: 	# Require that $init = init, and $type = local:  Otherwise
  201: 	# the caller is insane:
  202: 
  203: 	if(($init ne "init") && ($type ne "local")) {
  204: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
  205: 		     ."init = $init, and type = $type </font>");
  206: 	    close($Socket);;
  207: 	    return undef;
  208: 		
  209: 	}
  210: 	#  Now get the key filename:
  211: 
  212: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
  213: 	return $IDEAKey;
  214:     }
  215: }
  216: #------------------------------------------------------------------------------
  217: #
  218: #  SSLConnection
  219: #   Completes the formation of an ssh authenticated connection. The
  220: #   socket is promoted to an ssl socket.  If this promotion and the associated
  221: #   certificate exchange are successful, the IDEA key is generated and sent
  222: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
  223: #   the caller after the SSL tunnel is torn down.
  224: #
  225: # Parameters:
  226: #   Name              Type             Purpose
  227: #   $Socket          IO::Socket::INET  Plaintext socket.
  228: #
  229: # Returns:
  230: #    IDEA key on success.
  231: #    undef on failure.
  232: #
  233: sub SSLConnection {
  234:     my $Socket   = shift;
  235: 
  236:     Debug("SSLConnection: ");
  237:     my $KeyFile         = lonssl::KeyFile();
  238:     if(!$KeyFile) {
  239: 	my $err = lonssl::LastError();
  240: 	&logthis("<font color=\"red\"> CRITICAL"
  241: 		 ."Can't get key file $err </font>");
  242: 	return undef;
  243:     }
  244:     my ($CACertificate,
  245: 	$Certificate) = lonssl::CertificateFile();
  246: 
  247: 
  248:     # If any of the key, certificate or certificate authority 
  249:     # certificate filenames are not defined, this can't work.
  250: 
  251:     if((!$Certificate) || (!$CACertificate)) {
  252: 	my $err = lonssl::LastError();
  253: 	&logthis("<font color=\"red\"> CRITICAL"
  254: 		 ."Can't get certificates: $err </font>");
  255: 
  256: 	return undef;
  257:     }
  258:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
  259: 
  260:     # Indicate to our peer that we can procede with
  261:     # a transition to ssl authentication:
  262: 
  263:     print $Socket "ok:ssl\n";
  264: 
  265:     Debug("Approving promotion -> ssl");
  266:     #  And do so:
  267: 
  268:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
  269: 						$CACertificate,
  270: 						$Certificate,
  271: 						$KeyFile);
  272:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
  273: 	my $err = lonssl::LastError();
  274: 	&logthis("<font color=\"red\"> CRITICAL "
  275: 		 ."SSL Socket promotion failed: $err </font>");
  276: 	return undef;
  277:     }
  278:     Debug("SSL Promotion successful");
  279: 
  280:     # 
  281:     #  The only thing we'll use the socket for is to send the IDEA key
  282:     #  to the peer:
  283: 
  284:     my $Key = lonlocal::CreateCipherKey();
  285:     print $SSLSocket "$Key\n";
  286: 
  287:     lonssl::Close($SSLSocket); 
  288: 
  289:     Debug("Key exchange complete: $Key");
  290: 
  291:     return $Key;
  292: }
  293: #
  294: #     InsecureConnection: 
  295: #        If insecure connections are allowd,
  296: #        exchange a challenge with the client to 'validate' the
  297: #        client (not really, but that's the protocol):
  298: #        We produce a challenge string that's sent to the client.
  299: #        The client must then echo the challenge verbatim to us.
  300: #
  301: #  Parameter:
  302: #      Socket      - Socket open on the client.
  303: #  Returns:
  304: #      1           - success.
  305: #      0           - failure (e.g.mismatch or insecure not allowed).
  306: #
  307: sub InsecureConnection {
  308:     my $Socket  =  shift;
  309: 
  310:     #   Don't even start if insecure connections are not allowed.
  311: 
  312:     if(! $perlvar{londAllowInsecure}) {	# Insecure connections not allowed.
  313: 	return 0;
  314:     }
  315: 
  316:     #   Fabricate a challenge string and send it..
  317: 
  318:     my $challenge = "$$".time;	# pid + time.
  319:     print $Socket "$challenge\n";
  320:     &status("Waiting for challenge reply");
  321: 
  322:     my $answer = <$Socket>;
  323:     $answer    =~s/\W//g;
  324:     if($challenge eq $answer) {
  325: 	return 1;
  326:     } else {
  327: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
  328: 	&status("No challenge reqply");
  329: 	return 0;
  330:     }
  331:     
  332: 
  333: }
  334: #
  335: #   Safely execute a command (as long as it's not a shel command and doesn
  336: #   not require/rely on shell escapes.   The function operates by doing a
  337: #   a pipe based fork and capturing stdout and stderr  from the pipe.
  338: #
  339: # Formal Parameters:
  340: #     $line                    - A line of text to be executed as a command.
  341: # Returns:
  342: #     The output from that command.  If the output is multiline the caller
  343: #     must know how to split up the output.
  344: #
  345: #
  346: sub execute_command {
  347:     my ($line)    = @_;
  348:     my @words     = split(/\s/, $line);	# Bust the command up into words.
  349:     my $output    = "";
  350: 
  351:     my $pid = open(CHILD, "-|");
  352:     
  353:     if($pid) {			# Parent process
  354: 	Debug("In parent process for execute_command");
  355: 	my @data = <CHILD>;	# Read the child's outupt...
  356: 	close CHILD;
  357: 	foreach my $output_line (@data) {
  358: 	    Debug("Adding $output_line");
  359: 	    $output .= $output_line; # Presumably has a \n on it.
  360: 	}
  361: 
  362:     } else {			# Child process
  363: 	close (STDERR);
  364: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
  365: 	exec(@words);		# won't return.
  366:     }
  367:     return $output;
  368: }
  369: 
  370: 
  371: #   GetCertificate: Given a transaction that requires a certificate,
  372: #   this function will extract the certificate from the transaction
  373: #   request.  Note that at this point, the only concept of a certificate
  374: #   is the hostname to which we are connected.
  375: #
  376: #   Parameter:
  377: #      request   - The request sent by our client (this parameterization may
  378: #                  need to change when we really use a certificate granting
  379: #                  authority.
  380: #
  381: sub GetCertificate {
  382:     my $request = shift;
  383: 
  384:     return $clientip;
  385: }
  386: 
  387: #
  388: #   Return true if client is a manager.
  389: #
  390: sub isManager {
  391:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
  392: }
  393: #
  394: #   Return tru if client can do client functions
  395: #
  396: sub isClient {
  397:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
  398: }
  399: 
  400: 
  401: #
  402: #   ReadManagerTable: Reads in the current manager table. For now this is
  403: #                     done on each manager authentication because:
  404: #                     - These authentications are not frequent
  405: #                     - This allows dynamic changes to the manager table
  406: #                       without the need to signal to the lond.
  407: #
  408: sub ReadManagerTable {
  409: 
  410:     #   Clean out the old table first..
  411: 
  412:    foreach my $key (keys %managers) {
  413:       delete $managers{$key};
  414:    }
  415: 
  416:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
  417:    if (!open (MANAGERS, $tablename)) {
  418:       logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
  419:       return;
  420:    }
  421:    while(my $host = <MANAGERS>) {
  422:       chomp($host);
  423:       if ($host =~ "^#") {                  # Comment line.
  424:          next;
  425:       }
  426:       if (!defined $hostip{$host}) { # This is a non cluster member
  427: 	    #  The entry is of the form:
  428: 	    #    cluname:hostname
  429: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
  430: 	    #            the host key.
  431: 	    #  hostname- The dns name of the host.
  432: 	    #
  433:           my($cluname, $dnsname) = split(/:/, $host);
  434:           
  435:           my $ip = gethostbyname($dnsname);
  436:           if(defined($ip)) {                 # bad names don't deserve entry.
  437:             my $hostip = inet_ntoa($ip);
  438:             $managers{$hostip} = $cluname;
  439:             logthis('<font color="green"> registering manager '.
  440:                     "$dnsname as $cluname with $hostip </font>\n");
  441:          }
  442:       } else {
  443:          logthis('<font color="green"> existing host'." $host</font>\n");
  444:          $managers{$hostip{$host}} = $host;  # Use info from cluster tab if clumemeber
  445:       }
  446:    }
  447: }
  448: 
  449: #
  450: #  ValidManager: Determines if a given certificate represents a valid manager.
  451: #                in this primitive implementation, the 'certificate' is
  452: #                just the connecting loncapa client name.  This is checked
  453: #                against a valid client list in the configuration.
  454: #
  455: #                  
  456: sub ValidManager {
  457:     my $certificate = shift; 
  458: 
  459:     return isManager;
  460: }
  461: #
  462: #  CopyFile:  Called as part of the process of installing a 
  463: #             new configuration file.  This function copies an existing
  464: #             file to a backup file.
  465: # Parameters:
  466: #     oldfile  - Name of the file to backup.
  467: #     newfile  - Name of the backup file.
  468: # Return:
  469: #     0   - Failure (errno has failure reason).
  470: #     1   - Success.
  471: #
  472: sub CopyFile {
  473: 
  474:     my ($oldfile, $newfile) = @_;
  475: 
  476:     if (! copy($oldfile,$newfile)) {
  477:         return 0;
  478:     }
  479:     chmod(0660, $newfile);
  480:     return 1;
  481: }
  482: #
  483: #  Host files are passed out with externally visible host IPs.
  484: #  If, for example, we are behind a fire-wall or NAT host, our 
  485: #  internally visible IP may be different than the externally
  486: #  visible IP.  Therefore, we always adjust the contents of the
  487: #  host file so that the entry for ME is the IP that we believe
  488: #  we have.  At present, this is defined as the entry that
  489: #  DNS has for us.  If by some chance we are not able to get a
  490: #  DNS translation for us, then we assume that the host.tab file
  491: #  is correct.  
  492: #    BUGBUGBUG - in the future, we really should see if we can
  493: #       easily query the interface(s) instead.
  494: # Parameter(s):
  495: #     contents    - The contents of the host.tab to check.
  496: # Returns:
  497: #     newcontents - The adjusted contents.
  498: #
  499: #
  500: sub AdjustHostContents {
  501:     my $contents  = shift;
  502:     my $adjusted;
  503:     my $me        = $perlvar{'lonHostID'};
  504: 
  505:  foreach my $line (split(/\n/,$contents)) {
  506: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
  507: 	    chomp($line);
  508: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
  509: 	    if ($id eq $me) {
  510:           my $ip = gethostbyname($name);
  511:           my $ipnew = inet_ntoa($ip);
  512:          $ip = $ipnew;
  513: 		#  Reconstruct the host line and append to adjusted:
  514: 		
  515: 		   my $newline = "$id:$domain:$role:$name:$ip";
  516: 		   if($maxcon ne "") { # Not all hosts have loncnew tuning params
  517: 		     $newline .= ":$maxcon:$idleto:$mincon";
  518: 		   }
  519: 		   $adjusted .= $newline."\n";
  520: 		
  521:       } else {		# Not me, pass unmodified.
  522: 		   $adjusted .= $line."\n";
  523:       }
  524: 	} else {                  # Blank or comment never re-written.
  525: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
  526: 	}
  527:  }
  528:  return $adjusted;
  529: }
  530: #
  531: #   InstallFile: Called to install an administrative file:
  532: #       - The file is created with <name>.tmp
  533: #       - The <name>.tmp file is then mv'd to <name>
  534: #   This lugubrious procedure is done to ensure that we are never without
  535: #   a valid, even if dated, version of the file regardless of who crashes
  536: #   and when the crash occurs.
  537: #
  538: #  Parameters:
  539: #       Name of the file
  540: #       File Contents.
  541: #  Return:
  542: #      nonzero - success.
  543: #      0       - failure and $! has an errno.
  544: #
  545: sub InstallFile {
  546: 
  547:     my ($Filename, $Contents) = @_;
  548:     my $TempFile = $Filename.".tmp";
  549: 
  550:     #  Open the file for write:
  551: 
  552:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
  553:     if(!(defined $fh)) {
  554: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  555: 	return 0;
  556:     }
  557:     #  write the contents of the file:
  558: 
  559:     print $fh ($Contents); 
  560:     $fh->close;			# In case we ever have a filesystem w. locking
  561: 
  562:     chmod(0660, $TempFile);
  563: 
  564:     # Now we can move install the file in position.
  565:     
  566:     move($TempFile, $Filename);
  567: 
  568:     return 1;
  569: }
  570: 
  571: 
  572: #
  573: #   ConfigFileFromSelector: converts a configuration file selector
  574: #                 (one of host or domain at this point) into a 
  575: #                 configuration file pathname.
  576: #
  577: #  Parameters:
  578: #      selector  - Configuration file selector.
  579: #  Returns:
  580: #      Full path to the file or undef if the selector is invalid.
  581: #
  582: sub ConfigFileFromSelector {
  583:     my $selector   = shift;
  584:     my $tablefile;
  585: 
  586:     my $tabledir = $perlvar{'lonTabDir'}.'/';
  587:     if ($selector eq "hosts") {
  588: 	$tablefile = $tabledir."hosts.tab";
  589:     } elsif ($selector eq "domain") {
  590: 	$tablefile = $tabledir."domain.tab";
  591:     } else {
  592: 	return undef;
  593:     }
  594:     return $tablefile;
  595: 
  596: }
  597: #
  598: #   PushFile:  Called to do an administrative push of a file.
  599: #              - Ensure the file being pushed is one we support.
  600: #              - Backup the old file to <filename.saved>
  601: #              - Separate the contents of the new file out from the
  602: #                rest of the request.
  603: #              - Write the new file.
  604: #  Parameter:
  605: #     Request - The entire user request.  This consists of a : separated
  606: #               string pushfile:tablename:contents.
  607: #     NOTE:  The contents may have :'s in it as well making things a bit
  608: #            more interesting... but not much.
  609: #  Returns:
  610: #     String to send to client ("ok" or "refused" if bad file).
  611: #
  612: sub PushFile {
  613:     my $request = shift;    
  614:     my ($command, $filename, $contents) = split(":", $request, 3);
  615:     
  616:     #  At this point in time, pushes for only the following tables are
  617:     #  supported:
  618:     #   hosts.tab  ($filename eq host).
  619:     #   domain.tab ($filename eq domain).
  620:     # Construct the destination filename or reject the request.
  621:     #
  622:     # lonManage is supposed to ensure this, however this session could be
  623:     # part of some elaborate spoof that managed somehow to authenticate.
  624:     #
  625: 
  626: 
  627:     my $tablefile = ConfigFileFromSelector($filename);
  628:     if(! (defined $tablefile)) {
  629: 	return "refused";
  630:     }
  631:     #
  632:     # >copy< the old table to the backup table
  633:     #        don't rename in case system crashes/reboots etc. in the time
  634:     #        window between a rename and write.
  635:     #
  636:     my $backupfile = $tablefile;
  637:     $backupfile    =~ s/\.tab$/.old/;
  638:     if(!CopyFile($tablefile, $backupfile)) {
  639: 	&logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
  640: 	return "error:$!";
  641:     }
  642:     &logthis('<font color="green"> Pushfile: backed up '
  643: 	    .$tablefile." to $backupfile</font>");
  644:     
  645:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
  646:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
  647:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
  648:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
  649:     #  that possibilty.
  650: 
  651:     if($filename eq "host") {
  652: 	$contents = AdjustHostContents($contents);
  653:     }
  654: 
  655:     #  Install the new file:
  656: 
  657:     if(!InstallFile($tablefile, $contents)) {
  658: 	&logthis('<font color="red"> Pushfile: unable to install '
  659: 	 .$tablefile." $! </font>");
  660: 	return "error:$!";
  661:     } else {
  662: 	&logthis('<font color="green"> Installed new '.$tablefile
  663: 		 ."</font>");
  664: 
  665:     }
  666: 
  667: 
  668:     #  Indicate success:
  669:  
  670:     return "ok";
  671: 
  672: }
  673: 
  674: #
  675: #  Called to re-init either lonc or lond.
  676: #
  677: #  Parameters:
  678: #    request   - The full request by the client.  This is of the form
  679: #                reinit:<process>  
  680: #                where <process> is allowed to be either of 
  681: #                lonc or lond
  682: #
  683: #  Returns:
  684: #     The string to be sent back to the client either:
  685: #   ok         - Everything worked just fine.
  686: #   error:why  - There was a failure and why describes the reason.
  687: #
  688: #
  689: sub ReinitProcess {
  690:     my $request = shift;
  691: 
  692: 
  693:     # separate the request (reinit) from the process identifier and
  694:     # validate it producing the name of the .pid file for the process.
  695:     #
  696:     #
  697:     my ($junk, $process) = split(":", $request);
  698:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  699:     if($process eq 'lonc') {
  700: 	$processpidfile = $processpidfile."lonc.pid";
  701: 	if (!open(PIDFILE, "< $processpidfile")) {
  702: 	    return "error:Open failed for $processpidfile";
  703: 	}
  704: 	my $loncpid = <PIDFILE>;
  705: 	close(PIDFILE);
  706: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
  707: 		."</font>");
  708: 	kill("USR2", $loncpid);
  709:     } elsif ($process eq 'lond') {
  710: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  711: 	&UpdateHosts;			# Lond is us!!
  712:     } else {
  713: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  714: 		 ."</font>");
  715: 	return "error:Invalid process identifier $process";
  716:     }
  717:     return 'ok';
  718: }
  719: #   Validate a line in a configuration file edit script:
  720: #   Validation includes:
  721: #     - Ensuring the command is valid.
  722: #     - Ensuring the command has sufficient parameters
  723: #   Parameters:
  724: #     scriptline - A line to validate (\n has been stripped for what it's worth).
  725: #
  726: #   Return:
  727: #      0     - Invalid scriptline.
  728: #      1     - Valid scriptline
  729: #  NOTE:
  730: #     Only the command syntax is checked, not the executability of the
  731: #     command.
  732: #
  733: sub isValidEditCommand {
  734:     my $scriptline = shift;
  735: 
  736:     #   Line elements are pipe separated:
  737: 
  738:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
  739:     &logthis('<font color="green"> isValideditCommand checking: '.
  740: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
  741:     
  742:     if ($command eq "delete") {
  743: 	#
  744: 	#   key with no newline.
  745: 	#
  746: 	if( ($key eq "") || ($newline ne "")) {
  747: 	    return 0;		# Must have key but no newline.
  748: 	} else {
  749: 	    return 1;		# Valid syntax.
  750: 	}
  751:     } elsif ($command eq "replace") {
  752: 	#
  753: 	#   key and newline:
  754: 	#
  755: 	if (($key eq "") || ($newline eq "")) {
  756: 	    return 0;
  757: 	} else {
  758: 	    return 1;
  759: 	}
  760:     } elsif ($command eq "append") {
  761: 	if (($key ne "") && ($newline eq "")) {
  762: 	    return 1;
  763: 	} else {
  764: 	    return 0;
  765: 	}
  766:     } else {
  767: 	return 0;		# Invalid command.
  768:     }
  769:     return 0;			# Should not get here!!!
  770: }
  771: #
  772: #   ApplyEdit - Applies an edit command to a line in a configuration 
  773: #               file.  It is the caller's responsiblity to validate the
  774: #               edit line.
  775: #   Parameters:
  776: #      $directive - A single edit directive to apply.  
  777: #                   Edit directives are of the form:
  778: #                  append|newline      - Appends a new line to the file.
  779: #                  replace|key|newline - Replaces the line with key value 'key'
  780: #                  delete|key          - Deletes the line with key value 'key'.
  781: #      $editor   - A config file editor object that contains the
  782: #                  file being edited.
  783: #
  784: sub ApplyEdit {
  785: 
  786:     my ($directive, $editor) = @_;
  787: 
  788:     # Break the directive down into its command and its parameters
  789:     # (at most two at this point.  The meaning of the parameters, if in fact
  790:     #  they exist depends on the command).
  791: 
  792:     my ($command, $p1, $p2) = split(/\|/, $directive);
  793: 
  794:     if($command eq "append") {
  795: 	$editor->Append($p1);	          # p1 - key p2 null.
  796:     } elsif ($command eq "replace") {
  797: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
  798:     } elsif ($command eq "delete") {
  799: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
  800:     } else {			          # Should not get here!!!
  801: 	die "Invalid command given to ApplyEdit $command"
  802:     }
  803: }
  804: #
  805: # AdjustOurHost:
  806: #           Adjusts a host file stored in a configuration file editor object
  807: #           for the true IP address of this host. This is necessary for hosts
  808: #           that live behind a firewall.
  809: #           Those hosts have a publicly distributed IP of the firewall, but
  810: #           internally must use their actual IP.  We assume that a given
  811: #           host only has a single IP interface for now.
  812: # Formal Parameters:
  813: #     editor   - The configuration file editor to adjust.  This
  814: #                editor is assumed to contain a hosts.tab file.
  815: # Strategy:
  816: #    - Figure out our hostname.
  817: #    - Lookup the entry for this host.
  818: #    - Modify the line to contain our IP
  819: #    - Do a replace for this host.
  820: sub AdjustOurHost {
  821:     my $editor        = shift;
  822: 
  823:     # figure out who I am.
  824: 
  825:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
  826: 
  827:     #  Get my host file entry.
  828: 
  829:     my $ConfigLine    = $editor->Find($myHostName);
  830:     if(! (defined $ConfigLine)) {
  831: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
  832:     }
  833:     # figure out my IP:
  834:     #   Use the config line to get my hostname.
  835:     #   Use gethostbyname to translate that into an IP address.
  836:     #
  837:     my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
  838:     my $BinaryIp = gethostbyname($name);
  839:     my $ip       = inet_ntoa($ip);
  840:     #
  841:     #  Reassemble the config line from the elements in the list.
  842:     #  Note that if the loncnew items were not present before, they will
  843:     #  be now even if they would be empty
  844:     #
  845:     my $newConfigLine = $id;
  846:     foreach my $item ($domain, $role, $name, $ip, $maxcon, $idleto, $mincon) {
  847: 	$newConfigLine .= ":".$item;
  848:     }
  849:     #  Replace the line:
  850: 
  851:     $editor->ReplaceLine($id, $newConfigLine);
  852:     
  853: }
  854: #
  855: #   ReplaceConfigFile:
  856: #              Replaces a configuration file with the contents of a
  857: #              configuration file editor object.
  858: #              This is done by:
  859: #              - Copying the target file to <filename>.old
  860: #              - Writing the new file to <filename>.tmp
  861: #              - Moving <filename.tmp>  -> <filename>
  862: #              This laborious process ensures that the system is never without
  863: #              a configuration file that's at least valid (even if the contents
  864: #              may be dated).
  865: #   Parameters:
  866: #        filename   - Name of the file to modify... this is a full path.
  867: #        editor     - Editor containing the file.
  868: #
  869: sub ReplaceConfigFile {
  870:     
  871:     my ($filename, $editor) = @_;
  872: 
  873:     CopyFile ($filename, $filename.".old");
  874: 
  875:     my $contents  = $editor->Get(); # Get the contents of the file.
  876: 
  877:     InstallFile($filename, $contents);
  878: }
  879: #   
  880: #
  881: #   Called to edit a configuration table  file
  882: #   Parameters:
  883: #      request           - The entire command/request sent by lonc or lonManage
  884: #   Return:
  885: #      The reply to send to the client.
  886: #
  887: sub EditFile {
  888:     my $request = shift;
  889: 
  890:     #  Split the command into it's pieces:  edit:filetype:script
  891: 
  892:     my ($request, $filetype, $script) = split(/:/, $request,3);	# : in script
  893: 
  894:     #  Check the pre-coditions for success:
  895: 
  896:     if($request != "edit") {	# Something is amiss afoot alack.
  897: 	return "error:edit request detected, but request != 'edit'\n";
  898:     }
  899:     if( ($filetype ne "hosts")  &&
  900: 	($filetype ne "domain")) {
  901: 	return "error:edit requested with invalid file specifier: $filetype \n";
  902:     }
  903: 
  904:     #   Split the edit script and check it's validity.
  905: 
  906:     my @scriptlines = split(/\n/, $script);  # one line per element.
  907:     my $linecount   = scalar(@scriptlines);
  908:     for(my $i = 0; $i < $linecount; $i++) {
  909: 	chomp($scriptlines[$i]);
  910: 	if(!isValidEditCommand($scriptlines[$i])) {
  911: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
  912: 	}
  913:     }
  914: 
  915:     #   Execute the edit operation.
  916:     #   - Create a config file editor for the appropriate file and 
  917:     #   - execute each command in the script:
  918:     #
  919:     my $configfile = ConfigFileFromSelector($filetype);
  920:     if (!(defined $configfile)) {
  921: 	return "refused\n";
  922:     }
  923:     my $editor = ConfigFileEdit->new($configfile);
  924: 
  925:     for (my $i = 0; $i < $linecount; $i++) {
  926: 	ApplyEdit($scriptlines[$i], $editor);
  927:     }
  928:     # If the file is the host file, ensure that our host is
  929:     # adjusted to have our ip:
  930:     #
  931:     if($filetype eq "host") {
  932: 	AdjustOurHost($editor);
  933:     }
  934:     #  Finally replace the current file with our file.
  935:     #
  936:     ReplaceConfigFile($configfile, $editor);
  937: 
  938:     return "ok\n";
  939: }
  940: 
  941: #---------------------------------------------------------------
  942: #
  943: # Manipulation of hash based databases (factoring out common code
  944: # for later use as we refactor.
  945: #
  946: #  Ties a domain level resource file to a hash.
  947: #  If requested a history entry is created in the associated hist file.
  948: #
  949: #  Parameters:
  950: #     domain    - Name of the domain in which the resource file lives.
  951: #     namespace - Name of the hash within that domain.
  952: #     how       - How to tie the hash (e.g. GDBM_WRCREAT()).
  953: #     loghead   - Optional parameter, if present a log entry is created
  954: #                 in the associated history file and this is the first part
  955: #                  of that entry.
  956: #     logtail   - Goes along with loghead,  The actual logentry is of the
  957: #                 form $loghead:<timestamp>:logtail.
  958: # Returns:
  959: #    Reference to a hash bound to the db file or alternatively undef
  960: #    if the tie failed.
  961: #
  962: sub tie_domain_hash {
  963:     my ($domain,$namespace,$how,$loghead,$logtail) = @_;
  964:     
  965:     # Filter out any whitespace in the domain name:
  966:     
  967:     $domain =~ s/\W//g;
  968:     
  969:     # We have enough to go on to tie the hash:
  970:     
  971:     my $user_top_dir   = $perlvar{'lonUsersDir'};
  972:     my $domain_dir     = $user_top_dir."/$domain";
  973:     my $resource_file  = $domain_dir."/$namespace.db";
  974:     my %hash;
  975:     if(tie(%hash, 'GDBM_File', $resource_file, $how, 0640)) {
  976: 	if (defined($loghead)) {	# Need to log the operation.
  977: 	    my $logFh = IO::File->new(">>$domain_dir/$namespace.hist");
  978: 	    if($logFh) {
  979: 		my $timestamp = time;
  980: 		print $logFh "$loghead:$timestamp:$logtail\n";
  981: 	    }
  982: 	    $logFh->close;
  983: 	}
  984: 	return \%hash;		# Return the tied hash.
  985:     } else {
  986: 	return undef;		# Tie failed.
  987:     }
  988: }
  989: 
  990: #
  991: #   Ties a user's resource file to a hash.  
  992: #   If necessary, an appropriate history
  993: #   log file entry is made as well.
  994: #   This sub factors out common code from the subs that manipulate
  995: #   the various gdbm files that keep keyword value pairs.
  996: # Parameters:
  997: #   domain       - Name of the domain the user is in.
  998: #   user         - Name of the 'current user'.
  999: #   namespace    - Namespace representing the file to tie.
 1000: #   how          - What the tie is done to (e.g. GDBM_WRCREAT().
 1001: #   loghead      - Optional first part of log entry if there may be a
 1002: #                  history file.
 1003: #   what         - Optional tail of log entry if there may be a history
 1004: #                  file.
 1005: # Returns:
 1006: #   hash to which the database is tied.  It's up to the caller to untie.
 1007: #   undef if the has could not be tied.
 1008: #
 1009: sub tie_user_hash {
 1010:     my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
 1011: 
 1012:     $namespace=~s/\//\_/g;	# / -> _
 1013:     $namespace=~s/\W//g;		# whitespace eliminated.
 1014:     my $proname     = propath($domain, $user);
 1015:    
 1016:     #  Tie the database.
 1017:     
 1018:     my %hash;
 1019:     if(tie(%hash, 'GDBM_File', "$proname/$namespace.db",
 1020: 	   $how, 0640)) {
 1021: 	# If this is a namespace for which a history is kept,
 1022: 	# make the history log entry:    
 1023: 	if (($namespace !~/^nohist\_/) && (defined($loghead))) {
 1024: 	    my $args = scalar @_;
 1025: 	    Debug(" Opening history: $namespace $args");
 1026: 	    my $hfh = IO::File->new(">>$proname/$namespace.hist"); 
 1027: 	    if($hfh) {
 1028: 		my $now = time;
 1029: 		print $hfh "$loghead:$now:$what\n";
 1030: 	    }
 1031: 	    $hfh->close;
 1032: 	}
 1033: 	return \%hash;
 1034:     } else {
 1035: 	return undef;
 1036:     }
 1037:     
 1038: }
 1039: 
 1040: #   read_profile
 1041: #
 1042: #   Returns a set of specific entries from a user's profile file.
 1043: #   this is a utility function that is used by both get_profile_entry and
 1044: #   get_profile_entry_encrypted.
 1045: #
 1046: # Parameters:
 1047: #    udom       - Domain in which the user exists.
 1048: #    uname      - User's account name (loncapa account)
 1049: #    namespace  - The profile namespace to open.
 1050: #    what       - A set of & separated queries.
 1051: # Returns:
 1052: #    If all ok: - The string that needs to be shipped back to the user.
 1053: #    If failure - A string that starts with error: followed by the failure
 1054: #                 reason.. note that this probabyl gets shipped back to the
 1055: #                 user as well.
 1056: #
 1057: sub read_profile {
 1058:     my ($udom, $uname, $namespace, $what) = @_;
 1059:     
 1060:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 1061: 				 &GDBM_READER());
 1062:     if ($hashref) {
 1063:         my @queries=split(/\&/,$what);
 1064:         my $qresult='';
 1065: 	
 1066: 	for (my $i=0;$i<=$#queries;$i++) {
 1067: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
 1068: 	}
 1069: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
 1070: 	if (untie %$hashref) {
 1071: 	    return $qresult;
 1072: 	} else {
 1073: 	    return "error: ".($!+0)." untie (GDBM) Failed";
 1074: 	}
 1075:     } else {
 1076: 	if ($!+0 == 2) {
 1077: 	    return "error:No such file or GDBM reported bad block error";
 1078: 	} else {
 1079: 	    return "error: ".($!+0)." tie (GDBM) Failed";
 1080: 	}
 1081:     }
 1082: 
 1083: }
 1084: #--------------------- Request Handlers --------------------------------------------
 1085: #
 1086: #   By convention each request handler registers itself prior to the sub 
 1087: #   declaration:
 1088: #
 1089: 
 1090: #++
 1091: #
 1092: #  Handles ping requests.
 1093: #  Parameters:
 1094: #      $cmd    - the actual keyword that invoked us.
 1095: #      $tail   - the tail of the request that invoked us.
 1096: #      $replyfd- File descriptor connected to the client
 1097: #  Implicit Inputs:
 1098: #      $currenthostid - Global variable that carries the name of the host we are
 1099: #                       known as.
 1100: #  Returns:
 1101: #      1       - Ok to continue processing.
 1102: #      0       - Program should exit.
 1103: #  Side effects:
 1104: #      Reply information is sent to the client.
 1105: sub ping_handler {
 1106:     my ($cmd, $tail, $client) = @_;
 1107:     Debug("$cmd $tail $client .. $currenthostid:");
 1108:    
 1109:     Reply( $client,"$currenthostid\n","$cmd:$tail");
 1110:    
 1111:     return 1;
 1112: }
 1113: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
 1114: 
 1115: #++
 1116: #
 1117: # Handles pong requests.  Pong replies with our current host id, and
 1118: #                         the results of a ping sent to us via our lonc.
 1119: #
 1120: # Parameters:
 1121: #      $cmd    - the actual keyword that invoked us.
 1122: #      $tail   - the tail of the request that invoked us.
 1123: #      $replyfd- File descriptor connected to the client
 1124: #  Implicit Inputs:
 1125: #      $currenthostid - Global variable that carries the name of the host we are
 1126: #                       connected to.
 1127: #  Returns:
 1128: #      1       - Ok to continue processing.
 1129: #      0       - Program should exit.
 1130: #  Side effects:
 1131: #      Reply information is sent to the client.
 1132: sub pong_handler {
 1133:     my ($cmd, $tail, $replyfd) = @_;
 1134: 
 1135:     my $reply=&reply("ping",$clientname);
 1136:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
 1137:     return 1;
 1138: }
 1139: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
 1140: 
 1141: #++
 1142: #      Called to establish an encrypted session key with the remote client.
 1143: #      Note that with secure lond, in most cases this function is never
 1144: #      invoked.  Instead, the secure session key is established either
 1145: #      via a local file that's locked down tight and only lives for a short
 1146: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
 1147: #      bits from /dev/urandom, rather than the predictable pattern used by
 1148: #      by this sub.  This sub is only used in the old-style insecure
 1149: #      key negotiation.
 1150: # Parameters:
 1151: #      $cmd    - the actual keyword that invoked us.
 1152: #      $tail   - the tail of the request that invoked us.
 1153: #      $replyfd- File descriptor connected to the client
 1154: #  Implicit Inputs:
 1155: #      $currenthostid - Global variable that carries the name of the host
 1156: #                       known as.
 1157: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
 1158: #  Returns:
 1159: #      1       - Ok to continue processing.
 1160: #      0       - Program should exit.
 1161: #  Implicit Outputs:
 1162: #      Reply information is sent to the client.
 1163: #      $cipher is set with a reference to a new IDEA encryption object.
 1164: #
 1165: sub establish_key_handler {
 1166:     my ($cmd, $tail, $replyfd) = @_;
 1167: 
 1168:     my $buildkey=time.$$.int(rand 100000);
 1169:     $buildkey=~tr/1-6/A-F/;
 1170:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1171:     my $key=$currenthostid.$clientname;
 1172:     $key=~tr/a-z/A-Z/;
 1173:     $key=~tr/G-P/0-9/;
 1174:     $key=~tr/Q-Z/0-9/;
 1175:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1176:     $key=substr($key,0,32);
 1177:     my $cipherkey=pack("H32",$key);
 1178:     $cipher=new IDEA $cipherkey;
 1179:     &Reply($replyfd, "$buildkey\n", "$cmd:$tail"); 
 1180:    
 1181:     return 1;
 1182: 
 1183: }
 1184: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
 1185: 
 1186: #     Handler for the load command.  Returns the current system load average
 1187: #     to the requestor.
 1188: #
 1189: # Parameters:
 1190: #      $cmd    - the actual keyword that invoked us.
 1191: #      $tail   - the tail of the request that invoked us.
 1192: #      $replyfd- File descriptor connected to the client
 1193: #  Implicit Inputs:
 1194: #      $currenthostid - Global variable that carries the name of the host
 1195: #                       known as.
 1196: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
 1197: #  Returns:
 1198: #      1       - Ok to continue processing.
 1199: #      0       - Program should exit.
 1200: #  Side effects:
 1201: #      Reply information is sent to the client.
 1202: sub load_handler {
 1203:     my ($cmd, $tail, $replyfd) = @_;
 1204: 
 1205:    # Get the load average from /proc/loadavg and calculate it as a percentage of
 1206:    # the allowed load limit as set by the perl global variable lonLoadLim
 1207: 
 1208:     my $loadavg;
 1209:     my $loadfile=IO::File->new('/proc/loadavg');
 1210:    
 1211:     $loadavg=<$loadfile>;
 1212:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
 1213:    
 1214:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1215: 
 1216:     &Reply( $replyfd, "$loadpercent\n", "$cmd:$tail");
 1217:    
 1218:     return 1;
 1219: }
 1220: &register_handler("load", \&load_handler, 0, 1, 0);
 1221: 
 1222: #
 1223: #   Process the userload request.  This sub returns to the client the current
 1224: #  user load average.  It can be invoked either by clients or managers.
 1225: #
 1226: # Parameters:
 1227: #      $cmd    - the actual keyword that invoked us.
 1228: #      $tail   - the tail of the request that invoked us.
 1229: #      $replyfd- File descriptor connected to the client
 1230: #  Implicit Inputs:
 1231: #      $currenthostid - Global variable that carries the name of the host
 1232: #                       known as.
 1233: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
 1234: #  Returns:
 1235: #      1       - Ok to continue processing.
 1236: #      0       - Program should exit
 1237: # Implicit inputs:
 1238: #     whatever the userload() function requires.
 1239: #  Implicit outputs:
 1240: #     the reply is written to the client.
 1241: #
 1242: sub user_load_handler {
 1243:     my ($cmd, $tail, $replyfd) = @_;
 1244: 
 1245:     my $userloadpercent=&userload();
 1246:     &Reply($replyfd, "$userloadpercent\n", "$cmd:$tail");
 1247:     
 1248:     return 1;
 1249: }
 1250: &register_handler("userload", \&user_load_handler, 0, 1, 0);
 1251: 
 1252: #   Process a request for the authorization type of a user:
 1253: #   (userauth).
 1254: #
 1255: # Parameters:
 1256: #      $cmd    - the actual keyword that invoked us.
 1257: #      $tail   - the tail of the request that invoked us.
 1258: #      $replyfd- File descriptor connected to the client
 1259: #  Returns:
 1260: #      1       - Ok to continue processing.
 1261: #      0       - Program should exit
 1262: # Implicit outputs:
 1263: #    The user authorization type is written to the client.
 1264: #
 1265: sub user_authorization_type {
 1266:     my ($cmd, $tail, $replyfd) = @_;
 1267:    
 1268:     my $userinput = "$cmd:$tail";
 1269:    
 1270:     #  Pull the domain and username out of the command tail.
 1271:     # and call get_auth_type to determine the authentication type.
 1272:    
 1273:     my ($udom,$uname)=split(/:/,$tail);
 1274:     my $result = &get_auth_type($udom, $uname);
 1275:     if($result eq "nouser") {
 1276: 	&Failure( $replyfd, "unknown_user\n", $userinput);
 1277:     } else {
 1278: 	#
 1279: 	# We only want to pass the second field from get_auth_type
 1280: 	# for ^krb.. otherwise we'll be handing out the encrypted
 1281: 	# password for internals e.g.
 1282: 	#
 1283: 	my ($type,$otherinfo) = split(/:/,$result);
 1284: 	if($type =~ /^krb/) {
 1285: 	    $type = $result;
 1286: 	} else {
 1287:             $type .= ':';
 1288:         }
 1289: 	&Reply( $replyfd, "$type\n", $userinput);
 1290:     }
 1291:   
 1292:     return 1;
 1293: }
 1294: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
 1295: 
 1296: #   Process a request by a manager to push a hosts or domain table 
 1297: #   to us.  We pick apart the command and pass it on to the subs
 1298: #   that already exist to do this.
 1299: #
 1300: # Parameters:
 1301: #      $cmd    - the actual keyword that invoked us.
 1302: #      $tail   - the tail of the request that invoked us.
 1303: #      $client - File descriptor connected to the client
 1304: #  Returns:
 1305: #      1       - Ok to continue processing.
 1306: #      0       - Program should exit
 1307: # Implicit Output:
 1308: #    a reply is written to the client.
 1309: sub push_file_handler {
 1310:     my ($cmd, $tail, $client) = @_;
 1311: 
 1312:     my $userinput = "$cmd:$tail";
 1313: 
 1314:     # At this time we only know that the IP of our partner is a valid manager
 1315:     # the code below is a hook to do further authentication (e.g. to resolve
 1316:     # spoofing).
 1317: 
 1318:     my $cert = &GetCertificate($userinput);
 1319:     if(&ValidManager($cert)) { 
 1320: 
 1321: 	# Now presumably we have the bona fides of both the peer host and the
 1322: 	# process making the request.
 1323:       
 1324: 	my $reply = &PushFile($userinput);
 1325: 	&Reply($client, "$reply\n", $userinput);
 1326: 
 1327:     } else {
 1328: 	&Failure( $client, "refused\n", $userinput);
 1329:     } 
 1330:     return 1;
 1331: }
 1332: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
 1333: 
 1334: #
 1335: #   du  - list the disk usuage of a directory recursively. 
 1336: #    
 1337: #   note: stolen code from the ls file handler
 1338: #   under construction by Rick Banghart 
 1339: #    .
 1340: # Parameters:
 1341: #    $cmd        - The command that dispatched us (du).
 1342: #    $ududir     - The directory path to list... I'm not sure what this
 1343: #                  is relative as things like ls:. return e.g.
 1344: #                  no_such_dir.
 1345: #    $client     - Socket open on the client.
 1346: # Returns:
 1347: #     1 - indicating that the daemon should not disconnect.
 1348: # Side Effects:
 1349: #   The reply is written to  $client.
 1350: #
 1351: sub du_handler {
 1352:     my ($cmd, $ududir, $client) = @_;
 1353:     my ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
 1354:     my $userinput = "$cmd:$ududir";
 1355: 
 1356:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
 1357: 	&Failure($client,"refused\n","$cmd:$ududir");
 1358: 	return 1;
 1359:     }
 1360:     #  Since $ududir could have some nasties in it,
 1361:     #  we will require that ududir is a valid
 1362:     #  directory.  Just in case someone tries to
 1363:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
 1364:     #  etc.
 1365:     #
 1366:     if (-d $ududir) {
 1367: 	my $total_size=0;
 1368: 	my $code=sub { 
 1369: 	    if ($_=~/\.\d+\./) { return;} 
 1370: 	    if ($_=~/\.meta$/) { return;}
 1371: 	    $total_size+=(stat($_))[7];
 1372: 	};
 1373: 	chdir($ududir);
 1374: 	find($code,$ududir);
 1375: 	$total_size=int($total_size/1024);
 1376: 	&Reply($client,"$total_size\n","$cmd:$ududir");
 1377:     } else {
 1378: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
 1379:     }
 1380:     return 1;
 1381: }
 1382: &register_handler("du", \&du_handler, 0, 1, 0);
 1383: 
 1384: #
 1385: # The ls_handler routine should be considered obosolete and is retained
 1386: # for communication with legacy servers.  Please see the ls2_handler.
 1387: #
 1388: #   ls  - list the contents of a directory.  For each file in the
 1389: #    selected directory the filename followed by the full output of
 1390: #    the stat function is returned.  The returned info for each
 1391: #    file are separated by ':'.  The stat fields are separated by &'s.
 1392: # Parameters:
 1393: #    $cmd        - The command that dispatched us (ls).
 1394: #    $ulsdir     - The directory path to list... I'm not sure what this
 1395: #                  is relative as things like ls:. return e.g.
 1396: #                  no_such_dir.
 1397: #    $client     - Socket open on the client.
 1398: # Returns:
 1399: #     1 - indicating that the daemon should not disconnect.
 1400: # Side Effects:
 1401: #   The reply is written to  $client.
 1402: #
 1403: sub ls_handler {
 1404:     # obsoleted by ls2_handler
 1405:     my ($cmd, $ulsdir, $client) = @_;
 1406: 
 1407:     my $userinput = "$cmd:$ulsdir";
 1408: 
 1409:     my $obs;
 1410:     my $rights;
 1411:     my $ulsout='';
 1412:     my $ulsfn;
 1413:     if (-e $ulsdir) {
 1414: 	if(-d $ulsdir) {
 1415: 	    if (opendir(LSDIR,$ulsdir)) {
 1416: 		while ($ulsfn=readdir(LSDIR)) {
 1417: 		    undef($obs);
 1418: 		    undef($rights); 
 1419: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1420: 		    #We do some obsolete checking here
 1421: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1422: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1423: 			my @obsolete=<FILE>;
 1424: 			foreach my $obsolete (@obsolete) {
 1425: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1426: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
 1427: 			}
 1428: 		    }
 1429: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
 1430: 		    if($obs eq '1') { $ulsout.="&1"; }
 1431: 		    else { $ulsout.="&0"; }
 1432: 		    if($rights eq '1') { $ulsout.="&1:"; }
 1433: 		    else { $ulsout.="&0:"; }
 1434: 		}
 1435: 		closedir(LSDIR);
 1436: 	    }
 1437: 	} else {
 1438: 	    my @ulsstats=stat($ulsdir);
 1439: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1440: 	}
 1441:     } else {
 1442: 	$ulsout='no_such_dir';
 1443:     }
 1444:     if ($ulsout eq '') { $ulsout='empty'; }
 1445:     &Reply($client, "$ulsout\n", $userinput); # This supports debug logging.
 1446:     
 1447:     return 1;
 1448: 
 1449: }
 1450: &register_handler("ls", \&ls_handler, 0, 1, 0);
 1451: 
 1452: #
 1453: # Please also see the ls_handler, which this routine obosolets.
 1454: # ls2_handler differs from ls_handler in that it escapes its return 
 1455: # values before concatenating them together with ':'s.
 1456: #
 1457: #   ls2  - list the contents of a directory.  For each file in the
 1458: #    selected directory the filename followed by the full output of
 1459: #    the stat function is returned.  The returned info for each
 1460: #    file are separated by ':'.  The stat fields are separated by &'s.
 1461: # Parameters:
 1462: #    $cmd        - The command that dispatched us (ls).
 1463: #    $ulsdir     - The directory path to list... I'm not sure what this
 1464: #                  is relative as things like ls:. return e.g.
 1465: #                  no_such_dir.
 1466: #    $client     - Socket open on the client.
 1467: # Returns:
 1468: #     1 - indicating that the daemon should not disconnect.
 1469: # Side Effects:
 1470: #   The reply is written to  $client.
 1471: #
 1472: sub ls2_handler {
 1473:     my ($cmd, $ulsdir, $client) = @_;
 1474: 
 1475:     my $userinput = "$cmd:$ulsdir";
 1476: 
 1477:     my $obs;
 1478:     my $rights;
 1479:     my $ulsout='';
 1480:     my $ulsfn;
 1481:     if (-e $ulsdir) {
 1482:         if(-d $ulsdir) {
 1483:             if (opendir(LSDIR,$ulsdir)) {
 1484:                 while ($ulsfn=readdir(LSDIR)) {
 1485:                     undef($obs);
 1486: 		    undef($rights); 
 1487:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1488:                     #We do some obsolete checking here
 1489:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1490:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1491:                         my @obsolete=<FILE>;
 1492:                         foreach my $obsolete (@obsolete) {
 1493:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
 1494:                             if($obsolete =~ m|(<copyright>)(default)|) {
 1495:                                 $rights = 1;
 1496:                             }
 1497:                         }
 1498:                     }
 1499:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
 1500:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1501:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
 1502:                     $ulsout.= &escape($tmp).':';
 1503:                 }
 1504:                 closedir(LSDIR);
 1505:             }
 1506:         } else {
 1507:             my @ulsstats=stat($ulsdir);
 1508:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1509:         }
 1510:     } else {
 1511:         $ulsout='no_such_dir';
 1512:    }
 1513:    if ($ulsout eq '') { $ulsout='empty'; }
 1514:    &Reply($client, "$ulsout\n", $userinput); # This supports debug logging.
 1515:    return 1;
 1516: }
 1517: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
 1518: 
 1519: #   Process a reinit request.  Reinit requests that either
 1520: #   lonc or lond be reinitialized so that an updated 
 1521: #   host.tab or domain.tab can be processed.
 1522: #
 1523: # Parameters:
 1524: #      $cmd    - the actual keyword that invoked us.
 1525: #      $tail   - the tail of the request that invoked us.
 1526: #      $client - File descriptor connected to the client
 1527: #  Returns:
 1528: #      1       - Ok to continue processing.
 1529: #      0       - Program should exit
 1530: #  Implicit output:
 1531: #     a reply is sent to the client.
 1532: #
 1533: sub reinit_process_handler {
 1534:     my ($cmd, $tail, $client) = @_;
 1535:    
 1536:     my $userinput = "$cmd:$tail";
 1537:    
 1538:     my $cert = &GetCertificate($userinput);
 1539:     if(&ValidManager($cert)) {
 1540: 	chomp($userinput);
 1541: 	my $reply = &ReinitProcess($userinput);
 1542: 	&Reply( $client,  "$reply\n", $userinput);
 1543:     } else {
 1544: 	&Failure( $client, "refused\n", $userinput);
 1545:     }
 1546:     return 1;
 1547: }
 1548: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
 1549: 
 1550: #  Process the editing script for a table edit operation.
 1551: #  the editing operation must be encrypted and requested by
 1552: #  a manager host.
 1553: #
 1554: # Parameters:
 1555: #      $cmd    - the actual keyword that invoked us.
 1556: #      $tail   - the tail of the request that invoked us.
 1557: #      $client - File descriptor connected to the client
 1558: #  Returns:
 1559: #      1       - Ok to continue processing.
 1560: #      0       - Program should exit
 1561: #  Implicit output:
 1562: #     a reply is sent to the client.
 1563: #
 1564: sub edit_table_handler {
 1565:     my ($command, $tail, $client) = @_;
 1566:    
 1567:     my $userinput = "$command:$tail";
 1568: 
 1569:     my $cert = &GetCertificate($userinput);
 1570:     if(&ValidManager($cert)) {
 1571: 	my($filetype, $script) = split(/:/, $tail);
 1572: 	if (($filetype eq "hosts") || 
 1573: 	    ($filetype eq "domain")) {
 1574: 	    if($script ne "") {
 1575: 		&Reply($client,              # BUGBUG - EditFile
 1576: 		      &EditFile($userinput), #   could fail.
 1577: 		      $userinput);
 1578: 	    } else {
 1579: 		&Failure($client,"refused\n",$userinput);
 1580: 	    }
 1581: 	} else {
 1582: 	    &Failure($client,"refused\n",$userinput);
 1583: 	}
 1584:     } else {
 1585: 	&Failure($client,"refused\n",$userinput);
 1586:     }
 1587:     return 1;
 1588: }
 1589: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
 1590: 
 1591: #
 1592: #   Authenticate a user against the LonCAPA authentication
 1593: #   database.  Note that there are several authentication
 1594: #   possibilities:
 1595: #   - unix     - The user can be authenticated against the unix
 1596: #                password file.
 1597: #   - internal - The user can be authenticated against a purely 
 1598: #                internal per user password file.
 1599: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 1600: #                ticket granting authority.
 1601: #   - user     - The person tailoring LonCAPA can supply a user authentication
 1602: #                mechanism that is per system.
 1603: #
 1604: # Parameters:
 1605: #    $cmd      - The command that got us here.
 1606: #    $tail     - Tail of the command (remaining parameters).
 1607: #    $client   - File descriptor connected to client.
 1608: # Returns
 1609: #     0        - Requested to exit, caller should shut down.
 1610: #     1        - Continue processing.
 1611: # Implicit inputs:
 1612: #    The authentication systems describe above have their own forms of implicit
 1613: #    input into the authentication process that are described above.
 1614: #
 1615: sub authenticate_handler {
 1616:     my ($cmd, $tail, $client) = @_;
 1617: 
 1618:     
 1619:     #  Regenerate the full input line 
 1620:     
 1621:     my $userinput  = $cmd.":".$tail;
 1622:     
 1623:     #  udom    - User's domain.
 1624:     #  uname   - Username.
 1625:     #  upass   - User's password.
 1626:     
 1627:     my ($udom,$uname,$upass)=split(/:/,$tail);
 1628:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass");
 1629:     chomp($upass);
 1630:     $upass=&unescape($upass);
 1631: 
 1632:     my $pwdcorrect = &validate_user($udom, $uname, $upass);
 1633:     if($pwdcorrect) {
 1634: 	&Reply( $client, "authorized\n", $userinput);
 1635: 	#
 1636: 	#  Bad credentials: Failed to authorize
 1637: 	#
 1638:     } else {
 1639: 	&Failure( $client, "non_authorized\n", $userinput);
 1640:     }
 1641: 
 1642:     return 1;
 1643: }
 1644: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
 1645: 
 1646: #
 1647: #   Change a user's password.  Note that this function is complicated by
 1648: #   the fact that a user may be authenticated in more than one way:
 1649: #   At present, we are not able to change the password for all types of
 1650: #   authentication methods.  Only for:
 1651: #      unix    - unix password or shadow passoword style authentication.
 1652: #      local   - Locally written authentication mechanism.
 1653: #   For now, kerb4 and kerb5 password changes are not supported and result
 1654: #   in an error.
 1655: # FUTURE WORK:
 1656: #    Support kerberos passwd changes?
 1657: # Parameters:
 1658: #    $cmd      - The command that got us here.
 1659: #    $tail     - Tail of the command (remaining parameters).
 1660: #    $client   - File descriptor connected to client.
 1661: # Returns
 1662: #     0        - Requested to exit, caller should shut down.
 1663: #     1        - Continue processing.
 1664: # Implicit inputs:
 1665: #    The authentication systems describe above have their own forms of implicit
 1666: #    input into the authentication process that are described above.
 1667: sub change_password_handler {
 1668:     my ($cmd, $tail, $client) = @_;
 1669: 
 1670:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
 1671: 
 1672:     #
 1673:     #  udom  - user's domain.
 1674:     #  uname - Username.
 1675:     #  upass - Current password.
 1676:     #  npass - New password.
 1677:    
 1678:     my ($udom,$uname,$upass,$npass)=split(/:/,$tail);
 1679: 
 1680:     $upass=&unescape($upass);
 1681:     $npass=&unescape($npass);
 1682:     &Debug("Trying to change password for $uname");
 1683: 
 1684:     # First require that the user can be authenticated with their
 1685:     # old password:
 1686: 
 1687:     my $validated = &validate_user($udom, $uname, $upass);
 1688:     if($validated) {
 1689: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
 1690: 	
 1691: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 1692: 	if ($howpwd eq 'internal') {
 1693: 	    &Debug("internal auth");
 1694: 	    my $salt=time;
 1695: 	    $salt=substr($salt,6,2);
 1696: 	    my $ncpass=crypt($npass,$salt);
 1697: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
 1698: 		&logthis("Result of password change for "
 1699: 			 ."$uname: pwchange_success");
 1700: 		&Reply($client, "ok\n", $userinput);
 1701: 	    } else {
 1702: 		&logthis("Unable to open $uname passwd "               
 1703: 			 ."to change password");
 1704: 		&Failure( $client, "non_authorized\n",$userinput);
 1705: 	    }
 1706: 	} elsif ($howpwd eq 'unix') {
 1707: 	    my $result = &change_unix_password($uname, $npass);
 1708: 	    &logthis("Result of password change for $uname: ".
 1709: 		     $result);
 1710: 	    &Reply($client, "$result\n", $userinput);
 1711: 	} else {
 1712: 	    # this just means that the current password mode is not
 1713: 	    # one we know how to change (e.g the kerberos auth modes or
 1714: 	    # locally written auth handler).
 1715: 	    #
 1716: 	    &Failure( $client, "auth_mode_error\n", $userinput);
 1717: 	}  
 1718: 	
 1719:     } else {
 1720: 	&Failure( $client, "non_authorized\n", $userinput);
 1721:     }
 1722: 
 1723:     return 1;
 1724: }
 1725: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
 1726: 
 1727: #
 1728: #   Create a new user.  User in this case means a lon-capa user.
 1729: #   The user must either already exist in some authentication realm
 1730: #   like kerberos or the /etc/passwd.  If not, a user completely local to
 1731: #   this loncapa system is created.
 1732: #
 1733: # Parameters:
 1734: #    $cmd      - The command that got us here.
 1735: #    $tail     - Tail of the command (remaining parameters).
 1736: #    $client   - File descriptor connected to client.
 1737: # Returns
 1738: #     0        - Requested to exit, caller should shut down.
 1739: #     1        - Continue processing.
 1740: # Implicit inputs:
 1741: #    The authentication systems describe above have their own forms of implicit
 1742: #    input into the authentication process that are described above.
 1743: sub add_user_handler {
 1744: 
 1745:     my ($cmd, $tail, $client) = @_;
 1746: 
 1747: 
 1748:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 1749:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
 1750: 
 1751:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
 1752: 
 1753: 
 1754:     if($udom eq $currentdomainid) { # Reject new users for other domains...
 1755: 	
 1756: 	my $oldumask=umask(0077);
 1757: 	chomp($npass);
 1758: 	$npass=&unescape($npass);
 1759: 	my $passfilename  = &password_path($udom, $uname);
 1760: 	&Debug("Password file created will be:".$passfilename);
 1761: 	if (-e $passfilename) {
 1762: 	    &Failure( $client, "already_exists\n", $userinput);
 1763: 	} else {
 1764: 	    my $fperror='';
 1765: 	    if (!&mkpath($passfilename)) {
 1766: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
 1767: 		    ."makeuser";
 1768: 	    }
 1769: 	    unless ($fperror) {
 1770: 		my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
 1771: 		&Reply($client, $result, $userinput);     #BUGBUG - could be fail
 1772: 	    } else {
 1773: 		&Failure($client, "$fperror\n", $userinput);
 1774: 	    }
 1775: 	}
 1776: 	umask($oldumask);
 1777:     }  else {
 1778: 	&Failure($client, "not_right_domain\n",
 1779: 		$userinput);	# Even if we are multihomed.
 1780:     
 1781:     }
 1782:     return 1;
 1783: 
 1784: }
 1785: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
 1786: 
 1787: #
 1788: #   Change the authentication method of a user.  Note that this may
 1789: #   also implicitly change the user's password if, for example, the user is
 1790: #   joining an existing authentication realm.  Known authentication realms at
 1791: #   this time are:
 1792: #    internal   - Purely internal password file (only loncapa knows this user)
 1793: #    local      - Institutionally written authentication module.
 1794: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
 1795: #    kerb4      - kerberos version 4
 1796: #    kerb5      - kerberos version 5
 1797: #
 1798: # Parameters:
 1799: #    $cmd      - The command that got us here.
 1800: #    $tail     - Tail of the command (remaining parameters).
 1801: #    $client   - File descriptor connected to client.
 1802: # Returns
 1803: #     0        - Requested to exit, caller should shut down.
 1804: #     1        - Continue processing.
 1805: # Implicit inputs:
 1806: #    The authentication systems describe above have their own forms of implicit
 1807: #    input into the authentication process that are described above.
 1808: # NOTE:
 1809: #   This is also used to change the authentication credential values (e.g. passwd).
 1810: #   
 1811: #
 1812: sub change_authentication_handler {
 1813: 
 1814:     my ($cmd, $tail, $client) = @_;
 1815:    
 1816:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
 1817: 
 1818:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 1819:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
 1820:     if ($udom ne $currentdomainid) {
 1821: 	&Failure( $client, "not_right_domain\n", $client);
 1822:     } else {
 1823: 	
 1824: 	chomp($npass);
 1825: 	
 1826: 	$npass=&unescape($npass);
 1827: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
 1828: 	my $passfilename = &password_path($udom, $uname);
 1829: 	if ($passfilename) {	# Not allowed to create a new user!!
 1830: 	    # If just changing the unix passwd. need to arrange to run
 1831: 	    # passwd since otherwise make_passwd_file will run
 1832: 	    # lcuseradd which fails if an account already exists
 1833: 	    # (to prevent an unscrupulous LONCAPA admin from stealing
 1834: 	    # an existing account by overwriting it as a LonCAPA account).
 1835: 
 1836: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
 1837: 		my $result = &change_unix_password($uname, $npass);
 1838: 		&logthis("Result of password change for $uname: ".$result);
 1839: 		if ($result eq "ok") {
 1840: 		    &Reply($client, "$result\n")
 1841: 		} else {
 1842: 		    &Failure($client, "$result\n");
 1843: 		}
 1844: 	    } else {
 1845: 		my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
 1846: 		#
 1847: 		#  If the current auth mode is internal, and the old auth mode was
 1848: 		#  unix, or krb*,  and the user is an author for this domain,
 1849: 		#  re-run manage_permissions for that role in order to be able
 1850: 		#  to take ownership of the construction space back to www:www
 1851: 		#
 1852: 		
 1853: 		
 1854: 		if( (($oldauth =~ /^unix/) && ($umode eq "internal")) ||
 1855: 		    (($oldauth =~ /^internal/) && ($umode eq "unix")) ) { 
 1856: 		    if(&is_author($udom, $uname)) {
 1857: 			&Debug(" Need to manage author permissions...");
 1858: 			&manage_permissions("/$udom/_au", $udom, $uname, "$umode:");
 1859: 		    }
 1860: 		}
 1861: 		&Reply($client, $result, $userinput);
 1862: 	    }
 1863: 	       
 1864: 
 1865: 	} else {	       
 1866: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
 1867: 	}
 1868:     }
 1869:     return 1;
 1870: }
 1871: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
 1872: 
 1873: #
 1874: #   Determines if this is the home server for a user.  The home server
 1875: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
 1876: #   to do is determine if this file exists.
 1877: #
 1878: # Parameters:
 1879: #    $cmd      - The command that got us here.
 1880: #    $tail     - Tail of the command (remaining parameters).
 1881: #    $client   - File descriptor connected to client.
 1882: # Returns
 1883: #     0        - Requested to exit, caller should shut down.
 1884: #     1        - Continue processing.
 1885: # Implicit inputs:
 1886: #    The authentication systems describe above have their own forms of implicit
 1887: #    input into the authentication process that are described above.
 1888: #
 1889: sub is_home_handler {
 1890:     my ($cmd, $tail, $client) = @_;
 1891:    
 1892:     my $userinput  = "$cmd:$tail";
 1893:    
 1894:     my ($udom,$uname)=split(/:/,$tail);
 1895:     chomp($uname);
 1896:     my $passfile = &password_filename($udom, $uname);
 1897:     if($passfile) {
 1898: 	&Reply( $client, "found\n", $userinput);
 1899:     } else {
 1900: 	&Failure($client, "not_found\n", $userinput);
 1901:     }
 1902:     return 1;
 1903: }
 1904: &register_handler("home", \&is_home_handler, 0,1,0);
 1905: 
 1906: #
 1907: #   Process an update request for a resource?? I think what's going on here is
 1908: #   that a resource has been modified that we hold a subscription to.
 1909: #   If the resource is not local, then we must update, or at least invalidate our
 1910: #   cached copy of the resource. 
 1911: #   FUTURE WORK:
 1912: #      I need to look at this logic carefully.  My druthers would be to follow
 1913: #      typical caching logic, and simple invalidate the cache, drop any subscription
 1914: #      an let the next fetch start the ball rolling again... however that may
 1915: #      actually be more difficult than it looks given the complex web of
 1916: #      proxy servers.
 1917: # Parameters:
 1918: #    $cmd      - The command that got us here.
 1919: #    $tail     - Tail of the command (remaining parameters).
 1920: #    $client   - File descriptor connected to client.
 1921: # Returns
 1922: #     0        - Requested to exit, caller should shut down.
 1923: #     1        - Continue processing.
 1924: # Implicit inputs:
 1925: #    The authentication systems describe above have their own forms of implicit
 1926: #    input into the authentication process that are described above.
 1927: #
 1928: sub update_resource_handler {
 1929: 
 1930:     my ($cmd, $tail, $client) = @_;
 1931:    
 1932:     my $userinput = "$cmd:$tail";
 1933:    
 1934:     my $fname= $tail;		# This allows interactive testing
 1935: 
 1936: 
 1937:     my $ownership=ishome($fname);
 1938:     if ($ownership eq 'not_owner') {
 1939: 	if (-e $fname) {
 1940: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
 1941: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
 1942: 	    my $now=time;
 1943: 	    my $since=$now-$atime;
 1944: 	    if ($since>$perlvar{'lonExpire'}) {
 1945: 		my $reply=&reply("unsub:$fname","$clientname");
 1946: 		&devalidate_meta_cache($fname);
 1947: 		unlink("$fname");
 1948: 	    } else {
 1949: 		my $transname="$fname.in.transfer";
 1950: 		my $remoteurl=&reply("sub:$fname","$clientname");
 1951: 		my $response;
 1952: 		alarm(120);
 1953: 		{
 1954: 		    my $ua=new LWP::UserAgent;
 1955: 		    my $request=new HTTP::Request('GET',"$remoteurl");
 1956: 		    $response=$ua->request($request,$transname);
 1957: 		}
 1958: 		alarm(0);
 1959: 		if ($response->is_error()) {
 1960: 		    unlink($transname);
 1961: 		    my $message=$response->status_line;
 1962: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
 1963: 		} else {
 1964: 		    if ($remoteurl!~/\.meta$/) {
 1965: 			alarm(120);
 1966: 			{
 1967: 			    my $ua=new LWP::UserAgent;
 1968: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1969: 			    my $mresponse=$ua->request($mrequest,$fname.'.meta');
 1970: 			    if ($mresponse->is_error()) {
 1971: 				unlink($fname.'.meta');
 1972: 			    }
 1973: 			}
 1974: 			alarm(0);
 1975: 		    }
 1976: 		    rename($transname,$fname);
 1977: 		    &devalidate_meta_cache($fname);
 1978: 		}
 1979: 	    }
 1980: 	    &Reply( $client, "ok\n", $userinput);
 1981: 	} else {
 1982: 	    &Failure($client, "not_found\n", $userinput);
 1983: 	}
 1984:     } else {
 1985: 	&Failure($client, "rejected\n", $userinput);
 1986:     }
 1987:     return 1;
 1988: }
 1989: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
 1990: 
 1991: sub devalidate_meta_cache {
 1992:     my ($url) = @_;
 1993:     use Cache::Memcached;
 1994:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 1995:     $url = &declutter($url);
 1996:     $url =~ s-\.meta$--;
 1997:     my $id = &escape('meta:'.$url);
 1998:     $memcache->delete($id);
 1999: }
 2000: 
 2001: sub declutter {
 2002:     my $thisfn=shift;
 2003:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 2004:     $thisfn=~s/^\///;
 2005:     $thisfn=~s|^adm/wrapper/||;
 2006:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 2007:     $thisfn=~s/^res\///;
 2008:     $thisfn=~s/\?.+$//;
 2009:     return $thisfn;
 2010: }
 2011: #
 2012: #   Fetch a user file from a remote server to the user's home directory
 2013: #   userfiles subdir.
 2014: # Parameters:
 2015: #    $cmd      - The command that got us here.
 2016: #    $tail     - Tail of the command (remaining parameters).
 2017: #    $client   - File descriptor connected to client.
 2018: # Returns
 2019: #     0        - Requested to exit, caller should shut down.
 2020: #     1        - Continue processing.
 2021: #
 2022: sub fetch_user_file_handler {
 2023: 
 2024:     my ($cmd, $tail, $client) = @_;
 2025: 
 2026:     my $userinput = "$cmd:$tail";
 2027:     my $fname           = $tail;
 2028:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2029:     my $udir=&propath($udom,$uname).'/userfiles';
 2030:     unless (-e $udir) {
 2031: 	mkdir($udir,0770); 
 2032:     }
 2033:     Debug("fetch user file for $fname");
 2034:     if (-e $udir) {
 2035: 	$ufile=~s/^[\.\~]+//;
 2036: 
 2037: 	# IF necessary, create the path right down to the file.
 2038: 	# Note that any regular files in the way of this path are
 2039: 	# wiped out to deal with some earlier folly of mine.
 2040: 
 2041: 	if (!&mkpath($udir.'/'.$ufile)) {
 2042: 	    &Failure($client, "unable_to_create\n", $userinput);	    
 2043: 	}
 2044: 
 2045: 	my $destname=$udir.'/'.$ufile;
 2046: 	my $transname=$udir.'/'.$ufile.'.in.transit';
 2047: 	my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
 2048: 	my $response;
 2049: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
 2050: 	alarm(120);
 2051: 	{
 2052: 	    my $ua=new LWP::UserAgent;
 2053: 	    my $request=new HTTP::Request('GET',"$remoteurl");
 2054: 	    $response=$ua->request($request,$transname);
 2055: 	}
 2056: 	alarm(0);
 2057: 	if ($response->is_error()) {
 2058: 	    unlink($transname);
 2059: 	    my $message=$response->status_line;
 2060: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
 2061: 	    &Failure($client, "failed\n", $userinput);
 2062: 	} else {
 2063: 	    Debug("Renaming $transname to $destname");
 2064: 	    if (!rename($transname,$destname)) {
 2065: 		&logthis("Unable to move $transname to $destname");
 2066: 		unlink($transname);
 2067: 		&Failure($client, "failed\n", $userinput);
 2068: 	    } else {
 2069: 		&Reply($client, "ok\n", $userinput);
 2070: 	    }
 2071: 	}   
 2072:     } else {
 2073: 	&Failure($client, "not_home\n", $userinput);
 2074:     }
 2075:     return 1;
 2076: }
 2077: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
 2078: 
 2079: #
 2080: #   Remove a file from a user's home directory userfiles subdirectory.
 2081: # Parameters:
 2082: #    cmd   - the Lond request keyword that got us here.
 2083: #    tail  - the part of the command past the keyword.
 2084: #    client- File descriptor connected with the client.
 2085: #
 2086: # Returns:
 2087: #    1    - Continue processing.
 2088: sub remove_user_file_handler {
 2089:     my ($cmd, $tail, $client) = @_;
 2090: 
 2091:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2092: 
 2093:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2094:     if ($ufile =~m|/\.\./|) {
 2095: 	# any files paths with /../ in them refuse 
 2096: 	# to deal with
 2097: 	&Failure($client, "refused\n", "$cmd:$tail");
 2098:     } else {
 2099: 	my $udir = &propath($udom,$uname);
 2100: 	if (-e $udir) {
 2101: 	    my $file=$udir.'/userfiles/'.$ufile;
 2102: 	    if (-e $file) {
 2103: 		#
 2104: 		#   If the file is a regular file unlink is fine...
 2105: 		#   However it's possible the client wants a dir.
 2106: 		#   removed, in which case rmdir is more approprate:
 2107: 		#
 2108: 	        if (-f $file){
 2109: 		    unlink($file);
 2110: 		} elsif(-d $file) {
 2111: 		    rmdir($file);
 2112: 		}
 2113: 		if (-e $file) {
 2114: 		    #  File is still there after we deleted it ?!?
 2115: 
 2116: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2117: 		} else {
 2118: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2119: 		}
 2120: 	    } else {
 2121: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2122: 	    }
 2123: 	} else {
 2124: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2125: 	}
 2126:     }
 2127:     return 1;
 2128: }
 2129: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
 2130: 
 2131: #
 2132: #   make a directory in a user's home directory userfiles subdirectory.
 2133: # Parameters:
 2134: #    cmd   - the Lond request keyword that got us here.
 2135: #    tail  - the part of the command past the keyword.
 2136: #    client- File descriptor connected with the client.
 2137: #
 2138: # Returns:
 2139: #    1    - Continue processing.
 2140: sub mkdir_user_file_handler {
 2141:     my ($cmd, $tail, $client) = @_;
 2142: 
 2143:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 2144:     $dir=&unescape($dir);
 2145:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
 2146:     if ($ufile =~m|/\.\./|) {
 2147: 	# any files paths with /../ in them refuse 
 2148: 	# to deal with
 2149: 	&Failure($client, "refused\n", "$cmd:$tail");
 2150:     } else {
 2151: 	my $udir = &propath($udom,$uname);
 2152: 	if (-e $udir) {
 2153: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
 2154: 	    if (!&mkpath($newdir)) {
 2155: 		&Failure($client, "failed\n", "$cmd:$tail");
 2156: 	    }
 2157: 	    &Reply($client, "ok\n", "$cmd:$tail");
 2158: 	} else {
 2159: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2160: 	}
 2161:     }
 2162:     return 1;
 2163: }
 2164: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
 2165: 
 2166: #
 2167: #   rename a file in a user's home directory userfiles subdirectory.
 2168: # Parameters:
 2169: #    cmd   - the Lond request keyword that got us here.
 2170: #    tail  - the part of the command past the keyword.
 2171: #    client- File descriptor connected with the client.
 2172: #
 2173: # Returns:
 2174: #    1    - Continue processing.
 2175: sub rename_user_file_handler {
 2176:     my ($cmd, $tail, $client) = @_;
 2177: 
 2178:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
 2179:     $old=&unescape($old);
 2180:     $new=&unescape($new);
 2181:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
 2182: 	# any files paths with /../ in them refuse to deal with
 2183: 	&Failure($client, "refused\n", "$cmd:$tail");
 2184:     } else {
 2185: 	my $udir = &propath($udom,$uname);
 2186: 	if (-e $udir) {
 2187: 	    my $oldfile=$udir.'/userfiles/'.$old;
 2188: 	    my $newfile=$udir.'/userfiles/'.$new;
 2189: 	    if (-e $newfile) {
 2190: 		&Failure($client, "exists\n", "$cmd:$tail");
 2191: 	    } elsif (! -e $oldfile) {
 2192: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2193: 	    } else {
 2194: 		if (!rename($oldfile,$newfile)) {
 2195: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2196: 		} else {
 2197: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2198: 		}
 2199: 	    }
 2200: 	} else {
 2201: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2202: 	}
 2203:     }
 2204:     return 1;
 2205: }
 2206: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
 2207: 
 2208: #
 2209: #  Authenticate access to a user file by checking that the token the user's 
 2210: #  passed also exists in their session file
 2211: #
 2212: # Parameters:
 2213: #   cmd      - The request keyword that dispatched to tus.
 2214: #   tail     - The tail of the request (colon separated parameters).
 2215: #   client   - Filehandle open on the client.
 2216: # Return:
 2217: #    1.
 2218: sub token_auth_user_file_handler {
 2219:     my ($cmd, $tail, $client) = @_;
 2220: 
 2221:     my ($fname, $session) = split(/:/, $tail);
 2222:     
 2223:     chomp($session);
 2224:     my $reply="non_auth\n";
 2225:     if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
 2226: 	     $session.'.id')) {
 2227: 	while (my $line=<ENVIN>) {
 2228: 	    if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply="ok\n"; }
 2229: 	}
 2230: 	close(ENVIN);
 2231: 	&Reply($client, $reply, "$cmd:$tail");
 2232:     } else {
 2233: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
 2234:     }
 2235:     return 1;
 2236: 
 2237: }
 2238: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
 2239: 
 2240: #
 2241: #   Unsubscribe from a resource.
 2242: #
 2243: # Parameters:
 2244: #    $cmd      - The command that got us here.
 2245: #    $tail     - Tail of the command (remaining parameters).
 2246: #    $client   - File descriptor connected to client.
 2247: # Returns
 2248: #     0        - Requested to exit, caller should shut down.
 2249: #     1        - Continue processing.
 2250: #
 2251: sub unsubscribe_handler {
 2252:     my ($cmd, $tail, $client) = @_;
 2253: 
 2254:     my $userinput= "$cmd:$tail";
 2255:     
 2256:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
 2257: 
 2258:     &Debug("Unsubscribing $fname");
 2259:     if (-e $fname) {
 2260: 	&Debug("Exists");
 2261: 	&Reply($client, &unsub($fname,$clientip), $userinput);
 2262:     } else {
 2263: 	&Failure($client, "not_found\n", $userinput);
 2264:     }
 2265:     return 1;
 2266: }
 2267: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
 2268: 
 2269: #   Subscribe to a resource
 2270: #
 2271: # Parameters:
 2272: #    $cmd      - The command that got us here.
 2273: #    $tail     - Tail of the command (remaining parameters).
 2274: #    $client   - File descriptor connected to client.
 2275: # Returns
 2276: #     0        - Requested to exit, caller should shut down.
 2277: #     1        - Continue processing.
 2278: #
 2279: sub subscribe_handler {
 2280:     my ($cmd, $tail, $client)= @_;
 2281: 
 2282:     my $userinput  = "$cmd:$tail";
 2283: 
 2284:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
 2285: 
 2286:     return 1;
 2287: }
 2288: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
 2289: 
 2290: #
 2291: #   Determine the version of a resource (?) Or is it return
 2292: #   the top version of the resource?  Not yet clear from the
 2293: #   code in currentversion.
 2294: #
 2295: # Parameters:
 2296: #    $cmd      - The command that got us here.
 2297: #    $tail     - Tail of the command (remaining parameters).
 2298: #    $client   - File descriptor connected to client.
 2299: # Returns
 2300: #     0        - Requested to exit, caller should shut down.
 2301: #     1        - Continue processing.
 2302: #
 2303: sub current_version_handler {
 2304:     my ($cmd, $tail, $client) = @_;
 2305: 
 2306:     my $userinput= "$cmd:$tail";
 2307:    
 2308:     my $fname   = $tail;
 2309:     &Reply( $client, &currentversion($fname)."\n", $userinput);
 2310:     return 1;
 2311: 
 2312: }
 2313: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
 2314: 
 2315: #  Make an entry in a user's activity log.
 2316: #
 2317: # Parameters:
 2318: #    $cmd      - The command that got us here.
 2319: #    $tail     - Tail of the command (remaining parameters).
 2320: #    $client   - File descriptor connected to client.
 2321: # Returns
 2322: #     0        - Requested to exit, caller should shut down.
 2323: #     1        - Continue processing.
 2324: #
 2325: sub activity_log_handler {
 2326:     my ($cmd, $tail, $client) = @_;
 2327: 
 2328: 
 2329:     my $userinput= "$cmd:$tail";
 2330: 
 2331:     my ($udom,$uname,$what)=split(/:/,$tail);
 2332:     chomp($what);
 2333:     my $proname=&propath($udom,$uname);
 2334:     my $now=time;
 2335:     my $hfh;
 2336:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 2337: 	print $hfh "$now:$clientname:$what\n";
 2338: 	&Reply( $client, "ok\n", $userinput); 
 2339:     } else {
 2340: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
 2341: 		 ."while attempting log\n", 
 2342: 		 $userinput);
 2343:     }
 2344: 
 2345:     return 1;
 2346: }
 2347: &register_handler("log", \&activity_log_handler, 0, 1, 0);
 2348: 
 2349: #
 2350: #   Put a namespace entry in a user profile hash.
 2351: #   My druthers would be for this to be an encrypted interaction too.
 2352: #   anything that might be an inadvertent covert channel about either
 2353: #   user authentication or user personal information....
 2354: #
 2355: # Parameters:
 2356: #    $cmd      - The command that got us here.
 2357: #    $tail     - Tail of the command (remaining parameters).
 2358: #    $client   - File descriptor connected to client.
 2359: # Returns
 2360: #     0        - Requested to exit, caller should shut down.
 2361: #     1        - Continue processing.
 2362: #
 2363: sub put_user_profile_entry {
 2364:     my ($cmd, $tail, $client)  = @_;
 2365: 
 2366:     my $userinput = "$cmd:$tail";
 2367:     
 2368:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 2369:     if ($namespace ne 'roles') {
 2370: 	chomp($what);
 2371: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2372: 				  &GDBM_WRCREAT(),"P",$what);
 2373: 	if($hashref) {
 2374: 	    my @pairs=split(/\&/,$what);
 2375: 	    foreach my $pair (@pairs) {
 2376: 		my ($key,$value)=split(/=/,$pair);
 2377: 		$hashref->{$key}=$value;
 2378: 	    }
 2379: 	    if (untie(%$hashref)) {
 2380: 		&Reply( $client, "ok\n", $userinput);
 2381: 	    } else {
 2382: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2383: 			"while attempting put\n", 
 2384: 			$userinput);
 2385: 	    }
 2386: 	} else {
 2387: 	    &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
 2388: 		     "while attempting put\n", $userinput);
 2389: 	}
 2390:     } else {
 2391:         &Failure( $client, "refused\n", $userinput);
 2392:     }
 2393:     
 2394:     return 1;
 2395: }
 2396: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
 2397: 
 2398: #   Put a piece of new data in hash, returns error if entry already exists
 2399: # Parameters:
 2400: #    $cmd      - The command that got us here.
 2401: #    $tail     - Tail of the command (remaining parameters).
 2402: #    $client   - File descriptor connected to client.
 2403: # Returns
 2404: #     0        - Requested to exit, caller should shut down.
 2405: #     1        - Continue processing.
 2406: #
 2407: sub newput_user_profile_entry {
 2408:     my ($cmd, $tail, $client)  = @_;
 2409: 
 2410:     my $userinput = "$cmd:$tail";
 2411: 
 2412:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 2413:     if ($namespace eq 'roles') {
 2414:         &Failure( $client, "refused\n", $userinput);
 2415: 	return 1;
 2416:     }
 2417: 
 2418:     chomp($what);
 2419: 
 2420:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2421: 				 &GDBM_WRCREAT(),"N",$what);
 2422:     if(!$hashref) {
 2423: 	&Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
 2424: 		  "while attempting put\n", $userinput);
 2425: 	return 1;
 2426:     }
 2427: 
 2428:     my @pairs=split(/\&/,$what);
 2429:     foreach my $pair (@pairs) {
 2430: 	my ($key,$value)=split(/=/,$pair);
 2431: 	if (exists($hashref->{$key})) {
 2432: 	    &Failure($client, "key_exists: ".$key."\n",$userinput);
 2433: 	    return 1;
 2434: 	}
 2435:     }
 2436: 
 2437:     foreach my $pair (@pairs) {
 2438: 	my ($key,$value)=split(/=/,$pair);
 2439: 	$hashref->{$key}=$value;
 2440:     }
 2441: 
 2442:     if (untie(%$hashref)) {
 2443: 	&Reply( $client, "ok\n", $userinput);
 2444:     } else {
 2445: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2446: 		 "while attempting put\n", 
 2447: 		 $userinput);
 2448:     }
 2449:     return 1;
 2450: }
 2451: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
 2452: 
 2453: # 
 2454: #   Increment a profile entry in the user history file.
 2455: #   The history contains keyword value pairs.  In this case,
 2456: #   The value itself is a pair of numbers.  The first, the current value
 2457: #   the second an increment that this function applies to the current
 2458: #   value.
 2459: #
 2460: # Parameters:
 2461: #    $cmd      - The command that got us here.
 2462: #    $tail     - Tail of the command (remaining parameters).
 2463: #    $client   - File descriptor connected to client.
 2464: # Returns
 2465: #     0        - Requested to exit, caller should shut down.
 2466: #     1        - Continue processing.
 2467: #
 2468: sub increment_user_value_handler {
 2469:     my ($cmd, $tail, $client) = @_;
 2470:     
 2471:     my $userinput   = "$cmd:$tail";
 2472:     
 2473:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 2474:     if ($namespace ne 'roles') {
 2475:         chomp($what);
 2476: 	my $hashref = &tie_user_hash($udom, $uname,
 2477: 				     $namespace, &GDBM_WRCREAT(),
 2478: 				     "P",$what);
 2479: 	if ($hashref) {
 2480: 	    my @pairs=split(/\&/,$what);
 2481: 	    foreach my $pair (@pairs) {
 2482: 		my ($key,$value)=split(/=/,$pair);
 2483:                 $value = &unescape($value);
 2484: 		# We could check that we have a number...
 2485: 		if (! defined($value) || $value eq '') {
 2486: 		    $value = 1;
 2487: 		}
 2488: 		$hashref->{$key}+=$value;
 2489:                 if ($namespace eq 'nohist_resourcetracker') {
 2490:                     if ($hashref->{$key} < 0) {
 2491:                         $hashref->{$key} = 0;
 2492:                     }
 2493:                 }
 2494: 	    }
 2495: 	    if (untie(%$hashref)) {
 2496: 		&Reply( $client, "ok\n", $userinput);
 2497: 	    } else {
 2498: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2499: 			 "while attempting inc\n", $userinput);
 2500: 	    }
 2501: 	} else {
 2502: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2503: 		     "while attempting inc\n", $userinput);
 2504: 	}
 2505:     } else {
 2506: 	&Failure($client, "refused\n", $userinput);
 2507:     }
 2508:     
 2509:     return 1;
 2510: }
 2511: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 2512: 
 2513: #
 2514: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 2515: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 2516: #   for a person grants the permissions packaged with that role
 2517: #   to that user when the role is selected.
 2518: #
 2519: # Parameters:
 2520: #    $cmd       - The command string (rolesput).
 2521: #    $tail      - The remainder of the request line.  For rolesput this
 2522: #                 consists of a colon separated list that contains:
 2523: #                 The domain and user that is granting the role (logged).
 2524: #                 The domain and user that is getting the role.
 2525: #                 The roles being granted as a set of & separated pairs.
 2526: #                 each pair a key value pair.
 2527: #    $client    - File descriptor connected to the client.
 2528: # Returns:
 2529: #     0         - If the daemon should exit
 2530: #     1         - To continue processing.
 2531: #
 2532: #
 2533: sub roles_put_handler {
 2534:     my ($cmd, $tail, $client) = @_;
 2535: 
 2536:     my $userinput  = "$cmd:$tail";
 2537: 
 2538:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 2539:     
 2540: 
 2541:     my $namespace='roles';
 2542:     chomp($what);
 2543:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2544: 				 &GDBM_WRCREAT(), "P",
 2545: 				 "$exedom:$exeuser:$what");
 2546:     #
 2547:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 2548:     #  handle is open for the minimal amount of time.  Since the flush
 2549:     #  is done on close this improves the chances the log will be an un-
 2550:     #  corrupted ordered thing.
 2551:     if ($hashref) {
 2552: 	my $pass_entry = &get_auth_type($udom, $uname);
 2553: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
 2554: 	$auth_type = $auth_type.":";
 2555: 	my @pairs=split(/\&/,$what);
 2556: 	foreach my $pair (@pairs) {
 2557: 	    my ($key,$value)=split(/=/,$pair);
 2558: 	    &manage_permissions($key, $udom, $uname,
 2559: 			       $auth_type);
 2560: 	    $hashref->{$key}=$value;
 2561: 	}
 2562: 	if (untie($hashref)) {
 2563: 	    &Reply($client, "ok\n", $userinput);
 2564: 	} else {
 2565: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2566: 		     "while attempting rolesput\n", $userinput);
 2567: 	}
 2568:     } else {
 2569: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2570: 		 "while attempting rolesput\n", $userinput);
 2571:     }
 2572:     return 1;
 2573: }
 2574: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 2575: 
 2576: #
 2577: #   Deletes (removes) a role for a user.   This is equivalent to removing
 2578: #  a permissions package associated with the role from the user's profile.
 2579: #
 2580: # Parameters:
 2581: #     $cmd                 - The command (rolesdel)
 2582: #     $tail                - The remainder of the request line. This consists
 2583: #                             of:
 2584: #                             The domain and user requesting the change (logged)
 2585: #                             The domain and user being changed.
 2586: #                             The roles being revoked.  These are shipped to us
 2587: #                             as a bunch of & separated role name keywords.
 2588: #     $client              - The file handle open on the client.
 2589: # Returns:
 2590: #     1                    - Continue processing
 2591: #     0                    - Exit.
 2592: #
 2593: sub roles_delete_handler {
 2594:     my ($cmd, $tail, $client)  = @_;
 2595: 
 2596:     my $userinput    = "$cmd:$tail";
 2597:    
 2598:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 2599:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 2600: 	   "what = ".$what);
 2601:     my $namespace='roles';
 2602:     chomp($what);
 2603:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2604: 				 &GDBM_WRCREAT(), "D",
 2605: 				 "$exedom:$exeuser:$what");
 2606:     
 2607:     if ($hashref) {
 2608: 	my @rolekeys=split(/\&/,$what);
 2609: 	
 2610: 	foreach my $key (@rolekeys) {
 2611: 	    delete $hashref->{$key};
 2612: 	}
 2613: 	if (untie(%$hashref)) {
 2614: 	    &Reply($client, "ok\n", $userinput);
 2615: 	} else {
 2616: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2617: 		     "while attempting rolesdel\n", $userinput);
 2618: 	}
 2619:     } else {
 2620:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2621: 		 "while attempting rolesdel\n", $userinput);
 2622:     }
 2623:     
 2624:     return 1;
 2625: }
 2626: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 2627: 
 2628: # Unencrypted get from a user's profile database.  See 
 2629: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 2630: # This function retrieves a keyed item from a specific named database in the
 2631: # user's directory.
 2632: #
 2633: # Parameters:
 2634: #   $cmd             - Command request keyword (get).
 2635: #   $tail            - Tail of the command.  This is a colon separated list
 2636: #                      consisting of the domain and username that uniquely
 2637: #                      identifies the profile,
 2638: #                      The 'namespace' which selects the gdbm file to 
 2639: #                      do the lookup in, 
 2640: #                      & separated list of keys to lookup.  Note that
 2641: #                      the values are returned as an & separated list too.
 2642: #   $client          - File descriptor open on the client.
 2643: # Returns:
 2644: #   1       - Continue processing.
 2645: #   0       - Exit.
 2646: #
 2647: sub get_profile_entry {
 2648:     my ($cmd, $tail, $client) = @_;
 2649: 
 2650:     my $userinput= "$cmd:$tail";
 2651:    
 2652:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 2653:     chomp($what);
 2654: 
 2655:     my $replystring = read_profile($udom, $uname, $namespace, $what);
 2656:     my ($first) = split(/:/,$replystring);
 2657:     if($first ne "error") {
 2658: 	&Reply($client, "$replystring\n", $userinput);
 2659:     } else {
 2660: 	&Failure($client, $replystring." while attempting get\n", $userinput);
 2661:     }
 2662:     return 1;
 2663: 
 2664: 
 2665: }
 2666: &register_handler("get", \&get_profile_entry, 0,1,0);
 2667: 
 2668: #
 2669: #  Process the encrypted get request.  Note that the request is sent
 2670: #  in clear, but the reply is encrypted.  This is a small covert channel:
 2671: #  information about the sensitive keys is given to the snooper.  Just not
 2672: #  information about the values of the sensitive key.  Hmm if I wanted to
 2673: #  know these I'd snoop for the egets. Get the profile item names from them
 2674: #  and then issue a get for them since there's no enforcement of the
 2675: #  requirement of an encrypted get for particular profile items.  If I
 2676: #  were re-doing this, I'd force the request to be encrypted as well as the
 2677: #  reply.  I'd also just enforce encrypted transactions for all gets since
 2678: #  that would prevent any covert channel snooping.
 2679: #
 2680: #  Parameters:
 2681: #     $cmd               - Command keyword of request (eget).
 2682: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
 2683: #     $client            - File open on the client.
 2684: #  Returns:
 2685: #     1      - Continue processing
 2686: #     0      - server should exit.
 2687: sub get_profile_entry_encrypted {
 2688:     my ($cmd, $tail, $client) = @_;
 2689: 
 2690:     my $userinput = "$cmd:$tail";
 2691:    
 2692:     my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
 2693:     chomp($what);
 2694:     my $qresult = read_profile($udom, $uname, $namespace, $what);
 2695:     my ($first) = split(/:/, $qresult);
 2696:     if($first ne "error") {
 2697: 	
 2698: 	if ($cipher) {
 2699: 	    my $cmdlength=length($qresult);
 2700: 	    $qresult.="         ";
 2701: 	    my $encqresult='';
 2702: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 2703: 		$encqresult.= unpack("H16", 
 2704: 				     $cipher->encrypt(substr($qresult,
 2705: 							     $encidx,
 2706: 							     8)));
 2707: 	    }
 2708: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 2709: 	} else {
 2710: 		&Failure( $client, "error:no_key\n", $userinput);
 2711: 	    }
 2712:     } else {
 2713: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
 2714: 
 2715:     }
 2716:     
 2717:     return 1;
 2718: }
 2719: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
 2720: 
 2721: #
 2722: #   Deletes a key in a user profile database.
 2723: #   
 2724: #   Parameters:
 2725: #       $cmd                  - Command keyword (del).
 2726: #       $tail                 - Command tail.  IN this case a colon
 2727: #                               separated list containing:
 2728: #                               The domain and user that identifies uniquely
 2729: #                               the identity of the user.
 2730: #                               The profile namespace (name of the profile
 2731: #                               database file).
 2732: #                               & separated list of keywords to delete.
 2733: #       $client              - File open on client socket.
 2734: # Returns:
 2735: #     1   - Continue processing
 2736: #     0   - Exit server.
 2737: #
 2738: #
 2739: sub delete_profile_entry {
 2740:     my ($cmd, $tail, $client) = @_;
 2741: 
 2742:     my $userinput = "cmd:$tail";
 2743: 
 2744:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 2745:     chomp($what);
 2746:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2747: 				 &GDBM_WRCREAT(),
 2748: 				 "D",$what);
 2749:     if ($hashref) {
 2750:         my @keys=split(/\&/,$what);
 2751: 	foreach my $key (@keys) {
 2752: 	    delete($hashref->{$key});
 2753: 	}
 2754: 	if (untie(%$hashref)) {
 2755: 	    &Reply($client, "ok\n", $userinput);
 2756: 	} else {
 2757: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2758: 		    "while attempting del\n", $userinput);
 2759: 	}
 2760:     } else {
 2761: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2762: 		 "while attempting del\n", $userinput);
 2763:     }
 2764:     return 1;
 2765: }
 2766: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 2767: 
 2768: #
 2769: #  List the set of keys that are defined in a profile database file.
 2770: #  A successful reply from this will contain an & separated list of
 2771: #  the keys. 
 2772: # Parameters:
 2773: #     $cmd              - Command request (keys).
 2774: #     $tail             - Remainder of the request, a colon separated
 2775: #                         list containing domain/user that identifies the
 2776: #                         user being queried, and the database namespace
 2777: #                         (database filename essentially).
 2778: #     $client           - File open on the client.
 2779: #  Returns:
 2780: #    1    - Continue processing.
 2781: #    0    - Exit the server.
 2782: #
 2783: sub get_profile_keys {
 2784:     my ($cmd, $tail, $client) = @_;
 2785: 
 2786:     my $userinput = "$cmd:$tail";
 2787: 
 2788:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 2789:     my $qresult='';
 2790:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2791: 				  &GDBM_READER());
 2792:     if ($hashref) {
 2793: 	foreach my $key (keys %$hashref) {
 2794: 	    $qresult.="$key&";
 2795: 	}
 2796: 	if (untie(%$hashref)) {
 2797: 	    $qresult=~s/\&$//;
 2798: 	    &Reply($client, "$qresult\n", $userinput);
 2799: 	} else {
 2800: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2801: 		    "while attempting keys\n", $userinput);
 2802: 	}
 2803:     } else {
 2804: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2805: 		 "while attempting keys\n", $userinput);
 2806:     }
 2807:    
 2808:     return 1;
 2809: }
 2810: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 2811: 
 2812: #
 2813: #   Dump the contents of a user profile database.
 2814: #   Note that this constitutes a very large covert channel too since
 2815: #   the dump will return sensitive information that is not encrypted.
 2816: #   The naive security assumption is that the session negotiation ensures
 2817: #   our client is trusted and I don't believe that's assured at present.
 2818: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 2819: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 2820: # 
 2821: #  Parameters:
 2822: #     $cmd           - The command request keyword (currentdump).
 2823: #     $tail          - Remainder of the request, consisting of a colon
 2824: #                      separated list that has the domain/username and
 2825: #                      the namespace to dump (database file).
 2826: #     $client        - file open on the remote client.
 2827: # Returns:
 2828: #     1    - Continue processing.
 2829: #     0    - Exit the server.
 2830: #
 2831: sub dump_profile_database {
 2832:     my ($cmd, $tail, $client) = @_;
 2833: 
 2834:     my $userinput = "$cmd:$tail";
 2835:    
 2836:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 2837:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2838: 				 &GDBM_READER());
 2839:     if ($hashref) {
 2840: 	# Structure of %data:
 2841: 	# $data{$symb}->{$parameter}=$value;
 2842: 	# $data{$symb}->{'v.'.$parameter}=$version;
 2843: 	# since $parameter will be unescaped, we do not
 2844:  	# have to worry about silly parameter names...
 2845: 	
 2846:         my $qresult='';
 2847: 	my %data = ();                     # A hash of anonymous hashes..
 2848: 	while (my ($key,$value) = each(%$hashref)) {
 2849: 	    my ($v,$symb,$param) = split(/:/,$key);
 2850: 	    next if ($v eq 'version' || $symb eq 'keys');
 2851: 	    next if (exists($data{$symb}) && 
 2852: 		     exists($data{$symb}->{$param}) &&
 2853: 		     $data{$symb}->{'v.'.$param} > $v);
 2854: 	    $data{$symb}->{$param}=$value;
 2855: 	    $data{$symb}->{'v.'.$param}=$v;
 2856: 	}
 2857: 	if (untie(%$hashref)) {
 2858: 	    while (my ($symb,$param_hash) = each(%data)) {
 2859: 		while(my ($param,$value) = each (%$param_hash)){
 2860: 		    next if ($param =~ /^v\./);       # Ignore versions...
 2861: 		    #
 2862: 		    #   Just dump the symb=value pairs separated by &
 2863: 		    #
 2864: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 2865: 		}
 2866: 	    }
 2867: 	    chop($qresult);
 2868: 	    &Reply($client , "$qresult\n", $userinput);
 2869: 	} else {
 2870: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2871: 		     "while attempting currentdump\n", $userinput);
 2872: 	}
 2873:     } else {
 2874: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2875: 		"while attempting currentdump\n", $userinput);
 2876:     }
 2877: 
 2878:     return 1;
 2879: }
 2880: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 2881: 
 2882: #
 2883: #   Dump a profile database with an optional regular expression
 2884: #   to match against the keys.  In this dump, no effort is made
 2885: #   to separate symb from version information. Presumably the
 2886: #   databases that are dumped by this command are of a different
 2887: #   structure.  Need to look at this and improve the documentation of
 2888: #   both this and the currentdump handler.
 2889: # Parameters:
 2890: #    $cmd                     - The command keyword.
 2891: #    $tail                    - All of the characters after the $cmd:
 2892: #                               These are expected to be a colon
 2893: #                               separated list containing:
 2894: #                               domain/user - identifying the user.
 2895: #                               namespace   - identifying the database.
 2896: #                               regexp      - optional regular expression
 2897: #                                             that is matched against
 2898: #                                             database keywords to do
 2899: #                                             selective dumps.
 2900: #   $client                   - Channel open on the client.
 2901: # Returns:
 2902: #    1    - Continue processing.
 2903: # Side effects:
 2904: #    response is written to $client.
 2905: #
 2906: sub dump_with_regexp {
 2907:     my ($cmd, $tail, $client) = @_;
 2908: 
 2909: 
 2910:     my $userinput = "$cmd:$tail";
 2911: 
 2912:     my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);
 2913:     if (defined($regexp)) {
 2914: 	$regexp=&unescape($regexp);
 2915:     } else {
 2916: 	$regexp='.';
 2917:     }
 2918:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2919: 				 &GDBM_READER());
 2920:     if ($hashref) {
 2921:         my $qresult='';
 2922: 	while (my ($key,$value) = each(%$hashref)) {
 2923: 	    if ($regexp eq '.') {
 2924: 		$qresult.=$key.'='.$value.'&';
 2925: 	    } else {
 2926: 		my $unescapeKey = &unescape($key);
 2927: 		if (eval('$unescapeKey=~/$regexp/')) {
 2928: 		    $qresult.="$key=$value&";
 2929: 		}
 2930: 	    }
 2931: 	}
 2932: 	if (untie(%$hashref)) {
 2933: 	    chop($qresult);
 2934: 	    &Reply($client, "$qresult\n", $userinput);
 2935: 	} else {
 2936: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2937: 		     "while attempting dump\n", $userinput);
 2938: 	}
 2939:     } else {
 2940: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2941: 		"while attempting dump\n", $userinput);
 2942:     }
 2943: 
 2944:     return 1;
 2945: }
 2946: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 2947: 
 2948: #  Store a set of key=value pairs associated with a versioned name.
 2949: #
 2950: #  Parameters:
 2951: #    $cmd                - Request command keyword.
 2952: #    $tail               - Tail of the request.  This is a colon
 2953: #                          separated list containing:
 2954: #                          domain/user - User and authentication domain.
 2955: #                          namespace   - Name of the database being modified
 2956: #                          rid         - Resource keyword to modify.
 2957: #                          what        - new value associated with rid.
 2958: #
 2959: #    $client             - Socket open on the client.
 2960: #
 2961: #
 2962: #  Returns:
 2963: #      1 (keep on processing).
 2964: #  Side-Effects:
 2965: #    Writes to the client
 2966: sub store_handler {
 2967:     my ($cmd, $tail, $client) = @_;
 2968:  
 2969:     my $userinput = "$cmd:$tail";
 2970: 
 2971:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
 2972:     if ($namespace ne 'roles') {
 2973: 
 2974: 	chomp($what);
 2975: 	my @pairs=split(/\&/,$what);
 2976: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 2977: 				       &GDBM_WRCREAT(), "S",
 2978: 				       "$rid:$what");
 2979: 	if ($hashref) {
 2980: 	    my $now = time;
 2981: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
 2982: 	    my $key;
 2983: 	    $hashref->{"version:$rid"}++;
 2984: 	    my $version=$hashref->{"version:$rid"};
 2985: 	    my $allkeys=''; 
 2986: 	    foreach my $pair (@pairs) {
 2987: 		my ($key,$value)=split(/=/,$pair);
 2988: 		$allkeys.=$key.':';
 2989: 		$hashref->{"$version:$rid:$key"}=$value;
 2990: 	    }
 2991: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 2992: 	    $allkeys.='timestamp';
 2993: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 2994: 	    if (untie($hashref)) {
 2995: 		&Reply($client, "ok\n", $userinput);
 2996: 	    } else {
 2997: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2998: 			"while attempting store\n", $userinput);
 2999: 	    }
 3000: 	} else {
 3001: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3002: 		     "while attempting store\n", $userinput);
 3003: 	}
 3004:     } else {
 3005: 	&Failure($client, "refused\n", $userinput);
 3006:     }
 3007: 
 3008:     return 1;
 3009: }
 3010: &register_handler("store", \&store_handler, 0, 1, 0);
 3011: 
 3012: #
 3013: #  Dump out all versions of a resource that has key=value pairs associated
 3014: # with it for each version.  These resources are built up via the store
 3015: # command.
 3016: #
 3017: #  Parameters:
 3018: #     $cmd               - Command keyword.
 3019: #     $tail              - Remainder of the request which consists of:
 3020: #                          domain/user   - User and auth. domain.
 3021: #                          namespace     - name of resource database.
 3022: #                          rid           - Resource id.
 3023: #    $client             - socket open on the client.
 3024: #
 3025: # Returns:
 3026: #      1  indicating the caller should not yet exit.
 3027: # Side-effects:
 3028: #   Writes a reply to the client.
 3029: #   The reply is a string of the following shape:
 3030: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 3031: #    Where the 1 above represents version 1.
 3032: #    this continues for all pairs of keys in all versions.
 3033: #
 3034: #
 3035: #    
 3036: #
 3037: sub restore_handler {
 3038:     my ($cmd, $tail, $client) = @_;
 3039: 
 3040:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 3041: 
 3042:     my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
 3043:     $namespace=~s/\//\_/g;
 3044:     $namespace=~s/\W//g;
 3045:     chomp($rid);
 3046:     my $proname=&propath($udom,$uname);
 3047:     my $qresult='';
 3048:     my %hash;
 3049:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
 3050: 	    &GDBM_READER(),0640)) {
 3051: 	my $version=$hash{"version:$rid"};
 3052: 	$qresult.="version=$version&";
 3053: 	my $scope;
 3054: 	for ($scope=1;$scope<=$version;$scope++) {
 3055: 	    my $vkeys=$hash{"$scope:keys:$rid"};
 3056: 	    my @keys=split(/:/,$vkeys);
 3057: 	    my $key;
 3058: 	    $qresult.="$scope:keys=$vkeys&";
 3059: 	    foreach $key (@keys) {
 3060: 		$qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 3061: 	    }                                  
 3062: 	}
 3063: 	if (untie(%hash)) {
 3064: 	    $qresult=~s/\&$//;
 3065: 	    &Reply( $client, "$qresult\n", $userinput);
 3066: 	} else {
 3067: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3068: 		    "while attempting restore\n", $userinput);
 3069: 	}
 3070:     } else {
 3071: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3072: 		"while attempting restore\n", $userinput);
 3073:     }
 3074:   
 3075:     return 1;
 3076: 
 3077: 
 3078: }
 3079: &register_handler("restore", \&restore_handler, 0,1,0);
 3080: 
 3081: #
 3082: #   Add a chat message to to a discussion board.
 3083: #
 3084: # Parameters:
 3085: #    $cmd                - Request keyword.
 3086: #    $tail               - Tail of the command. A colon separated list
 3087: #                          containing:
 3088: #                          cdom    - Domain on which the chat board lives
 3089: #                          cnum    - Identifier of the discussion group.
 3090: #                          post    - Body of the posting.
 3091: #   $client              - Socket open on the client.
 3092: # Returns:
 3093: #   1    - Indicating caller should keep on processing.
 3094: #
 3095: # Side-effects:
 3096: #   writes a reply to the client.
 3097: #
 3098: #
 3099: sub send_chat_handler {
 3100:     my ($cmd, $tail, $client) = @_;
 3101: 
 3102:     
 3103:     my $userinput = "$cmd:$tail";
 3104: 
 3105:     my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
 3106:     &chat_add($cdom,$cnum,$newpost);
 3107:     &Reply($client, "ok\n", $userinput);
 3108: 
 3109:     return 1;
 3110: }
 3111: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 3112: 
 3113: #
 3114: #   Retrieve the set of chat messagss from a discussion board.
 3115: #
 3116: #  Parameters:
 3117: #    $cmd             - Command keyword that initiated the request.
 3118: #    $tail            - Remainder of the request after the command
 3119: #                       keyword.  In this case a colon separated list of
 3120: #                       chat domain    - Which discussion board.
 3121: #                       chat id        - Discussion thread(?)
 3122: #                       domain/user    - Authentication domain and username
 3123: #                                        of the requesting person.
 3124: #   $client           - Socket open on the client program.
 3125: # Returns:
 3126: #    1     - continue processing
 3127: # Side effects:
 3128: #    Response is written to the client.
 3129: #
 3130: sub retrieve_chat_handler {
 3131:     my ($cmd, $tail, $client) = @_;
 3132: 
 3133: 
 3134:     my $userinput = "$cmd:$tail";
 3135: 
 3136:     my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
 3137:     my $reply='';
 3138:     foreach (&get_chat($cdom,$cnum,$udom,$uname)) {
 3139: 	$reply.=&escape($_).':';
 3140:     }
 3141:     $reply=~s/\:$//;
 3142:     &Reply($client, $reply."\n", $userinput);
 3143: 
 3144: 
 3145:     return 1;
 3146: }
 3147: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 3148: 
 3149: #
 3150: #  Initiate a query of an sql database.  SQL query repsonses get put in
 3151: #  a file for later retrieval.  This prevents sql query results from
 3152: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 3153: #  less of an issue since multiple outstanding requests can be concurrently
 3154: #  serviced.
 3155: #
 3156: #  Parameters:
 3157: #     $cmd       - COmmand keyword that initiated the request.
 3158: #     $tail      - Remainder of the command after the keyword.
 3159: #                  For this function, this consists of a query and
 3160: #                  3 arguments that are self-documentingly labelled
 3161: #                  in the original arg1, arg2, arg3.
 3162: #     $client    - Socket open on the client.
 3163: # Return:
 3164: #    1   - Indicating processing should continue.
 3165: # Side-effects:
 3166: #    a reply is written to $client.
 3167: #
 3168: sub send_query_handler {
 3169:     my ($cmd, $tail, $client) = @_;
 3170: 
 3171: 
 3172:     my $userinput = "$cmd:$tail";
 3173: 
 3174:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 3175:     $query=~s/\n*$//g;
 3176:     &Reply($client, "". &sql_reply("$clientname\&$query".
 3177: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 3178: 	  $userinput);
 3179:     
 3180:     return 1;
 3181: }
 3182: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 3183: 
 3184: #
 3185: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 3186: #   The query is submitted via a "querysend" transaction.
 3187: #   There it is passed on to the lonsql daemon, queued and issued to
 3188: #   mysql.
 3189: #     This transaction is invoked when the sql transaction is complete
 3190: #   it stores the query results in flie and indicates query completion.
 3191: #   presumably local software then fetches this response... I'm guessing
 3192: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 3193: #   lonsql on completion of the query interacts with the lond of our
 3194: #   client to do a query reply storing two files:
 3195: #    - id     - The results of the query.
 3196: #    - id.end - Indicating the transaction completed. 
 3197: #    NOTE: id is a unique id assigned to the query and querysend time.
 3198: # Parameters:
 3199: #    $cmd        - Command keyword that initiated this request.
 3200: #    $tail       - Remainder of the tail.  In this case that's a colon
 3201: #                  separated list containing the query Id and the 
 3202: #                  results of the query.
 3203: #    $client     - Socket open on the client.
 3204: # Return:
 3205: #    1           - Indicating that we should continue processing.
 3206: # Side effects:
 3207: #    ok written to the client.
 3208: #
 3209: sub reply_query_handler {
 3210:     my ($cmd, $tail, $client) = @_;
 3211: 
 3212: 
 3213:     my $userinput = "$cmd:$tail";
 3214: 
 3215:     my ($cmd,$id,$reply)=split(/:/,$userinput); 
 3216:     my $store;
 3217:     my $execdir=$perlvar{'lonDaemons'};
 3218:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 3219: 	$reply=~s/\&/\n/g;
 3220: 	print $store $reply;
 3221: 	close $store;
 3222: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 3223: 	print $store2 "done\n";
 3224: 	close $store2;
 3225: 	&Reply($client, "ok\n", $userinput);
 3226:     } else {
 3227: 	&Failure($client, "error: ".($!+0)
 3228: 		." IO::File->new Failed ".
 3229: 		"while attempting queryreply\n", $userinput);
 3230:     }
 3231:  
 3232: 
 3233:     return 1;
 3234: }
 3235: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 3236: 
 3237: #
 3238: #  Process the courseidput request.  Not quite sure what this means
 3239: #  at the system level sense.  It appears a gdbm file in the 
 3240: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 3241: #  a set of entries made in that database.
 3242: #
 3243: # Parameters:
 3244: #   $cmd      - The command keyword that initiated this request.
 3245: #   $tail     - Tail of the command.  In this case consists of a colon
 3246: #               separated list contaning the domain to apply this to and
 3247: #               an ampersand separated list of keyword=value pairs.
 3248: #               Each value is a colon separated list that includes:  
 3249: #               description, institutional code and course owner.
 3250: #               For backward compatibility with versions included
 3251: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
 3252: #               code and/or course owner are preserved from the existing 
 3253: #               record when writing a new record in response to 1.1 or 
 3254: #               1.2 implementations of lonnet::flushcourselogs().   
 3255: #                      
 3256: #   $client   - Socket open on the client.
 3257: # Returns:
 3258: #   1    - indicating that processing should continue
 3259: #
 3260: # Side effects:
 3261: #   reply is written to the client.
 3262: #
 3263: sub put_course_id_handler {
 3264:     my ($cmd, $tail, $client) = @_;
 3265: 
 3266: 
 3267:     my $userinput = "$cmd:$tail";
 3268: 
 3269:     my ($udom, $what) = split(/:/, $tail,2);
 3270:     chomp($what);
 3271:     my $now=time;
 3272:     my @pairs=split(/\&/,$what);
 3273: 
 3274:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3275:     if ($hashref) {
 3276: 	foreach my $pair (@pairs) {
 3277:             my ($key,$courseinfo) = split(/=/,$pair,2);
 3278:             $courseinfo =~ s/=/:/g;
 3279: 
 3280:             my @current_items = split(/:/,$hashref->{$key});
 3281:             shift(@current_items); # remove description
 3282:             pop(@current_items);   # remove last access
 3283:             my $numcurrent = scalar(@current_items);
 3284: 
 3285:             my @new_items = split(/:/,$courseinfo);
 3286:             my $numnew = scalar(@new_items);
 3287:             if ($numcurrent > 0) {
 3288:                 if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
 3289:                     $courseinfo .= ':'.join(':',@current_items);
 3290:                 } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
 3291:                     $courseinfo .= ':'.$current_items[$numcurrent-1];
 3292:                 }
 3293:             }
 3294: 	    $hashref->{$key}=$courseinfo.':'.$now;
 3295: 	}
 3296: 	if (untie(%$hashref)) {
 3297: 	    &Reply( $client, "ok\n", $userinput);
 3298: 	} else {
 3299: 	    &Failure($client, "error: ".($!+0)
 3300: 		     ." untie(GDBM) Failed ".
 3301: 		     "while attempting courseidput\n", $userinput);
 3302: 	}
 3303:     } else {
 3304: 	&Failure($client, "error: ".($!+0)
 3305: 		 ." tie(GDBM) Failed ".
 3306: 		 "while attempting courseidput\n", $userinput);
 3307:     }
 3308:     
 3309: 
 3310:     return 1;
 3311: }
 3312: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 3313: 
 3314: #  Retrieves the value of a course id resource keyword pattern
 3315: #  defined since a starting date.  Both the starting date and the
 3316: #  keyword pattern are optional.  If the starting date is not supplied it
 3317: #  is treated as the beginning of time.  If the pattern is not found,
 3318: #  it is treatred as "." matching everything.
 3319: #
 3320: #  Parameters:
 3321: #     $cmd     - Command keyword that resulted in us being dispatched.
 3322: #     $tail    - The remainder of the command that, in this case, consists
 3323: #                of a colon separated list of:
 3324: #                 domain   - The domain in which the course database is 
 3325: #                            defined.
 3326: #                 since    - Optional parameter describing the minimum
 3327: #                            time of definition(?) of the resources that
 3328: #                            will match the dump.
 3329: #                 description - regular expression that is used to filter
 3330: #                            the dump.  Only keywords matching this regexp
 3331: #                            will be used.
 3332: #                 institutional code - optional supplied code to filter 
 3333: #                            the dump. Only courses with an institutional code 
 3334: #                            that match the supplied code will be returned.
 3335: #                 owner    - optional supplied username of owner to filter
 3336: #                            the dump.  Only courses for which the course 
 3337: #                            owner matches the supplied username will be
 3338: #                            returned. Implicit assumption that owner
 3339: #                            is a user in the domain in which the
 3340: #                            course database is defined.
 3341: #     $client  - The socket open on the client.
 3342: # Returns:
 3343: #    1     - Continue processing.
 3344: # Side Effects:
 3345: #   a reply is written to $client.
 3346: sub dump_course_id_handler {
 3347:     my ($cmd, $tail, $client) = @_;
 3348: 
 3349:     my $userinput = "$cmd:$tail";
 3350: 
 3351:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter) =split(/:/,$tail);
 3352:     if (defined($description)) {
 3353: 	$description=&unescape($description);
 3354:     } else {
 3355: 	$description='.';
 3356:     }
 3357:     if (defined($instcodefilter)) {
 3358:         $instcodefilter=&unescape($instcodefilter);
 3359:     } else {
 3360:         $instcodefilter='.';
 3361:     }
 3362:     if (defined($ownerfilter)) {
 3363:         $ownerfilter=&unescape($ownerfilter);
 3364:     } else {
 3365:         $ownerfilter='.';
 3366:     }
 3367:     if (defined($coursefilter)) {
 3368:         $coursefilter=&unescape($coursefilter);
 3369:     } else {
 3370:         $coursefilter='.';
 3371:     }
 3372: 
 3373:     unless (defined($since)) { $since=0; }
 3374:     my $qresult='';
 3375:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3376:     if ($hashref) {
 3377: 	while (my ($key,$value) = each(%$hashref)) {
 3378: 	    my ($descr,$lasttime,$inst_code,$owner);
 3379:             my @courseitems = split(/:/,$value);
 3380:             $lasttime = pop(@courseitems);
 3381: 	    ($descr,$inst_code,$owner)=@courseitems;
 3382: 	    if ($lasttime<$since) { next; }
 3383:             my $match = 1;
 3384: 	    unless ($description eq '.') {
 3385: 		my $unescapeDescr = &unescape($descr);
 3386: 		unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
 3387:                     $match = 0;
 3388: 		}
 3389:             }
 3390:             unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
 3391:                 my $unescapeInstcode = &unescape($inst_code);
 3392:                 unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
 3393:                     $match = 0;
 3394:                 }
 3395: 	    }
 3396:             unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
 3397:                 my $unescapeOwner = &unescape($owner);
 3398:                 unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
 3399:                     $match = 0;
 3400:                 }
 3401:             }
 3402:             unless ($coursefilter eq '.' || !defined($coursefilter)) {
 3403:                 my $unescapeCourse = &unescape($key);
 3404:                 unless (eval('$unescapeCourse=~/^$udom(_)\Q$coursefilter\E$/')) {
 3405:                     $match = 0;
 3406:                 }
 3407:             }
 3408:             if ($match == 1) {
 3409:                 $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
 3410:             }
 3411: 	}
 3412: 	if (untie(%$hashref)) {
 3413: 	    chop($qresult);
 3414: 	    &Reply($client, "$qresult\n", $userinput);
 3415: 	} else {
 3416: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3417: 		    "while attempting courseiddump\n", $userinput);
 3418: 	}
 3419:     } else {
 3420: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3421: 		"while attempting courseiddump\n", $userinput);
 3422:     }
 3423: 
 3424: 
 3425:     return 1;
 3426: }
 3427: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 3428: 
 3429: #
 3430: #  Puts an id to a domains id database. 
 3431: #
 3432: #  Parameters:
 3433: #   $cmd     - The command that triggered us.
 3434: #   $tail    - Remainder of the request other than the command. This is a 
 3435: #              colon separated list containing:
 3436: #              $domain  - The domain for which we are writing the id.
 3437: #              $pairs  - The id info to write... this is and & separated list
 3438: #                        of keyword=value.
 3439: #   $client  - Socket open on the client.
 3440: #  Returns:
 3441: #    1   - Continue processing.
 3442: #  Side effects:
 3443: #     reply is written to $client.
 3444: #
 3445: sub put_id_handler {
 3446:     my ($cmd,$tail,$client) = @_;
 3447: 
 3448: 
 3449:     my $userinput = "$cmd:$tail";
 3450: 
 3451:     my ($udom,$what)=split(/:/,$tail);
 3452:     chomp($what);
 3453:     my @pairs=split(/\&/,$what);
 3454:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 3455: 				   "P", $what);
 3456:     if ($hashref) {
 3457: 	foreach my $pair (@pairs) {
 3458: 	    my ($key,$value)=split(/=/,$pair);
 3459: 	    $hashref->{$key}=$value;
 3460: 	}
 3461: 	if (untie(%$hashref)) {
 3462: 	    &Reply($client, "ok\n", $userinput);
 3463: 	} else {
 3464: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3465: 		     "while attempting idput\n", $userinput);
 3466: 	}
 3467:     } else {
 3468: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3469: 		  "while attempting idput\n", $userinput);
 3470:     }
 3471: 
 3472:     return 1;
 3473: }
 3474: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 3475: 
 3476: #
 3477: #  Retrieves a set of id values from the id database.
 3478: #  Returns an & separated list of results, one for each requested id to the
 3479: #  client.
 3480: #
 3481: # Parameters:
 3482: #   $cmd       - Command keyword that caused us to be dispatched.
 3483: #   $tail      - Tail of the command.  Consists of a colon separated:
 3484: #               domain - the domain whose id table we dump
 3485: #               ids      Consists of an & separated list of
 3486: #                        id keywords whose values will be fetched.
 3487: #                        nonexisting keywords will have an empty value.
 3488: #   $client    - Socket open on the client.
 3489: #
 3490: # Returns:
 3491: #    1 - indicating processing should continue.
 3492: # Side effects:
 3493: #   An & separated list of results is written to $client.
 3494: #
 3495: sub get_id_handler {
 3496:     my ($cmd, $tail, $client) = @_;
 3497: 
 3498:     
 3499:     my $userinput = "$client:$tail";
 3500:     
 3501:     my ($udom,$what)=split(/:/,$tail);
 3502:     chomp($what);
 3503:     my @queries=split(/\&/,$what);
 3504:     my $qresult='';
 3505:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 3506:     if ($hashref) {
 3507: 	for (my $i=0;$i<=$#queries;$i++) {
 3508: 	    $qresult.="$hashref->{$queries[$i]}&";
 3509: 	}
 3510: 	if (untie(%$hashref)) {
 3511: 	    $qresult=~s/\&$//;
 3512: 	    &Reply($client, "$qresult\n", $userinput);
 3513: 	} else {
 3514: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3515: 		      "while attempting idget\n",$userinput);
 3516: 	}
 3517:     } else {
 3518: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3519: 		 "while attempting idget\n",$userinput);
 3520:     }
 3521:     
 3522:     return 1;
 3523: }
 3524: &register_handler("idget", \&get_id_handler, 0, 1, 0);
 3525: 
 3526: #
 3527: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
 3528: #
 3529: # Parameters
 3530: #   $cmd       - Command keyword that caused us to be dispatched.
 3531: #   $tail      - Tail of the command.  Consists of a colon separated:
 3532: #               domain - the domain whose dcmail we are recording
 3533: #               email    Consists of key=value pair 
 3534: #                        where key is unique msgid
 3535: #                        and value is message (in XML)
 3536: #   $client    - Socket open on the client.
 3537: #
 3538: # Returns:
 3539: #    1 - indicating processing should continue.
 3540: # Side effects
 3541: #     reply is written to $client.
 3542: #
 3543: sub put_dcmail_handler {
 3544:     my ($cmd,$tail,$client) = @_;
 3545:     my $userinput = "$cmd:$tail";
 3546:                                                                                 
 3547:     my ($udom,$what)=split(/:/,$tail);
 3548:     chomp($what);
 3549:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 3550:     if ($hashref) {
 3551:         my ($key,$value)=split(/=/,$what);
 3552:         $hashref->{$key}=$value;
 3553:     }
 3554:     if (untie(%$hashref)) {
 3555:         &Reply($client, "ok\n", $userinput);
 3556:     } else {
 3557:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3558:                  "while attempting dcmailput\n", $userinput);
 3559:     }
 3560:     return 1;
 3561: }
 3562: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
 3563: 
 3564: #
 3565: # Retrieves broadcast e-mail from nohist_dcmail database
 3566: # Returns to client an & separated list of key=value pairs,
 3567: # where key is msgid and value is message information.
 3568: #
 3569: # Parameters
 3570: #   $cmd       - Command keyword that caused us to be dispatched.
 3571: #   $tail      - Tail of the command.  Consists of a colon separated:
 3572: #               domain - the domain whose dcmail table we dump
 3573: #               startfilter - beginning of time window 
 3574: #               endfilter - end of time window
 3575: #               sendersfilter - & separated list of username:domain 
 3576: #                 for senders to search for.
 3577: #   $client    - Socket open on the client.
 3578: #
 3579: # Returns:
 3580: #    1 - indicating processing should continue.
 3581: # Side effects
 3582: #     reply (& separated list of msgid=messageinfo pairs) is 
 3583: #     written to $client.
 3584: #
 3585: sub dump_dcmail_handler {
 3586:     my ($cmd, $tail, $client) = @_;
 3587:                                                                                 
 3588:     my $userinput = "$cmd:$tail";
 3589:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
 3590:     chomp($sendersfilter);
 3591:     my @senders = ();
 3592:     if (defined($startfilter)) {
 3593:         $startfilter=&unescape($startfilter);
 3594:     } else {
 3595:         $startfilter='.';
 3596:     }
 3597:     if (defined($endfilter)) {
 3598:         $endfilter=&unescape($endfilter);
 3599:     } else {
 3600:         $endfilter='.';
 3601:     }
 3602:     if (defined($sendersfilter)) {
 3603:         $sendersfilter=&unescape($sendersfilter);
 3604: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
 3605:     }
 3606: 
 3607:     my $qresult='';
 3608:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
 3609:     if ($hashref) {
 3610:         while (my ($key,$value) = each(%$hashref)) {
 3611:             my $match = 1;
 3612:             my ($timestamp,$subj,$uname,$udom) = 
 3613: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
 3614:             $subj = &unescape($subj);
 3615:             unless ($startfilter eq '.' || !defined($startfilter)) {
 3616:                 if ($timestamp < $startfilter) {
 3617:                     $match = 0;
 3618:                 }
 3619:             }
 3620:             unless ($endfilter eq '.' || !defined($endfilter)) {
 3621:                 if ($timestamp > $endfilter) {
 3622:                     $match = 0;
 3623:                 }
 3624:             }
 3625:             unless (@senders < 1) {
 3626:                 unless (grep/^$uname:$udom$/,@senders) {
 3627:                     $match = 0;
 3628:                 }
 3629:             }
 3630:             if ($match == 1) {
 3631:                 $qresult.=$key.'='.$value.'&';
 3632:             }
 3633:         }
 3634:         if (untie(%$hashref)) {
 3635:             chop($qresult);
 3636:             &Reply($client, "$qresult\n", $userinput);
 3637:         } else {
 3638:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3639:                     "while attempting dcmaildump\n", $userinput);
 3640:         }
 3641:     } else {
 3642:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3643:                 "while attempting dcmaildump\n", $userinput);
 3644:     }
 3645:     return 1;
 3646: }
 3647: 
 3648: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
 3649: 
 3650: #
 3651: # Puts domain roles in nohist_domainroles database
 3652: #
 3653: # Parameters
 3654: #   $cmd       - Command keyword that caused us to be dispatched.
 3655: #   $tail      - Tail of the command.  Consists of a colon separated:
 3656: #               domain - the domain whose roles we are recording  
 3657: #               role -   Consists of key=value pair
 3658: #                        where key is unique role
 3659: #                        and value is start/end date information
 3660: #   $client    - Socket open on the client.
 3661: #
 3662: # Returns:
 3663: #    1 - indicating processing should continue.
 3664: # Side effects
 3665: #     reply is written to $client.
 3666: #
 3667: 
 3668: sub put_domainroles_handler {
 3669:     my ($cmd,$tail,$client) = @_;
 3670: 
 3671:     my $userinput = "$cmd:$tail";
 3672:     my ($udom,$what)=split(/:/,$tail);
 3673:     chomp($what);
 3674:     my @pairs=split(/\&/,$what);
 3675:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 3676:     if ($hashref) {
 3677:         foreach my $pair (@pairs) {
 3678:             my ($key,$value)=split(/=/,$pair);
 3679:             $hashref->{$key}=$value;
 3680:         }
 3681:         if (untie(%$hashref)) {
 3682:             &Reply($client, "ok\n", $userinput);
 3683:         } else {
 3684:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3685:                      "while attempting domroleput\n", $userinput);
 3686:         }
 3687:     } else {
 3688:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3689:                   "while attempting domroleput\n", $userinput);
 3690:     }
 3691:                                                                                   
 3692:     return 1;
 3693: }
 3694: 
 3695: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
 3696: 
 3697: #
 3698: # Retrieves domain roles from nohist_domainroles database
 3699: # Returns to client an & separated list of key=value pairs,
 3700: # where key is role and value is start and end date information.
 3701: #
 3702: # Parameters
 3703: #   $cmd       - Command keyword that caused us to be dispatched.
 3704: #   $tail      - Tail of the command.  Consists of a colon separated:
 3705: #               domain - the domain whose domain roles table we dump
 3706: #   $client    - Socket open on the client.
 3707: #
 3708: # Returns:
 3709: #    1 - indicating processing should continue.
 3710: # Side effects
 3711: #     reply (& separated list of role=start/end info pairs) is
 3712: #     written to $client.
 3713: #
 3714: sub dump_domainroles_handler {
 3715:     my ($cmd, $tail, $client) = @_;
 3716:                                                                                            
 3717:     my $userinput = "$cmd:$tail";
 3718:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
 3719:     chomp($rolesfilter);
 3720:     my @roles = ();
 3721:     if (defined($startfilter)) {
 3722:         $startfilter=&unescape($startfilter);
 3723:     } else {
 3724:         $startfilter='.';
 3725:     }
 3726:     if (defined($endfilter)) {
 3727:         $endfilter=&unescape($endfilter);
 3728:     } else {
 3729:         $endfilter='.';
 3730:     }
 3731:     if (defined($rolesfilter)) {
 3732:         $rolesfilter=&unescape($rolesfilter);
 3733: 	@roles = split(/\&/,$rolesfilter);
 3734:     }
 3735:                                                                                            
 3736:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
 3737:     if ($hashref) {
 3738:         my $qresult = '';
 3739:         while (my ($key,$value) = each(%$hashref)) {
 3740:             my $match = 1;
 3741:             my ($start,$end) = split(/:/,&unescape($value));
 3742:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
 3743:             unless ($startfilter eq '.' || !defined($startfilter)) {
 3744:                 if ($start >= $startfilter) {
 3745:                     $match = 0;
 3746:                 }
 3747:             }
 3748:             unless ($endfilter eq '.' || !defined($endfilter)) {
 3749:                 if ($end <= $endfilter) {
 3750:                     $match = 0;
 3751:                 }
 3752:             }
 3753:             unless (@roles < 1) {
 3754:                 unless (grep/^$trole$/,@roles) {
 3755:                     $match = 0;
 3756:                 }
 3757:             }
 3758:             if ($match == 1) {
 3759:                 $qresult.=$key.'='.$value.'&';
 3760:             }
 3761:         }
 3762:         if (untie(%$hashref)) {
 3763:             chop($qresult);
 3764:             &Reply($client, "$qresult\n", $userinput);
 3765:         } else {
 3766:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3767:                     "while attempting domrolesdump\n", $userinput);
 3768:         }
 3769:     } else {
 3770:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3771:                 "while attempting domrolesdump\n", $userinput);
 3772:     }
 3773:     return 1;
 3774: }
 3775: 
 3776: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
 3777: 
 3778: 
 3779: #  Process the tmpput command I'm not sure what this does.. Seems to
 3780: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 3781: # where Id is the client's ip concatenated with a sequence number.
 3782: # The file will contain some value that is passed in.  Is this e.g.
 3783: # a login token?
 3784: #
 3785: # Parameters:
 3786: #    $cmd     - The command that got us dispatched.
 3787: #    $tail    - The remainder of the request following $cmd:
 3788: #               In this case this will be the contents of the file.
 3789: #    $client  - Socket connected to the client.
 3790: # Returns:
 3791: #    1 indicating processing can continue.
 3792: # Side effects:
 3793: #   A file is created in the local filesystem.
 3794: #   A reply is sent to the client.
 3795: sub tmp_put_handler {
 3796:     my ($cmd, $what, $client) = @_;
 3797: 
 3798:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 3799: 
 3800: 
 3801:     my $store;
 3802:     $tmpsnum++;
 3803:     my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 3804:     $id=~s/\W/\_/g;
 3805:     $what=~s/\n//g;
 3806:     my $execdir=$perlvar{'lonDaemons'};
 3807:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 3808: 	print $store $what;
 3809: 	close $store;
 3810: 	&Reply($client, "$id\n", $userinput);
 3811:     } else {
 3812: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 3813: 		  "while attempting tmpput\n", $userinput);
 3814:     }
 3815:     return 1;
 3816:   
 3817: }
 3818: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 3819: 
 3820: #   Processes the tmpget command.  This command returns the contents
 3821: #  of a temporary resource file(?) created via tmpput.
 3822: #
 3823: # Paramters:
 3824: #    $cmd      - Command that got us dispatched.
 3825: #    $id       - Tail of the command, contain the id of the resource
 3826: #                we want to fetch.
 3827: #    $client   - socket open on the client.
 3828: # Return:
 3829: #    1         - Inidcating processing can continue.
 3830: # Side effects:
 3831: #   A reply is sent to the client.
 3832: #
 3833: sub tmp_get_handler {
 3834:     my ($cmd, $id, $client) = @_;
 3835: 
 3836:     my $userinput = "$cmd:$id"; 
 3837:     
 3838: 
 3839:     $id=~s/\W/\_/g;
 3840:     my $store;
 3841:     my $execdir=$perlvar{'lonDaemons'};
 3842:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 3843: 	my $reply=<$store>;
 3844: 	&Reply( $client, "$reply\n", $userinput);
 3845: 	close $store;
 3846:     } else {
 3847: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 3848: 		  "while attempting tmpget\n", $userinput);
 3849:     }
 3850: 
 3851:     return 1;
 3852: }
 3853: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 3854: 
 3855: #
 3856: #  Process the tmpdel command.  This command deletes a temp resource
 3857: #  created by the tmpput command.
 3858: #
 3859: # Parameters:
 3860: #   $cmd      - Command that got us here.
 3861: #   $id       - Id of the temporary resource created.
 3862: #   $client   - socket open on the client process.
 3863: #
 3864: # Returns:
 3865: #   1     - Indicating processing should continue.
 3866: # Side Effects:
 3867: #   A file is deleted
 3868: #   A reply is sent to the client.
 3869: sub tmp_del_handler {
 3870:     my ($cmd, $id, $client) = @_;
 3871:     
 3872:     my $userinput= "$cmd:$id";
 3873:     
 3874:     chomp($id);
 3875:     $id=~s/\W/\_/g;
 3876:     my $execdir=$perlvar{'lonDaemons'};
 3877:     if (unlink("$execdir/tmp/$id.tmp")) {
 3878: 	&Reply($client, "ok\n", $userinput);
 3879:     } else {
 3880: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 3881: 		  "while attempting tmpdel\n", $userinput);
 3882:     }
 3883:     
 3884:     return 1;
 3885: 
 3886: }
 3887: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 3888: 
 3889: #
 3890: #   Processes the setannounce command.  This command
 3891: #   creates a file named announce.txt in the top directory of
 3892: #   the documentn root and sets its contents.  The announce.txt file is
 3893: #   printed in its entirety at the LonCAPA login page.  Note:
 3894: #   once the announcement.txt fileis created it cannot be deleted.
 3895: #   However, setting the contents of the file to empty removes the
 3896: #   announcement from the login page of loncapa so who cares.
 3897: #
 3898: # Parameters:
 3899: #    $cmd          - The command that got us dispatched.
 3900: #    $announcement - The text of the announcement.
 3901: #    $client       - Socket open on the client process.
 3902: # Retunrns:
 3903: #   1             - Indicating request processing should continue
 3904: # Side Effects:
 3905: #   The file {DocRoot}/announcement.txt is created.
 3906: #   A reply is sent to $client.
 3907: #
 3908: sub set_announce_handler {
 3909:     my ($cmd, $announcement, $client) = @_;
 3910:   
 3911:     my $userinput    = "$cmd:$announcement";
 3912: 
 3913:     chomp($announcement);
 3914:     $announcement=&unescape($announcement);
 3915:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 3916: 				'/announcement.txt')) {
 3917: 	print $store $announcement;
 3918: 	close $store;
 3919: 	&Reply($client, "ok\n", $userinput);
 3920:     } else {
 3921: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 3922:     }
 3923: 
 3924:     return 1;
 3925: }
 3926: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 3927: 
 3928: #
 3929: #  Return the version of the daemon.  This can be used to determine
 3930: #  the compatibility of cross version installations or, alternatively to
 3931: #  simply know who's out of date and who isn't.  Note that the version
 3932: #  is returned concatenated with the tail.
 3933: # Parameters:
 3934: #   $cmd        - the request that dispatched to us.
 3935: #   $tail       - Tail of the request (client's version?).
 3936: #   $client     - Socket open on the client.
 3937: #Returns:
 3938: #   1 - continue processing requests.
 3939: # Side Effects:
 3940: #   Replies with version to $client.
 3941: sub get_version_handler {
 3942:     my ($cmd, $tail, $client) = @_;
 3943: 
 3944:     my $userinput  = $cmd.$tail;
 3945:     
 3946:     &Reply($client, &version($userinput)."\n", $userinput);
 3947: 
 3948: 
 3949:     return 1;
 3950: }
 3951: &register_handler("version", \&get_version_handler, 0, 1, 0);
 3952: 
 3953: #  Set the current host and domain.  This is used to support
 3954: #  multihomed systems.  Each IP of the system, or even separate daemons
 3955: #  on the same IP can be treated as handling a separate lonCAPA virtual
 3956: #  machine.  This command selects the virtual lonCAPA.  The client always
 3957: #  knows the right one since it is lonc and it is selecting the domain/system
 3958: #  from the hosts.tab file.
 3959: # Parameters:
 3960: #    $cmd      - Command that dispatched us.
 3961: #    $tail     - Tail of the command (domain/host requested).
 3962: #    $socket   - Socket open on the client.
 3963: #
 3964: # Returns:
 3965: #     1   - Indicates the program should continue to process requests.
 3966: # Side-effects:
 3967: #     The default domain/system context is modified for this daemon.
 3968: #     a reply is sent to the client.
 3969: #
 3970: sub set_virtual_host_handler {
 3971:     my ($cmd, $tail, $socket) = @_;
 3972:   
 3973:     my $userinput  ="$cmd:$tail";
 3974: 
 3975:     &Reply($client, &sethost($userinput)."\n", $userinput);
 3976: 
 3977: 
 3978:     return 1;
 3979: }
 3980: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 3981: 
 3982: #  Process a request to exit:
 3983: #   - "bye" is sent to the client.
 3984: #   - The client socket is shutdown and closed.
 3985: #   - We indicate to the caller that we should exit.
 3986: # Formal Parameters:
 3987: #   $cmd                - The command that got us here.
 3988: #   $tail               - Tail of the command (empty).
 3989: #   $client             - Socket open on the tail.
 3990: # Returns:
 3991: #   0      - Indicating the program should exit!!
 3992: #
 3993: sub exit_handler {
 3994:     my ($cmd, $tail, $client) = @_;
 3995: 
 3996:     my $userinput = "$cmd:$tail";
 3997: 
 3998:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 3999:     &Reply($client, "bye\n", $userinput);
 4000:     $client->shutdown(2);        # shutdown the socket forcibly.
 4001:     $client->close();
 4002: 
 4003:     return 0;
 4004: }
 4005: &register_handler("exit", \&exit_handler, 0,1,1);
 4006: &register_handler("init", \&exit_handler, 0,1,1);
 4007: &register_handler("quit", \&exit_handler, 0,1,1);
 4008: 
 4009: #  Determine if auto-enrollment is enabled.
 4010: #  Note that the original had what I believe to be a defect.
 4011: #  The original returned 0 if the requestor was not a registerd client.
 4012: #  It should return "refused".
 4013: # Formal Parameters:
 4014: #   $cmd       - The command that invoked us.
 4015: #   $tail      - The tail of the command (Extra command parameters.
 4016: #   $client    - The socket open on the client that issued the request.
 4017: # Returns:
 4018: #    1         - Indicating processing should continue.
 4019: #
 4020: sub enrollment_enabled_handler {
 4021:     my ($cmd, $tail, $client) = @_;
 4022:     my $userinput = $cmd.":".$tail; # For logging purposes.
 4023: 
 4024:     
 4025:     my $cdom = split(/:/, $tail);   # Domain we're asking about.
 4026:     my $outcome  = &localenroll::run($cdom);
 4027:     &Reply($client, "$outcome\n", $userinput);
 4028: 
 4029:     return 1;
 4030: }
 4031: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 4032: 
 4033: #   Get the official sections for which auto-enrollment is possible.
 4034: #   Since the admin people won't know about 'unofficial sections' 
 4035: #   we cannot auto-enroll on them.
 4036: # Formal Parameters:
 4037: #    $cmd     - The command request that got us dispatched here.
 4038: #    $tail    - The remainder of the request.  In our case this
 4039: #               will be split into:
 4040: #               $coursecode   - The course name from the admin point of view.
 4041: #               $cdom         - The course's domain(?).
 4042: #    $client  - Socket open on the client.
 4043: # Returns:
 4044: #    1    - Indiciting processing should continue.
 4045: #
 4046: sub get_sections_handler {
 4047:     my ($cmd, $tail, $client) = @_;
 4048:     my $userinput = "$cmd:$tail";
 4049: 
 4050:     my ($coursecode, $cdom) = split(/:/, $tail);
 4051:     my @secs = &localenroll::get_sections($coursecode,$cdom);
 4052:     my $seclist = &escape(join(':',@secs));
 4053: 
 4054:     &Reply($client, "$seclist\n", $userinput);
 4055:     
 4056: 
 4057:     return 1;
 4058: }
 4059: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 4060: 
 4061: #   Validate the owner of a new course section.  
 4062: #
 4063: # Formal Parameters:
 4064: #   $cmd      - Command that got us dispatched.
 4065: #   $tail     - the remainder of the command.  For us this consists of a
 4066: #               colon separated string containing:
 4067: #                  $inst    - Course Id from the institutions point of view.
 4068: #                  $owner   - Proposed owner of the course.
 4069: #                  $cdom    - Domain of the course (from the institutions
 4070: #                             point of view?)..
 4071: #   $client   - Socket open on the client.
 4072: #
 4073: # Returns:
 4074: #   1        - Processing should continue.
 4075: #
 4076: sub validate_course_owner_handler {
 4077:     my ($cmd, $tail, $client)  = @_;
 4078:     my $userinput = "$cmd:$tail";
 4079:     my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
 4080: 
 4081:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
 4082:     &Reply($client, "$outcome\n", $userinput);
 4083: 
 4084: 
 4085: 
 4086:     return 1;
 4087: }
 4088: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 4089: 
 4090: #
 4091: #   Validate a course section in the official schedule of classes
 4092: #   from the institutions point of view (part of autoenrollment).
 4093: #
 4094: # Formal Parameters:
 4095: #   $cmd          - The command request that got us dispatched.
 4096: #   $tail         - The tail of the command.  In this case,
 4097: #                   this is a colon separated set of words that will be split
 4098: #                   into:
 4099: #                        $inst_course_id - The course/section id from the
 4100: #                                          institutions point of view.
 4101: #                        $cdom           - The domain from the institutions
 4102: #                                          point of view.
 4103: #   $client       - Socket open on the client.
 4104: # Returns:
 4105: #    1           - Indicating processing should continue.
 4106: #
 4107: sub validate_course_section_handler {
 4108:     my ($cmd, $tail, $client) = @_;
 4109:     my $userinput = "$cmd:$tail";
 4110:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 4111: 
 4112:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 4113:     &Reply($client, "$outcome\n", $userinput);
 4114: 
 4115: 
 4116:     return 1;
 4117: }
 4118: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 4119: 
 4120: #
 4121: #   Create a password for a new auto-enrollment user.
 4122: #   I think/guess, this password allows access to the institutions 
 4123: #   AIS class list server/services.  Stuart can correct this comment
 4124: #   when he finds out how wrong I am.
 4125: #
 4126: # Formal Parameters:
 4127: #    $cmd     - The command request that got us dispatched.
 4128: #    $tail    - The tail of the command.   In this case this is a colon separated
 4129: #               set of words that will be split into:
 4130: #               $authparam - An authentication parameter (username??).
 4131: #               $cdom      - The domain of the course from the institution's
 4132: #                            point of view.
 4133: #    $client  - The socket open on the client.
 4134: # Returns:
 4135: #    1 - continue processing.
 4136: #
 4137: sub create_auto_enroll_password_handler {
 4138:     my ($cmd, $tail, $client) = @_;
 4139:     my $userinput = "$cmd:$tail";
 4140: 
 4141:     my ($authparam, $cdom) = split(/:/, $userinput);
 4142: 
 4143:     my ($create_passwd,$authchk);
 4144:     ($authparam,
 4145:      $create_passwd,
 4146:      $authchk) = &localenroll::create_password($authparam,$cdom);
 4147: 
 4148:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 4149: 	   $userinput);
 4150: 
 4151: 
 4152:     return 1;
 4153: }
 4154: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 4155: 		  0, 1, 0);
 4156: 
 4157: #   Retrieve and remove temporary files created by/during autoenrollment.
 4158: #
 4159: # Formal Parameters:
 4160: #    $cmd      - The command that got us dispatched.
 4161: #    $tail     - The tail of the command.  In our case this is a colon 
 4162: #                separated list that will be split into:
 4163: #                $filename - The name of the file to remove.
 4164: #                            The filename is given as a path relative to
 4165: #                            the LonCAPA temp file directory.
 4166: #    $client   - Socket open on the client.
 4167: #
 4168: # Returns:
 4169: #   1     - Continue processing.
 4170: sub retrieve_auto_file_handler {
 4171:     my ($cmd, $tail, $client)    = @_;
 4172:     my $userinput                = "cmd:$tail";
 4173: 
 4174:     my ($filename)   = split(/:/, $tail);
 4175: 
 4176:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 4177:     if ( (-e $source) && ($filename ne '') ) {
 4178: 	my $reply = '';
 4179: 	if (open(my $fh,$source)) {
 4180: 	    while (<$fh>) {
 4181: 		chomp($_);
 4182: 		$_ =~ s/^\s+//g;
 4183: 		$_ =~ s/\s+$//g;
 4184: 		$reply .= $_;
 4185: 	    }
 4186: 	    close($fh);
 4187: 	    &Reply($client, &escape($reply)."\n", $userinput);
 4188: 
 4189: #   Does this have to be uncommented??!?  (RF).
 4190: #
 4191: #                                unlink($source);
 4192: 	} else {
 4193: 	    &Failure($client, "error\n", $userinput);
 4194: 	}
 4195:     } else {
 4196: 	&Failure($client, "error\n", $userinput);
 4197:     }
 4198:     
 4199: 
 4200:     return 1;
 4201: }
 4202: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 4203: 
 4204: #
 4205: #   Read and retrieve institutional code format (for support form).
 4206: # Formal Parameters:
 4207: #    $cmd        - Command that dispatched us.
 4208: #    $tail       - Tail of the command.  In this case it conatins 
 4209: #                  the course domain and the coursename.
 4210: #    $client     - Socket open on the client.
 4211: # Returns:
 4212: #    1     - Continue processing.
 4213: #
 4214: sub get_institutional_code_format_handler {
 4215:     my ($cmd, $tail, $client)   = @_;
 4216:     my $userinput               = "$cmd:$tail";
 4217: 
 4218:     my $reply;
 4219:     my($cdom,$course) = split(/:/,$tail);
 4220:     my @pairs = split/\&/,$course;
 4221:     my %instcodes = ();
 4222:     my %codes = ();
 4223:     my @codetitles = ();
 4224:     my %cat_titles = ();
 4225:     my %cat_order = ();
 4226:     foreach (@pairs) {
 4227: 	my ($key,$value) = split/=/,$_;
 4228: 	$instcodes{&unescape($key)} = &unescape($value);
 4229:     }
 4230:     my $formatreply = &localenroll::instcode_format($cdom,
 4231: 						    \%instcodes,
 4232: 						    \%codes,
 4233: 						    \@codetitles,
 4234: 						    \%cat_titles,
 4235: 						    \%cat_order);
 4236:     if ($formatreply eq 'ok') {
 4237: 	my $codes_str = &hash2str(%codes);
 4238: 	my $codetitles_str = &array2str(@codetitles);
 4239: 	my $cat_titles_str = &hash2str(%cat_titles);
 4240: 	my $cat_order_str = &hash2str(%cat_order);
 4241: 	&Reply($client,
 4242: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 4243: 	       .$cat_order_str."\n",
 4244: 	       $userinput);
 4245:     } else {
 4246: 	# this else branch added by RF since if not ok, lonc will
 4247: 	# hang waiting on reply until timeout.
 4248: 	#
 4249: 	&Reply($client, "format_error\n", $userinput);
 4250:     }
 4251:     
 4252:     return 1;
 4253: }
 4254: &register_handler("autoinstcodeformat",
 4255: 		  \&get_institutional_code_format_handler,0,1,0);
 4256: 
 4257: #
 4258: # Gets a student's photo to exist (in the correct image type) in the user's 
 4259: # directory.
 4260: # Formal Parameters:
 4261: #    $cmd     - The command request that got us dispatched.
 4262: #    $tail    - A colon separated set of words that will be split into:
 4263: #               $domain - student's domain
 4264: #               $uname  - student username
 4265: #               $type   - image type desired
 4266: #    $client  - The socket open on the client.
 4267: # Returns:
 4268: #    1 - continue processing.
 4269: sub student_photo_handler {
 4270:     my ($cmd, $tail, $client) = @_;
 4271:     my ($domain,$uname,$type) = split(/:/, $tail);
 4272: 
 4273:     my $path=&propath($domain,$uname).
 4274: 	'/userfiles/internal/studentphoto.'.$type;
 4275:     if (-e $path) {
 4276: 	&Reply($client,"ok\n","$cmd:$tail");
 4277: 	return 1;
 4278:     }
 4279:     &mkpath($path);
 4280:     my $file=&localstudentphoto::fetch($domain,$uname);
 4281:     if (!$file) {
 4282: 	&Failure($client,"unavailable\n","$cmd:$tail");
 4283: 	return 1;
 4284:     }
 4285:     if (!-e $path) { &convert_photo($file,$path); }
 4286:     if (-e $path) {
 4287: 	&Reply($client,"ok\n","$cmd:$tail");
 4288: 	return 1;
 4289:     }
 4290:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
 4291:     return 1;
 4292: }
 4293: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
 4294: 
 4295: # mkpath makes all directories for a file, expects an absolute path with a
 4296: # file or a trailing / if just a dir is passed
 4297: # returns 1 on success 0 on failure
 4298: sub mkpath {
 4299:     my ($file)=@_;
 4300:     my @parts=split(/\//,$file,-1);
 4301:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
 4302:     for (my $i=3;$i<= ($#parts-1);$i++) {
 4303: 	$now.='/'.$parts[$i]; 
 4304: 	if (!-e $now) {
 4305: 	    if  (!mkdir($now,0770)) { return 0; }
 4306: 	}
 4307:     }
 4308:     return 1;
 4309: }
 4310: 
 4311: #---------------------------------------------------------------
 4312: #
 4313: #   Getting, decoding and dispatching requests:
 4314: #
 4315: #
 4316: #   Get a Request:
 4317: #   Gets a Request message from the client.  The transaction
 4318: #   is defined as a 'line' of text.  We remove the new line
 4319: #   from the text line.  
 4320: #
 4321: sub get_request {
 4322:     my $input = <$client>;
 4323:     chomp($input);
 4324: 
 4325:     &Debug("get_request: Request = $input\n");
 4326: 
 4327:     &status('Processing '.$clientname.':'.$input);
 4328: 
 4329:     return $input;
 4330: }
 4331: #---------------------------------------------------------------
 4332: #
 4333: #  Process a request.  This sub should shrink as each action
 4334: #  gets farmed out into a separat sub that is registered 
 4335: #  with the dispatch hash.  
 4336: #
 4337: # Parameters:
 4338: #    user_input   - The request received from the client (lonc).
 4339: # Returns:
 4340: #    true to keep processing, false if caller should exit.
 4341: #
 4342: sub process_request {
 4343:     my ($userinput) = @_;      # Easier for now to break style than to
 4344:                                 # fix all the userinput -> user_input.
 4345:     my $wasenc    = 0;		# True if request was encrypted.
 4346: # ------------------------------------------------------------ See if encrypted
 4347:     if ($userinput =~ /^enc/) {
 4348: 	$userinput = decipher($userinput);
 4349: 	$wasenc=1;
 4350: 	if(!$userinput) {	# Cipher not defined.
 4351: 	    &Failure($client, "error: Encrypted data without negotated key\n");
 4352: 	    return 0;
 4353: 	}
 4354:     }
 4355:     Debug("process_request: $userinput\n");
 4356:     
 4357:     #  
 4358:     #   The 'correct way' to add a command to lond is now to
 4359:     #   write a sub to execute it and Add it to the command dispatch
 4360:     #   hash via a call to register_handler..  The comments to that
 4361:     #   sub should give you enough to go on to show how to do this
 4362:     #   along with the examples that are building up as this code
 4363:     #   is getting refactored.   Until all branches of the
 4364:     #   if/elseif monster below have been factored out into
 4365:     #   separate procesor subs, if the dispatch hash is missing
 4366:     #   the command keyword, we will fall through to the remainder
 4367:     #   of the if/else chain below in order to keep this thing in 
 4368:     #   working order throughout the transmogrification.
 4369: 
 4370:     my ($command, $tail) = split(/:/, $userinput, 2);
 4371:     chomp($command);
 4372:     chomp($tail);
 4373:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 4374:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 4375:     if(!$tail) {
 4376: 	$tail ="";		# defined but blank.
 4377:     }
 4378: 
 4379:     &Debug("Command received: $command, encoded = $wasenc");
 4380: 
 4381:     if(defined $Dispatcher{$command}) {
 4382: 
 4383: 	my $dispatch_info = $Dispatcher{$command};
 4384: 	my $handler       = $$dispatch_info[0];
 4385: 	my $need_encode   = $$dispatch_info[1];
 4386: 	my $client_types  = $$dispatch_info[2];
 4387: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 4388: 	      ."ClientType $client_types");
 4389:       
 4390: 	#  Validate the request:
 4391:       
 4392: 	my $ok = 1;
 4393: 	my $requesterprivs = 0;
 4394: 	if(&isClient()) {
 4395: 	    $requesterprivs |= $CLIENT_OK;
 4396: 	}
 4397: 	if(&isManager()) {
 4398: 	    $requesterprivs |= $MANAGER_OK;
 4399: 	}
 4400: 	if($need_encode && (!$wasenc)) {
 4401: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 4402: 	    $ok = 0;
 4403: 	}
 4404: 	if(($client_types & $requesterprivs) == 0) {
 4405: 	    Debug("Client not privileged to do this operation");
 4406: 	    $ok = 0;
 4407: 	}
 4408: 
 4409: 	if($ok) {
 4410: 	    Debug("Dispatching to handler $command $tail");
 4411: 	    my $keep_going = &$handler($command, $tail, $client);
 4412: 	    return $keep_going;
 4413: 	} else {
 4414: 	    Debug("Refusing to dispatch because client did not match requirements");
 4415: 	    Failure($client, "refused\n", $userinput);
 4416: 	    return 1;
 4417: 	}
 4418: 
 4419:     }    
 4420: 
 4421:     print $client "unknown_cmd\n";
 4422: # -------------------------------------------------------------------- complete
 4423:     Debug("process_request - returning 1");
 4424:     return 1;
 4425: }
 4426: #
 4427: #   Decipher encoded traffic
 4428: #  Parameters:
 4429: #     input      - Encoded data.
 4430: #  Returns:
 4431: #     Decoded data or undef if encryption key was not yet negotiated.
 4432: #  Implicit input:
 4433: #     cipher  - This global holds the negotiated encryption key.
 4434: #
 4435: sub decipher {
 4436:     my ($input)  = @_;
 4437:     my $output = '';
 4438:     
 4439:     
 4440:     if($cipher) {
 4441: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 4442: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 4443: 	    $output .= 
 4444: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 4445: 	}
 4446: 	return substr($output, 0, $enclength);
 4447:     } else {
 4448: 	return undef;
 4449:     }
 4450: }
 4451: 
 4452: #
 4453: #   Register a command processor.  This function is invoked to register a sub
 4454: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 4455: #   dispatch requests to an appropriate sub, and do the top level validity checking
 4456: #   as well:
 4457: #    - Is the keyword recognized.
 4458: #    - Is the proper client type attempting the request.
 4459: #    - Is the request encrypted if it has to be.
 4460: #   Parameters:
 4461: #    $request_name         - Name of the request being registered.
 4462: #                           This is the command request that will match
 4463: #                           against the hash keywords to lookup the information
 4464: #                           associated with the dispatch information.
 4465: #    $procedure           - Reference to a sub to call to process the request.
 4466: #                           All subs get called as follows:
 4467: #                             Procedure($cmd, $tail, $replyfd, $key)
 4468: #                             $cmd    - the actual keyword that invoked us.
 4469: #                             $tail   - the tail of the request that invoked us.
 4470: #                             $replyfd- File descriptor connected to the client
 4471: #    $must_encode          - True if the request must be encoded to be good.
 4472: #    $client_ok            - True if it's ok for a client to request this.
 4473: #    $manager_ok           - True if it's ok for a manager to request this.
 4474: # Side effects:
 4475: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 4476: #      - On failure, the program will die as it's a bad internal bug to try to 
 4477: #        register a duplicate command handler.
 4478: #
 4479: sub register_handler {
 4480:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 4481: 
 4482:     #  Don't allow duplication#
 4483:    
 4484:     if (defined $Dispatcher{$request_name}) {
 4485: 	die "Attempting to define a duplicate request handler for $request_name\n";
 4486:     }
 4487:     #   Build the client type mask:
 4488:     
 4489:     my $client_type_mask = 0;
 4490:     if($client_ok) {
 4491: 	$client_type_mask  |= $CLIENT_OK;
 4492:     }
 4493:     if($manager_ok) {
 4494: 	$client_type_mask  |= $MANAGER_OK;
 4495:     }
 4496:    
 4497:     #  Enter the hash:
 4498:       
 4499:     my @entry = ($procedure, $must_encode, $client_type_mask);
 4500:    
 4501:     $Dispatcher{$request_name} = \@entry;
 4502:    
 4503: }
 4504: 
 4505: 
 4506: #------------------------------------------------------------------
 4507: 
 4508: 
 4509: 
 4510: 
 4511: #
 4512: #  Convert an error return code from lcpasswd to a string value.
 4513: #
 4514: sub lcpasswdstrerror {
 4515:     my $ErrorCode = shift;
 4516:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 4517: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 4518:     } else {
 4519: 	return $passwderrors[$ErrorCode];
 4520:     }
 4521: }
 4522: 
 4523: #
 4524: # Convert an error return code from lcuseradd to a string value:
 4525: #
 4526: sub lcuseraddstrerror {
 4527:     my $ErrorCode = shift;
 4528:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
 4529: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
 4530:     } else {
 4531: 	return $adderrors[$ErrorCode];
 4532:     }
 4533: }
 4534: 
 4535: # grabs exception and records it to log before exiting
 4536: sub catchexception {
 4537:     my ($error)=@_;
 4538:     $SIG{'QUIT'}='DEFAULT';
 4539:     $SIG{__DIE__}='DEFAULT';
 4540:     &status("Catching exception");
 4541:     &logthis("<font color='red'>CRITICAL: "
 4542:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
 4543:      ."a crash with this error msg->[$error]</font>");
 4544:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 4545:     if ($client) { print $client "error: $error\n"; }
 4546:     $server->close();
 4547:     die($error);
 4548: }
 4549: sub timeout {
 4550:     &status("Handling Timeout");
 4551:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 4552:     &catchexception('Timeout');
 4553: }
 4554: # -------------------------------- Set signal handlers to record abnormal exits
 4555: 
 4556: 
 4557: $SIG{'QUIT'}=\&catchexception;
 4558: $SIG{__DIE__}=\&catchexception;
 4559: 
 4560: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 4561: &status("Read loncapa.conf and loncapa_apache.conf");
 4562: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 4563: %perlvar=%{$perlvarref};
 4564: undef $perlvarref;
 4565: 
 4566: # ----------------------------- Make sure this process is running from user=www
 4567: my $wwwid=getpwnam('www');
 4568: if ($wwwid!=$<) {
 4569:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 4570:    my $subj="LON: $currenthostid User ID mismatch";
 4571:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
 4572:  mailto $emailto -s '$subj' > /dev/null");
 4573:    exit 1;
 4574: }
 4575: 
 4576: # --------------------------------------------- Check if other instance running
 4577: 
 4578: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 4579: 
 4580: if (-e $pidfile) {
 4581:    my $lfh=IO::File->new("$pidfile");
 4582:    my $pide=<$lfh>;
 4583:    chomp($pide);
 4584:    if (kill 0 => $pide) { die "already running"; }
 4585: }
 4586: 
 4587: # ------------------------------------------------------------- Read hosts file
 4588: 
 4589: 
 4590: 
 4591: # establish SERVER socket, bind and listen.
 4592: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 4593:                                 Type      => SOCK_STREAM,
 4594:                                 Proto     => 'tcp',
 4595:                                 Reuse     => 1,
 4596:                                 Listen    => 10 )
 4597:   or die "making socket: $@\n";
 4598: 
 4599: # --------------------------------------------------------- Do global variables
 4600: 
 4601: # global variables
 4602: 
 4603: my %children               = ();       # keys are current child process IDs
 4604: 
 4605: sub REAPER {                        # takes care of dead children
 4606:     $SIG{CHLD} = \&REAPER;
 4607:     &status("Handling child death");
 4608:     my $pid;
 4609:     do {
 4610: 	$pid = waitpid(-1,&WNOHANG());
 4611: 	if (defined($children{$pid})) {
 4612: 	    &logthis("Child $pid died");
 4613: 	    delete($children{$pid});
 4614: 	} elsif ($pid > 0) {
 4615: 	    &logthis("Unknown Child $pid died");
 4616: 	}
 4617:     } while ( $pid > 0 );
 4618:     foreach my $child (keys(%children)) {
 4619: 	$pid = waitpid($child,&WNOHANG());
 4620: 	if ($pid > 0) {
 4621: 	    &logthis("Child $child - $pid looks like we missed it's death");
 4622: 	    delete($children{$pid});
 4623: 	}
 4624:     }
 4625:     &status("Finished Handling child death");
 4626: }
 4627: 
 4628: sub HUNTSMAN {                      # signal handler for SIGINT
 4629:     &status("Killing children (INT)");
 4630:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 4631:     kill 'INT' => keys %children;
 4632:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 4633:     my $execdir=$perlvar{'lonDaemons'};
 4634:     unlink("$execdir/logs/lond.pid");
 4635:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 4636:     &status("Done killing children");
 4637:     exit;                           # clean up with dignity
 4638: }
 4639: 
 4640: sub HUPSMAN {                      # signal handler for SIGHUP
 4641:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 4642:     &status("Killing children for restart (HUP)");
 4643:     kill 'INT' => keys %children;
 4644:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 4645:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 4646:     my $execdir=$perlvar{'lonDaemons'};
 4647:     unlink("$execdir/logs/lond.pid");
 4648:     &status("Restarting self (HUP)");
 4649:     exec("$execdir/lond");         # here we go again
 4650: }
 4651: 
 4652: #
 4653: #    Kill off hashes that describe the host table prior to re-reading it.
 4654: #    Hashes affected are:
 4655: #       %hostid, %hostdom %hostip %hostdns.
 4656: #
 4657: sub KillHostHashes {
 4658:     foreach my $key (keys %hostid) {
 4659: 	delete $hostid{$key};
 4660:     }
 4661:     foreach my $key (keys %hostdom) {
 4662: 	delete $hostdom{$key};
 4663:     }
 4664:     foreach my $key (keys %hostip) {
 4665: 	delete $hostip{$key};
 4666:     }
 4667:     foreach my $key (keys %hostdns) {
 4668: 	delete $hostdns{$key};
 4669:     }
 4670: }
 4671: #
 4672: #   Read in the host table from file and distribute it into the various hashes:
 4673: #
 4674: #    - %hostid  -  Indexed by IP, the loncapa hostname.
 4675: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
 4676: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
 4677: sub ReadHostTable {
 4678: 
 4679:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
 4680:     my $myloncapaname = $perlvar{'lonHostID'};
 4681:     Debug("My loncapa name is : $myloncapaname");
 4682:     my %name_to_ip;
 4683:     while (my $configline=<CONFIG>) {
 4684: 	if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
 4685: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 4686: 	    $name=~s/\s//g;
 4687: 	    my $ip;
 4688: 	    if (!exists($name_to_ip{$name})) {
 4689: 		$ip = gethostbyname($name);
 4690: 		if (!$ip || length($ip) ne 4) {
 4691: 		    &logthis("Skipping host $id name $name no IP found\n");
 4692: 		    next;
 4693: 		}
 4694: 		$ip=inet_ntoa($ip);
 4695: 		$name_to_ip{$name} = $ip;
 4696: 	    } else {
 4697: 		$ip = $name_to_ip{$name};
 4698: 	    }
 4699: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
 4700: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
 4701: 	    $hostip{$id}=$ip;         # IP address of host.
 4702: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
 4703: 
 4704: 	    if ($id eq $perlvar{'lonHostID'}) { 
 4705: 		Debug("Found me in the host table: $name");
 4706: 		$thisserver=$name; 
 4707: 	    }
 4708: 	}
 4709:     }
 4710:     close(CONFIG);
 4711: }
 4712: #
 4713: #  Reload the Apache daemon's state.
 4714: #  This is done by invoking /home/httpd/perl/apachereload
 4715: #  a setuid perl script that can be root for us to do this job.
 4716: #
 4717: sub ReloadApache {
 4718:     my $execdir = $perlvar{'lonDaemons'};
 4719:     my $script  = $execdir."/apachereload";
 4720:     system($script);
 4721: }
 4722: 
 4723: #
 4724: #   Called in response to a USR2 signal.
 4725: #   - Reread hosts.tab
 4726: #   - All children connected to hosts that were removed from hosts.tab
 4727: #     are killed via SIGINT
 4728: #   - All children connected to previously existing hosts are sent SIGUSR1
 4729: #   - Our internal hosts hash is updated to reflect the new contents of
 4730: #     hosts.tab causing connections from hosts added to hosts.tab to
 4731: #     now be honored.
 4732: #
 4733: sub UpdateHosts {
 4734:     &status("Reload hosts.tab");
 4735:     logthis('<font color="blue"> Updating connections </font>');
 4736:     #
 4737:     #  The %children hash has the set of IP's we currently have children
 4738:     #  on.  These need to be matched against records in the hosts.tab
 4739:     #  Any ip's no longer in the table get killed off they correspond to
 4740:     #  either dropped or changed hosts.  Note that the re-read of the table
 4741:     #  will take care of new and changed hosts as connections come into being.
 4742: 
 4743: 
 4744:     KillHostHashes;
 4745:     ReadHostTable;
 4746: 
 4747:     foreach my $child (keys %children) {
 4748: 	my $childip = $children{$child};
 4749: 	if(!$hostid{$childip}) {
 4750: 	    logthis('<font color="blue"> UpdateHosts killing child '
 4751: 		    ." $child for ip $childip </font>");
 4752: 	    kill('INT', $child);
 4753: 	} else {
 4754: 	    logthis('<font color="green"> keeping child for ip '
 4755: 		    ." $childip (pid=$child) </font>");
 4756: 	}
 4757:     }
 4758:     ReloadApache;
 4759:     &status("Finished reloading hosts.tab");
 4760: }
 4761: 
 4762: 
 4763: sub checkchildren {
 4764:     &status("Checking on the children (sending signals)");
 4765:     &initnewstatus();
 4766:     &logstatus();
 4767:     &logthis('Going to check on the children');
 4768:     my $docdir=$perlvar{'lonDocRoot'};
 4769:     foreach (sort keys %children) {
 4770: 	#sleep 1;
 4771:         unless (kill 'USR1' => $_) {
 4772: 	    &logthis ('Child '.$_.' is dead');
 4773:             &logstatus($$.' is dead');
 4774: 	    delete($children{$_});
 4775:         } 
 4776:     }
 4777:     sleep 5;
 4778:     $SIG{ALRM} = sub { Debug("timeout"); 
 4779: 		       die "timeout";  };
 4780:     $SIG{__DIE__} = 'DEFAULT';
 4781:     &status("Checking on the children (waiting for reports)");
 4782:     foreach (sort keys %children) {
 4783:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 4784:           eval {
 4785:             alarm(300);
 4786: 	    &logthis('Child '.$_.' did not respond');
 4787: 	    kill 9 => $_;
 4788: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 4789: 	    #$subj="LON: $currenthostid killed lond process $_";
 4790: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 4791: 	    #$execdir=$perlvar{'lonDaemons'};
 4792: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 4793: 	    delete($children{$_});
 4794: 	    alarm(0);
 4795: 	  }
 4796:         }
 4797:     }
 4798:     $SIG{ALRM} = 'DEFAULT';
 4799:     $SIG{__DIE__} = \&catchexception;
 4800:     &status("Finished checking children");
 4801:     &logthis('Finished Checking children');
 4802: }
 4803: 
 4804: # --------------------------------------------------------------------- Logging
 4805: 
 4806: sub logthis {
 4807:     my $message=shift;
 4808:     my $execdir=$perlvar{'lonDaemons'};
 4809:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 4810:     my $now=time;
 4811:     my $local=localtime($now);
 4812:     $lastlog=$local.': '.$message;
 4813:     print $fh "$local ($$): $message\n";
 4814: }
 4815: 
 4816: # ------------------------- Conditional log if $DEBUG true.
 4817: sub Debug {
 4818:     my $message = shift;
 4819:     if($DEBUG) {
 4820: 	&logthis($message);
 4821:     }
 4822: }
 4823: 
 4824: #
 4825: #   Sub to do replies to client.. this gives a hook for some
 4826: #   debug tracing too:
 4827: #  Parameters:
 4828: #     fd      - File open on client.
 4829: #     reply   - Text to send to client.
 4830: #     request - Original request from client.
 4831: #
 4832: sub Reply {
 4833:     my ($fd, $reply, $request) = @_;
 4834:     print $fd $reply;
 4835:     Debug("Request was $request  Reply was $reply");
 4836: 
 4837:     $Transactions++;
 4838: }
 4839: 
 4840: 
 4841: #
 4842: #    Sub to report a failure.
 4843: #    This function:
 4844: #     -   Increments the failure statistic counters.
 4845: #     -   Invokes Reply to send the error message to the client.
 4846: # Parameters:
 4847: #    fd       - File descriptor open on the client
 4848: #    reply    - Reply text to emit.
 4849: #    request  - The original request message (used by Reply
 4850: #               to debug if that's enabled.
 4851: # Implicit outputs:
 4852: #    $Failures- The number of failures is incremented.
 4853: #    Reply (invoked here) sends a message to the 
 4854: #    client:
 4855: #
 4856: sub Failure {
 4857:     my $fd      = shift;
 4858:     my $reply   = shift;
 4859:     my $request = shift;
 4860:    
 4861:     $Failures++;
 4862:     Reply($fd, $reply, $request);      # That's simple eh?
 4863: }
 4864: # ------------------------------------------------------------------ Log status
 4865: 
 4866: sub logstatus {
 4867:     &status("Doing logging");
 4868:     my $docdir=$perlvar{'lonDocRoot'};
 4869:     {
 4870: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 4871:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 4872:         $fh->close();
 4873:     }
 4874:     &status("Finished $$.txt");
 4875:     {
 4876: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 4877: 	flock(LOG,LOCK_EX);
 4878: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 4879: 	    .$status."\t".$lastlog."\t $keymode\n";
 4880: 	flock(LOG,LOCK_UN);
 4881: 	close(LOG);
 4882:     }
 4883:     &status("Finished logging");
 4884: }
 4885: 
 4886: sub initnewstatus {
 4887:     my $docdir=$perlvar{'lonDocRoot'};
 4888:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 4889:     my $now=time;
 4890:     my $local=localtime($now);
 4891:     print $fh "LOND status $local - parent $$\n\n";
 4892:     opendir(DIR,"$docdir/lon-status/londchld");
 4893:     while (my $filename=readdir(DIR)) {
 4894:         unlink("$docdir/lon-status/londchld/$filename");
 4895:     }
 4896:     closedir(DIR);
 4897: }
 4898: 
 4899: # -------------------------------------------------------------- Status setting
 4900: 
 4901: sub status {
 4902:     my $what=shift;
 4903:     my $now=time;
 4904:     my $local=localtime($now);
 4905:     $status=$local.': '.$what;
 4906:     $0='lond: '.$what.' '.$local;
 4907: }
 4908: 
 4909: # -------------------------------------------------------- Escape Special Chars
 4910: 
 4911: sub escape {
 4912:     my $str=shift;
 4913:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 4914:     return $str;
 4915: }
 4916: 
 4917: # ----------------------------------------------------- Un-Escape Special Chars
 4918: 
 4919: sub unescape {
 4920:     my $str=shift;
 4921:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 4922:     return $str;
 4923: }
 4924: 
 4925: # ----------------------------------------------------------- Send USR1 to lonc
 4926: 
 4927: sub reconlonc {
 4928:     my $peerfile=shift;
 4929:     &logthis("Trying to reconnect for $peerfile");
 4930:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
 4931:     if (my $fh=IO::File->new("$loncfile")) {
 4932: 	my $loncpid=<$fh>;
 4933:         chomp($loncpid);
 4934:         if (kill 0 => $loncpid) {
 4935: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
 4936:             kill USR1 => $loncpid;
 4937:         } else {
 4938: 	    &logthis(
 4939:               "<font color='red'>CRITICAL: "
 4940:              ."lonc at pid $loncpid not responding, giving up</font>");
 4941:         }
 4942:     } else {
 4943:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
 4944:     }
 4945: }
 4946: 
 4947: # -------------------------------------------------- Non-critical communication
 4948: 
 4949: sub subreply {
 4950:     my ($cmd,$server)=@_;
 4951:     my $peerfile="$perlvar{'lonSockDir'}/$server";
 4952:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 4953:                                       Type    => SOCK_STREAM,
 4954:                                       Timeout => 10)
 4955:        or return "con_lost";
 4956:     print $sclient "$cmd\n";
 4957:     my $answer=<$sclient>;
 4958:     chomp($answer);
 4959:     if (!$answer) { $answer="con_lost"; }
 4960:     return $answer;
 4961: }
 4962: 
 4963: sub reply {
 4964:   my ($cmd,$server)=@_;
 4965:   my $answer;
 4966:   if ($server ne $currenthostid) { 
 4967:     $answer=subreply($cmd,$server);
 4968:     if ($answer eq 'con_lost') {
 4969: 	$answer=subreply("ping",$server);
 4970:         if ($answer ne $server) {
 4971: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
 4972:            &reconlonc("$perlvar{'lonSockDir'}/$server");
 4973:         }
 4974:         $answer=subreply($cmd,$server);
 4975:     }
 4976:   } else {
 4977:     $answer='self_reply';
 4978:   } 
 4979:   return $answer;
 4980: }
 4981: 
 4982: # -------------------------------------------------------------- Talk to lonsql
 4983: 
 4984: sub sql_reply {
 4985:     my ($cmd)=@_;
 4986:     my $answer=&sub_sql_reply($cmd);
 4987:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 4988:     return $answer;
 4989: }
 4990: 
 4991: sub sub_sql_reply {
 4992:     my ($cmd)=@_;
 4993:     my $unixsock="mysqlsock";
 4994:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 4995:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 4996:                                       Type    => SOCK_STREAM,
 4997:                                       Timeout => 10)
 4998:        or return "con_lost";
 4999:     print $sclient "$cmd\n";
 5000:     my $answer=<$sclient>;
 5001:     chomp($answer);
 5002:     if (!$answer) { $answer="con_lost"; }
 5003:     return $answer;
 5004: }
 5005: 
 5006: # -------------------------------------------- Return path to profile directory
 5007: 
 5008: sub propath {
 5009:     my ($udom,$uname)=@_;
 5010:     $udom=~s/\W//g;
 5011:     $uname=~s/\W//g;
 5012:     my $subdir=$uname.'__';
 5013:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5014:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
 5015:     return $proname;
 5016: } 
 5017: 
 5018: # --------------------------------------- Is this the home server of an author?
 5019: 
 5020: sub ishome {
 5021:     my $author=shift;
 5022:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 5023:     my ($udom,$uname)=split(/\//,$author);
 5024:     my $proname=propath($udom,$uname);
 5025:     if (-e $proname) {
 5026: 	return 'owner';
 5027:     } else {
 5028:         return 'not_owner';
 5029:     }
 5030: }
 5031: 
 5032: # ======================================================= Continue main program
 5033: # ---------------------------------------------------- Fork once and dissociate
 5034: 
 5035: my $fpid=fork;
 5036: exit if $fpid;
 5037: die "Couldn't fork: $!" unless defined ($fpid);
 5038: 
 5039: POSIX::setsid() or die "Can't start new session: $!";
 5040: 
 5041: # ------------------------------------------------------- Write our PID on disk
 5042: 
 5043: my $execdir=$perlvar{'lonDaemons'};
 5044: open (PIDSAVE,">$execdir/logs/lond.pid");
 5045: print PIDSAVE "$$\n";
 5046: close(PIDSAVE);
 5047: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 5048: &status('Starting');
 5049: 
 5050: 
 5051: 
 5052: # ----------------------------------------------------- Install signal handlers
 5053: 
 5054: 
 5055: $SIG{CHLD} = \&REAPER;
 5056: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 5057: $SIG{HUP}  = \&HUPSMAN;
 5058: $SIG{USR1} = \&checkchildren;
 5059: $SIG{USR2} = \&UpdateHosts;
 5060: 
 5061: #  Read the host hashes:
 5062: 
 5063: ReadHostTable;
 5064: 
 5065: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
 5066: 
 5067: # --------------------------------------------------------------
 5068: #   Accept connections.  When a connection comes in, it is validated
 5069: #   and if good, a child process is created to process transactions
 5070: #   along the connection.
 5071: 
 5072: while (1) {
 5073:     &status('Starting accept');
 5074:     $client = $server->accept() or next;
 5075:     &status('Accepted '.$client.' off to spawn');
 5076:     make_new_child($client);
 5077:     &status('Finished spawning');
 5078: }
 5079: 
 5080: sub make_new_child {
 5081:     my $pid;
 5082: #    my $cipher;     # Now global
 5083:     my $sigset;
 5084: 
 5085:     $client = shift;
 5086:     &status('Starting new child '.$client);
 5087:     &logthis('<font color="green"> Attempting to start child ('.$client.
 5088: 	     ")</font>");    
 5089:     # block signal for fork
 5090:     $sigset = POSIX::SigSet->new(SIGINT);
 5091:     sigprocmask(SIG_BLOCK, $sigset)
 5092:         or die "Can't block SIGINT for fork: $!\n";
 5093: 
 5094:     die "fork: $!" unless defined ($pid = fork);
 5095: 
 5096:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 5097: 	                               # connection liveness.
 5098: 
 5099:     #
 5100:     #  Figure out who we're talking to so we can record the peer in 
 5101:     #  the pid hash.
 5102:     #
 5103:     my $caller = getpeername($client);
 5104:     my ($port,$iaddr);
 5105:     if (defined($caller) && length($caller) > 0) {
 5106: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 5107:     } else {
 5108: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 5109:     }
 5110:     if (defined($iaddr)) {
 5111: 	$clientip  = inet_ntoa($iaddr);
 5112: 	Debug("Connected with $clientip");
 5113:     } else {
 5114: 	&logthis("Unable to determine clientip");
 5115: 	$clientip='Unavailable';
 5116:     }
 5117:     
 5118:     if ($pid) {
 5119:         # Parent records the child's birth and returns.
 5120:         sigprocmask(SIG_UNBLOCK, $sigset)
 5121:             or die "Can't unblock SIGINT for fork: $!\n";
 5122:         $children{$pid} = $clientip;
 5123:         &status('Started child '.$pid);
 5124:         return;
 5125:     } else {
 5126:         # Child can *not* return from this subroutine.
 5127:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 5128:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 5129:                                 #don't get intercepted
 5130:         $SIG{USR1}= \&logstatus;
 5131:         $SIG{ALRM}= \&timeout;
 5132:         $lastlog='Forked ';
 5133:         $status='Forked';
 5134: 
 5135:         # unblock signals
 5136:         sigprocmask(SIG_UNBLOCK, $sigset)
 5137:             or die "Can't unblock SIGINT for fork: $!\n";
 5138: 
 5139: #        my $tmpsnum=0;            # Now global
 5140: #---------------------------------------------------- kerberos 5 initialization
 5141:         &Authen::Krb5::init_context();
 5142: 	unless (($dist eq 'fedora4') || ($dist eq 'suse9.3')) {
 5143: 	    &Authen::Krb5::init_ets();
 5144: 	}
 5145: 
 5146: 	&status('Accepted connection');
 5147: # =============================================================================
 5148:             # do something with the connection
 5149: # -----------------------------------------------------------------------------
 5150: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 5151: 
 5152: 	ReadManagerTable;	# May also be a manager!!
 5153: 	
 5154: 	my $outsideip=$clientip;
 5155: 	if ($clientip eq '127.0.0.1') {
 5156: 	    $outsideip=$hostip{$perlvar{'lonHostID'}};
 5157: 	}
 5158: 
 5159: 	my $clientrec=($hostid{$outsideip}     ne undef);
 5160: 	my $ismanager=($managers{$outsideip}    ne undef);
 5161: 	$clientname  = "[unknonwn]";
 5162: 	if($clientrec) {	# Establish client type.
 5163: 	    $ConnectionType = "client";
 5164: 	    $clientname = $hostid{$outsideip};
 5165: 	    if($ismanager) {
 5166: 		$ConnectionType = "both";
 5167: 	    }
 5168: 	} else {
 5169: 	    $ConnectionType = "manager";
 5170: 	    $clientname = $managers{$outsideip};
 5171: 	}
 5172: 	my $clientok;
 5173: 
 5174: 	if ($clientrec || $ismanager) {
 5175: 	    &status("Waiting for init from $clientip $clientname");
 5176: 	    &logthis('<font color="yellow">INFO: Connection, '.
 5177: 		     $clientip.
 5178: 		  " ($clientname) connection type = $ConnectionType </font>" );
 5179: 	    &status("Connecting $clientip  ($clientname))"); 
 5180: 	    my $remotereq=<$client>;
 5181: 	    chomp($remotereq);
 5182: 	    Debug("Got init: $remotereq");
 5183: 	    my $inikeyword = split(/:/, $remotereq);
 5184: 	    if ($remotereq =~ /^init/) {
 5185: 		&sethost("sethost:$perlvar{'lonHostID'}");
 5186: 		#
 5187: 		#  If the remote is attempting a local init... give that a try:
 5188: 		#
 5189: 		my ($i, $inittype) = split(/:/, $remotereq);
 5190: 
 5191: 		# If the connection type is ssl, but I didn't get my
 5192: 		# certificate files yet, then I'll drop  back to 
 5193: 		# insecure (if allowed).
 5194: 		
 5195: 		if($inittype eq "ssl") {
 5196: 		    my ($ca, $cert) = lonssl::CertificateFile;
 5197: 		    my $kfile       = lonssl::KeyFile;
 5198: 		    if((!$ca)   || 
 5199: 		       (!$cert) || 
 5200: 		       (!$kfile)) {
 5201: 			$inittype = ""; # This forces insecure attempt.
 5202: 			&logthis("<font color=\"blue\"> Certificates not "
 5203: 				 ."installed -- trying insecure auth</font>");
 5204: 		    } else {	# SSL certificates are in place so
 5205: 		    }		# Leave the inittype alone.
 5206: 		}
 5207: 
 5208: 		if($inittype eq "local") {
 5209: 		    my $key = LocalConnection($client, $remotereq);
 5210: 		    if($key) {
 5211: 			Debug("Got local key $key");
 5212: 			$clientok     = 1;
 5213: 			my $cipherkey = pack("H32", $key);
 5214: 			$cipher       = new IDEA($cipherkey);
 5215: 			print $client "ok:local\n";
 5216: 			&logthis('<font color="green"'
 5217: 				 . "Successful local authentication </font>");
 5218: 			$keymode = "local"
 5219: 		    } else {
 5220: 			Debug("Failed to get local key");
 5221: 			$clientok = 0;
 5222: 			shutdown($client, 3);
 5223: 			close $client;
 5224: 		    }
 5225: 		} elsif ($inittype eq "ssl") {
 5226: 		    my $key = SSLConnection($client);
 5227: 		    if ($key) {
 5228: 			$clientok = 1;
 5229: 			my $cipherkey = pack("H32", $key);
 5230: 			$cipher       = new IDEA($cipherkey);
 5231: 			&logthis('<font color="green">'
 5232: 				 ."Successfull ssl authentication with $clientname </font>");
 5233: 			$keymode = "ssl";
 5234: 	     
 5235: 		    } else {
 5236: 			$clientok = 0;
 5237: 			close $client;
 5238: 		    }
 5239: 	   
 5240: 		} else {
 5241: 		    my $ok = InsecureConnection($client);
 5242: 		    if($ok) {
 5243: 			$clientok = 1;
 5244: 			&logthis('<font color="green">'
 5245: 				 ."Successful insecure authentication with $clientname </font>");
 5246: 			print $client "ok\n";
 5247: 			$keymode = "insecure";
 5248: 		    } else {
 5249: 			&logthis('<font color="yellow">'
 5250: 				  ."Attempted insecure connection disallowed </font>");
 5251: 			close $client;
 5252: 			$clientok = 0;
 5253: 			
 5254: 		    }
 5255: 		}
 5256: 	    } else {
 5257: 		&logthis(
 5258: 			 "<font color='blue'>WARNING: "
 5259: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 5260: 		&status('No init '.$clientip);
 5261: 	    }
 5262: 	    
 5263: 	} else {
 5264: 	    &logthis(
 5265: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 5266: 	    &status('Hung up on '.$clientip);
 5267: 	}
 5268:  
 5269: 	if ($clientok) {
 5270: # ---------------- New known client connecting, could mean machine online again
 5271: 	    
 5272: 	    foreach my $id (keys(%hostip)) {
 5273: 		if ($hostip{$id} ne $clientip ||
 5274: 		    $hostip{$currenthostid} eq $clientip) {
 5275: 		    # no need to try to do recon's to myself
 5276: 		    next;
 5277: 		}
 5278: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
 5279: 	    }
 5280: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 5281: 	    &status('Will listen to '.$clientname);
 5282: # ------------------------------------------------------------ Process requests
 5283: 	    my $keep_going = 1;
 5284: 	    my $user_input;
 5285: 	    while(($user_input = get_request) && $keep_going) {
 5286: 		alarm(120);
 5287: 		Debug("Main: Got $user_input\n");
 5288: 		$keep_going = &process_request($user_input);
 5289: 		alarm(0);
 5290: 		&status('Listening to '.$clientname." ($keymode)");	   
 5291: 	    }
 5292: 
 5293: # --------------------------------------------- client unknown or fishy, refuse
 5294: 	}  else {
 5295: 	    print $client "refused\n";
 5296: 	    $client->close();
 5297: 	    &logthis("<font color='blue'>WARNING: "
 5298: 		     ."Rejected client $clientip, closing connection</font>");
 5299: 	}
 5300:     }            
 5301:     
 5302: # =============================================================================
 5303:     
 5304:     &logthis("<font color='red'>CRITICAL: "
 5305: 	     ."Disconnect from $clientip ($clientname)</font>");    
 5306:     
 5307:     
 5308:     # this exit is VERY important, otherwise the child will become
 5309:     # a producer of more and more children, forking yourself into
 5310:     # process death.
 5311:     exit;
 5312:     
 5313: }
 5314: #
 5315: #   Determine if a user is an author for the indicated domain.
 5316: #
 5317: # Parameters:
 5318: #    domain          - domain to check in .
 5319: #    user            - Name of user to check.
 5320: #
 5321: # Return:
 5322: #     1             - User is an author for domain.
 5323: #     0             - User is not an author for domain.
 5324: sub is_author {
 5325:     my ($domain, $user) = @_;
 5326: 
 5327:     &Debug("is_author: $user @ $domain");
 5328: 
 5329:     my $hashref = &tie_user_hash($domain, $user, "roles",
 5330: 				 &GDBM_READER());
 5331: 
 5332:     #  Author role should show up as a key /domain/_au
 5333: 
 5334:     my $key   = "/$domain/_au";
 5335:     my $value = $hashref->{$key};
 5336: 
 5337:     if(defined($value)) {
 5338: 	&Debug("$user @ $domain is an author");
 5339:     }
 5340: 
 5341:     return defined($value);
 5342: }
 5343: #
 5344: #   Checks to see if the input roleput request was to set
 5345: # an author role.  If so, invokes the lchtmldir script to set
 5346: # up a correct public_html 
 5347: # Parameters:
 5348: #    request   - The request sent to the rolesput subchunk.
 5349: #                We're looking for  /domain/_au
 5350: #    domain    - The domain in which the user is having roles doctored.
 5351: #    user      - Name of the user for which the role is being put.
 5352: #    authtype  - The authentication type associated with the user.
 5353: #
 5354: sub manage_permissions {
 5355:     my ($request, $domain, $user, $authtype) = @_;
 5356: 
 5357:     &Debug("manage_permissions: $request $domain $user $authtype");
 5358: 
 5359:     # See if the request is of the form /$domain/_au
 5360:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
 5361: 	my $execdir = $perlvar{'lonDaemons'};
 5362: 	my $userhome= "/home/$user" ;
 5363: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
 5364: 	&Debug("Setting homedir permissions for $userhome");
 5365: 	system("$execdir/lchtmldir $userhome $user $authtype");
 5366:     }
 5367: }
 5368: 
 5369: 
 5370: #
 5371: #  Return the full path of a user password file, whether it exists or not.
 5372: # Parameters:
 5373: #   domain     - Domain in which the password file lives.
 5374: #   user       - name of the user.
 5375: # Returns:
 5376: #    Full passwd path:
 5377: #
 5378: sub password_path {
 5379:     my ($domain, $user) = @_;
 5380:     return &propath($domain, $user).'/passwd';
 5381: }
 5382: 
 5383: #   Password Filename
 5384: #   Returns the path to a passwd file given domain and user... only if
 5385: #  it exists.
 5386: # Parameters:
 5387: #   domain    - Domain in which to search.
 5388: #   user      - username.
 5389: # Returns:
 5390: #   - If the password file exists returns its path.
 5391: #   - If the password file does not exist, returns undefined.
 5392: #
 5393: sub password_filename {
 5394:     my ($domain, $user) = @_;
 5395: 
 5396:     Debug ("PasswordFilename called: dom = $domain user = $user");
 5397: 
 5398:     my $path  = &password_path($domain, $user);
 5399:     Debug("PasswordFilename got path: $path");
 5400:     if(-e $path) {
 5401: 	return $path;
 5402:     } else {
 5403: 	return undef;
 5404:     }
 5405: }
 5406: 
 5407: #
 5408: #   Rewrite the contents of the user's passwd file.
 5409: #  Parameters:
 5410: #    domain    - domain of the user.
 5411: #    name      - User's name.
 5412: #    contents  - New contents of the file.
 5413: # Returns:
 5414: #   0    - Failed.
 5415: #   1    - Success.
 5416: #
 5417: sub rewrite_password_file {
 5418:     my ($domain, $user, $contents) = @_;
 5419: 
 5420:     my $file = &password_filename($domain, $user);
 5421:     if (defined $file) {
 5422: 	my $pf = IO::File->new(">$file");
 5423: 	if($pf) {
 5424: 	    print $pf "$contents\n";
 5425: 	    return 1;
 5426: 	} else {
 5427: 	    return 0;
 5428: 	}
 5429:     } else {
 5430: 	return 0;
 5431:     }
 5432: 
 5433: }
 5434: 
 5435: #
 5436: #   get_auth_type - Determines the authorization type of a user in a domain.
 5437: 
 5438: #     Returns the authorization type or nouser if there is no such user.
 5439: #
 5440: sub get_auth_type 
 5441: {
 5442: 
 5443:     my ($domain, $user)  = @_;
 5444: 
 5445:     Debug("get_auth_type( $domain, $user ) \n");
 5446:     my $proname    = &propath($domain, $user); 
 5447:     my $passwdfile = "$proname/passwd";
 5448:     if( -e $passwdfile ) {
 5449: 	my $pf = IO::File->new($passwdfile);
 5450: 	my $realpassword = <$pf>;
 5451: 	chomp($realpassword);
 5452: 	Debug("Password info = $realpassword\n");
 5453: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 5454: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 5455: 	return "$authtype:$contentpwd";     
 5456:     } else {
 5457: 	Debug("Returning nouser");
 5458: 	return "nouser";
 5459:     }
 5460: }
 5461: 
 5462: #
 5463: #  Validate a user given their domain, name and password.  This utility
 5464: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 5465: #  to validate the login credentials of a user.
 5466: # Parameters:
 5467: #    $domain    - The domain being logged into (this is required due to
 5468: #                 the capability for multihomed systems.
 5469: #    $user      - The name of the user being validated.
 5470: #    $password  - The user's propoposed password.
 5471: #
 5472: # Returns:
 5473: #     1        - The domain,user,pasword triplet corresponds to a valid
 5474: #                user.
 5475: #     0        - The domain,user,password triplet is not a valid user.
 5476: #
 5477: sub validate_user {
 5478:     my ($domain, $user, $password) = @_;
 5479: 
 5480: 
 5481:     # Why negative ~pi you may well ask?  Well this function is about
 5482:     # authentication, and therefore very important to get right.
 5483:     # I've initialized the flag that determines whether or not I've 
 5484:     # validated correctly to a value it's not supposed to get.
 5485:     # At the end of this function. I'll ensure that it's not still that
 5486:     # value so we don't just wind up returning some accidental value
 5487:     # as a result of executing an unforseen code path that
 5488:     # did not set $validated.  At the end of valid execution paths,
 5489:     # validated shoule be 1 for success or 0 for failuer.
 5490: 
 5491:     my $validated = -3.14159;
 5492: 
 5493:     #  How we authenticate is determined by the type of authentication
 5494:     #  the user has been assigned.  If the authentication type is
 5495:     #  "nouser", the user does not exist so we will return 0.
 5496: 
 5497:     my $contents = &get_auth_type($domain, $user);
 5498:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 5499: 
 5500:     my $null = pack("C",0);	# Used by kerberos auth types.
 5501: 
 5502:     if ($howpwd ne 'nouser') {
 5503: 
 5504: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 5505: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
 5506: 	}
 5507: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 5508: 	    $contentpwd = (getpwnam($user))[1];
 5509: 	    if($contentpwd) {
 5510: 		if($contentpwd eq 'x') { # Shadow password file...
 5511: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 5512: 		    open PWAUTH,  "|$pwauth_path" or
 5513: 			die "Cannot invoke authentication";
 5514: 		    print PWAUTH "$user\n$password\n";
 5515: 		    close PWAUTH;
 5516: 		    $validated = ! $?;
 5517: 
 5518: 		} else { 	         # Passwords in /etc/passwd. 
 5519: 		    $validated = (crypt($password,
 5520: 					$contentpwd) eq $contentpwd);
 5521: 		}
 5522: 	    } else {
 5523: 		$validated = 0;
 5524: 	    }
 5525: 	}
 5526: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 5527: 	    if(! ($password =~ /$null/) ) {
 5528: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 5529: 							   "",
 5530: 							   $contentpwd,,
 5531: 							   'krbtgt',
 5532: 							   $contentpwd,
 5533: 							   1,
 5534: 							   $password);
 5535: 		if(!$k4error) {
 5536: 		    $validated = 1;
 5537: 		} else {
 5538: 		    $validated = 0;
 5539: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
 5540: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 5541: 		}
 5542: 	    } else {
 5543: 		$validated = 0; # Password has a match with null.
 5544: 	    }
 5545: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 5546: 	    if(!($password =~ /$null/)) { # Null password not allowed.
 5547: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
 5548: 							  .$contentpwd);
 5549: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 5550: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 5551: 		my $credentials= &Authen::Krb5::cc_default();
 5552: 		$credentials->initialize($krbclient);
 5553: 		my $krbreturn  = &Authen::Krb5::get_in_tkt_with_password($krbclient,
 5554: 									 $krbserver,
 5555: 									 $password,
 5556: 									 $credentials);
 5557: 		$validated = ($krbreturn == 1);
 5558: 	    } else {
 5559: 		$validated = 0;
 5560: 	    }
 5561: 	} elsif ($howpwd eq "localauth") { 
 5562: 	    #  Authenticate via installation specific authentcation method:
 5563: 	    $validated = &localauth::localauth($user, 
 5564: 					       $password, 
 5565: 					       $contentpwd);
 5566: 	} else {			# Unrecognized auth is also bad.
 5567: 	    $validated = 0;
 5568: 	}
 5569:     } else {
 5570: 	$validated = 0;
 5571:     }
 5572:     #
 5573:     #  $validated has the correct stat of the authentication:
 5574:     #
 5575: 
 5576:     unless ($validated != -3.14159) {
 5577: 	#  I >really really< want to know if this happens.
 5578: 	#  since it indicates that user authentication is badly
 5579: 	#  broken in some code path.
 5580:         #
 5581: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
 5582:     }
 5583:     return $validated;
 5584: }
 5585: 
 5586: 
 5587: sub addline {
 5588:     my ($fname,$hostid,$ip,$newline)=@_;
 5589:     my $contents;
 5590:     my $found=0;
 5591:     my $expr='^'.$hostid.':'.$ip.':';
 5592:     $expr =~ s/\./\\\./g;
 5593:     my $sh;
 5594:     if ($sh=IO::File->new("$fname.subscription")) {
 5595: 	while (my $subline=<$sh>) {
 5596: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 5597: 	}
 5598: 	$sh->close();
 5599:     }
 5600:     $sh=IO::File->new(">$fname.subscription");
 5601:     if ($contents) { print $sh $contents; }
 5602:     if ($newline) { print $sh $newline; }
 5603:     $sh->close();
 5604:     return $found;
 5605: }
 5606: 
 5607: sub get_chat {
 5608:     my ($cdom,$cname,$udom,$uname)=@_;
 5609:     my %hash;
 5610:     my $proname=&propath($cdom,$cname);
 5611:     my @entries=();
 5612:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 5613: 	    &GDBM_READER(),0640)) {
 5614: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 5615: 	untie %hash;
 5616:     }
 5617:     my @participants=();
 5618:     my $cutoff=time-60;
 5619:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
 5620: 	    &GDBM_WRCREAT(),0640)) {
 5621:         $hash{$uname.':'.$udom}=time;
 5622:         foreach (sort keys %hash) {
 5623: 	    if ($hash{$_}>$cutoff) {
 5624: 		$participants[$#participants+1]='active_participant:'.$_;
 5625:             }
 5626:         }
 5627:         untie %hash;
 5628:     }
 5629:     return (@participants,@entries);
 5630: }
 5631: 
 5632: sub chat_add {
 5633:     my ($cdom,$cname,$newchat)=@_;
 5634:     my %hash;
 5635:     my $proname=&propath($cdom,$cname);
 5636:     my @entries=();
 5637:     my $time=time;
 5638:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 5639: 	    &GDBM_WRCREAT(),0640)) {
 5640: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 5641: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 5642: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 5643: 	my $newid=$time.'_000000';
 5644: 	if ($thentime==$time) {
 5645: 	    $idnum=~s/^0+//;
 5646: 	    $idnum++;
 5647: 	    $idnum=substr('000000'.$idnum,-6,6);
 5648: 	    $newid=$time.'_'.$idnum;
 5649: 	}
 5650: 	$hash{$newid}=$newchat;
 5651: 	my $expired=$time-3600;
 5652: 	foreach (keys %hash) {
 5653: 	    my ($thistime)=($_=~/(\d+)\_/);
 5654: 	    if ($thistime<$expired) {
 5655: 		delete $hash{$_};
 5656: 	    }
 5657: 	}
 5658: 	untie %hash;
 5659:     }
 5660:     {
 5661: 	my $hfh;
 5662: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
 5663: 	    print $hfh "$time:".&unescape($newchat)."\n";
 5664: 	}
 5665:     }
 5666: }
 5667: 
 5668: sub unsub {
 5669:     my ($fname,$clientip)=@_;
 5670:     my $result;
 5671:     my $unsubs = 0;		# Number of successful unsubscribes:
 5672: 
 5673: 
 5674:     # An old way subscriptions were handled was to have a 
 5675:     # subscription marker file:
 5676: 
 5677:     Debug("Attempting unlink of $fname.$clientname");
 5678:     if (unlink("$fname.$clientname")) {
 5679: 	$unsubs++;		# Successful unsub via marker file.
 5680:     } 
 5681: 
 5682:     # The more modern way to do it is to have a subscription list
 5683:     # file:
 5684: 
 5685:     if (-e "$fname.subscription") {
 5686: 	my $found=&addline($fname,$clientname,$clientip,'');
 5687: 	if ($found) { 
 5688: 	    $unsubs++;
 5689: 	}
 5690:     } 
 5691: 
 5692:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 5693:     #  resource we can return ok:
 5694: 
 5695:     if($unsubs) {
 5696: 	$result = "ok\n";
 5697:     } else {
 5698: 	$result = "not_subscribed\n";
 5699:     }
 5700: 
 5701:     return $result;
 5702: }
 5703: 
 5704: sub currentversion {
 5705:     my $fname=shift;
 5706:     my $version=-1;
 5707:     my $ulsdir='';
 5708:     if ($fname=~/^(.+)\/[^\/]+$/) {
 5709:        $ulsdir=$1;
 5710:     }
 5711:     my ($fnamere1,$fnamere2);
 5712:     # remove version if already specified
 5713:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 5714:     # get the bits that go before and after the version number
 5715:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 5716: 	$fnamere1=$1;
 5717: 	$fnamere2='.'.$2;
 5718:     }
 5719:     if (-e $fname) { $version=1; }
 5720:     if (-e $ulsdir) {
 5721: 	if(-d $ulsdir) {
 5722: 	    if (opendir(LSDIR,$ulsdir)) {
 5723: 		my $ulsfn;
 5724: 		while ($ulsfn=readdir(LSDIR)) {
 5725: # see if this is a regular file (ignore links produced earlier)
 5726: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 5727: 		    unless (-l $thisfile) {
 5728: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 5729: 			    if ($1>$version) { $version=$1; }
 5730: 			}
 5731: 		    }
 5732: 		}
 5733: 		closedir(LSDIR);
 5734: 		$version++;
 5735: 	    }
 5736: 	}
 5737:     }
 5738:     return $version;
 5739: }
 5740: 
 5741: sub thisversion {
 5742:     my $fname=shift;
 5743:     my $version=-1;
 5744:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 5745: 	$version=$1;
 5746:     }
 5747:     return $version;
 5748: }
 5749: 
 5750: sub subscribe {
 5751:     my ($userinput,$clientip)=@_;
 5752:     my $result;
 5753:     my ($cmd,$fname)=split(/:/,$userinput,2);
 5754:     my $ownership=&ishome($fname);
 5755:     if ($ownership eq 'owner') {
 5756: # explitly asking for the current version?
 5757:         unless (-e $fname) {
 5758:             my $currentversion=&currentversion($fname);
 5759: 	    if (&thisversion($fname)==$currentversion) {
 5760:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 5761: 		    my $root=$1;
 5762:                     my $extension=$2;
 5763:                     symlink($root.'.'.$extension,
 5764:                             $root.'.'.$currentversion.'.'.$extension);
 5765:                     unless ($extension=~/\.meta$/) {
 5766:                        symlink($root.'.'.$extension.'.meta',
 5767:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 5768: 		    }
 5769:                 }
 5770:             }
 5771:         }
 5772: 	if (-e $fname) {
 5773: 	    if (-d $fname) {
 5774: 		$result="directory\n";
 5775: 	    } else {
 5776: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 5777: 		my $now=time;
 5778: 		my $found=&addline($fname,$clientname,$clientip,
 5779: 				   "$clientname:$clientip:$now\n");
 5780: 		if ($found) { $result="$fname\n"; }
 5781: 		# if they were subscribed to only meta data, delete that
 5782:                 # subscription, when you subscribe to a file you also get
 5783:                 # the metadata
 5784: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 5785: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 5786: 		$fname="http://$thisserver/".$fname;
 5787: 		$result="$fname\n";
 5788: 	    }
 5789: 	} else {
 5790: 	    $result="not_found\n";
 5791: 	}
 5792:     } else {
 5793: 	$result="rejected\n";
 5794:     }
 5795:     return $result;
 5796: }
 5797: #  Change the passwd of a unix user.  The caller must have
 5798: #  first verified that the user is a loncapa user.
 5799: #
 5800: # Parameters:
 5801: #    user      - Unix user name to change.
 5802: #    pass      - New password for the user.
 5803: # Returns:
 5804: #    ok    - if success
 5805: #    other - Some meaningfule error message string.
 5806: # NOTE:
 5807: #    invokes a setuid script to change the passwd.
 5808: sub change_unix_password {
 5809:     my ($user, $pass) = @_;
 5810: 
 5811:     &Debug("change_unix_password");
 5812:     my $execdir=$perlvar{'lonDaemons'};
 5813:     &Debug("Opening lcpasswd pipeline");
 5814:     my $pf = IO::File->new("|$execdir/lcpasswd > "
 5815: 			   ."$perlvar{'lonDaemons'}"
 5816: 			   ."/logs/lcpasswd.log");
 5817:     print $pf "$user\n$pass\n$pass\n";
 5818:     close $pf;
 5819:     my $err = $?;
 5820:     return ($err < @passwderrors) ? $passwderrors[$err] : 
 5821: 	"pwchange_falure - unknown error";
 5822: 
 5823:     
 5824: }
 5825: 
 5826: 
 5827: sub make_passwd_file {
 5828:     my ($uname, $umode,$npass,$passfilename)=@_;
 5829:     my $result="ok\n";
 5830:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 5831: 	{
 5832: 	    my $pf = IO::File->new(">$passfilename");
 5833: 	    if ($pf) {
 5834: 		print $pf "$umode:$npass\n";
 5835: 	    } else {
 5836: 		$result = "pass_file_failed_error";
 5837: 	    }
 5838: 	}
 5839:     } elsif ($umode eq 'internal') {
 5840: 	my $salt=time;
 5841: 	$salt=substr($salt,6,2);
 5842: 	my $ncpass=crypt($npass,$salt);
 5843: 	{
 5844: 	    &Debug("Creating internal auth");
 5845: 	    my $pf = IO::File->new(">$passfilename");
 5846: 	    if($pf) {
 5847: 		print $pf "internal:$ncpass\n"; 
 5848: 	    } else {
 5849: 		$result = "pass_file_failed_error";
 5850: 	    }
 5851: 	}
 5852:     } elsif ($umode eq 'localauth') {
 5853: 	{
 5854: 	    my $pf = IO::File->new(">$passfilename");
 5855: 	    if($pf) {
 5856: 		print $pf "localauth:$npass\n";
 5857: 	    } else {
 5858: 		$result = "pass_file_failed_error";
 5859: 	    }
 5860: 	}
 5861:     } elsif ($umode eq 'unix') {
 5862: 	{
 5863: 	    #
 5864: 	    #  Don't allow the creation of privileged accounts!!! that would
 5865: 	    #  be real bad!!!
 5866: 	    #
 5867: 	    my $uid = getpwnam($uname);
 5868: 	    if((defined $uid) && ($uid == 0)) {
 5869: 		&logthis(">>>Attempted to create privilged account blocked");
 5870: 		return "no_priv_account_error\n";
 5871: 	    }
 5872: 
 5873: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
 5874: 
 5875: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
 5876: 	    {
 5877: 		&Debug("Executing external: ".$execpath);
 5878: 		&Debug("user  = ".$uname.", Password =". $npass);
 5879: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
 5880: 		print $se "$uname\n";
 5881: 		print $se "$npass\n";
 5882: 		print $se "$npass\n";
 5883: 		print $se "$lc_error_file\n"; # Status -> unique file.
 5884: 	    }
 5885: 	    if (-r $lc_error_file) {
 5886: 		&Debug("Opening error file: $lc_error_file");
 5887: 		my $error = IO::File->new("< $lc_error_file");
 5888: 		my $useraddok = <$error>;
 5889: 		$error->close;
 5890: 		unlink($lc_error_file);
 5891: 		
 5892: 		chomp $useraddok;
 5893: 	
 5894: 		if($useraddok > 0) {
 5895: 		    my $error_text = &lcuseraddstrerror($useraddok);
 5896: 		    &logthis("Failed lcuseradd: $error_text");
 5897: 		    $result = "lcuseradd_failed:$error_text\n";
 5898: 		}  else {
 5899: 		    my $pf = IO::File->new(">$passfilename");
 5900: 		    if($pf) {
 5901: 			print $pf "unix:\n";
 5902: 		    } else {
 5903: 			$result = "pass_file_failed_error";
 5904: 		    }
 5905: 		}
 5906: 	    }  else {
 5907: 		&Debug("Could not locate lcuseradd error: $lc_error_file");
 5908: 		$result="bug_lcuseradd_no_output_file";
 5909: 	    }
 5910: 	}
 5911:     } elsif ($umode eq 'none') {
 5912: 	{
 5913: 	    my $pf = IO::File->new("> $passfilename");
 5914: 	    if($pf) {
 5915: 		print $pf "none:\n";
 5916: 	    } else {
 5917: 		$result = "pass_file_failed_error";
 5918: 	    }
 5919: 	}
 5920:     } else {
 5921: 	$result="auth_mode_error\n";
 5922:     }
 5923:     return $result;
 5924: }
 5925: 
 5926: sub convert_photo {
 5927:     my ($start,$dest)=@_;
 5928:     system("convert $start $dest");
 5929: }
 5930: 
 5931: sub sethost {
 5932:     my ($remotereq) = @_;
 5933:     my (undef,$hostid)=split(/:/,$remotereq);
 5934:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 5935:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
 5936: 	$currenthostid  =$hostid;
 5937: 	$currentdomainid=$hostdom{$hostid};
 5938: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 5939:     } else {
 5940: 	&logthis("Requested host id $hostid not an alias of ".
 5941: 		 $perlvar{'lonHostID'}." refusing connection");
 5942: 	return 'unable_to_set';
 5943:     }
 5944:     return 'ok';
 5945: }
 5946: 
 5947: sub version {
 5948:     my ($userinput)=@_;
 5949:     $remoteVERSION=(split(/:/,$userinput))[1];
 5950:     return "version:$VERSION";
 5951: }
 5952: 
 5953: #There is a copy of this in lonnet.pm
 5954: sub userload {
 5955:     my $numusers=0;
 5956:     {
 5957: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 5958: 	my $filename;
 5959: 	my $curtime=time;
 5960: 	while ($filename=readdir(LONIDS)) {
 5961: 	    if ($filename eq '.' || $filename eq '..') {next;}
 5962: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 5963: 	    if ($curtime-$mtime < 1800) { $numusers++; }
 5964: 	}
 5965: 	closedir(LONIDS);
 5966:     }
 5967:     my $userloadpercent=0;
 5968:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 5969:     if ($maxuserload) {
 5970: 	$userloadpercent=100*$numusers/$maxuserload;
 5971:     }
 5972:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 5973:     return $userloadpercent;
 5974: }
 5975: 
 5976: # Routines for serializing arrays and hashes (copies from lonnet)
 5977: 
 5978: sub array2str {
 5979:   my (@array) = @_;
 5980:   my $result=&arrayref2str(\@array);
 5981:   $result=~s/^__ARRAY_REF__//;
 5982:   $result=~s/__END_ARRAY_REF__$//;
 5983:   return $result;
 5984: }
 5985:                                                                                  
 5986: sub arrayref2str {
 5987:   my ($arrayref) = @_;
 5988:   my $result='__ARRAY_REF__';
 5989:   foreach my $elem (@$arrayref) {
 5990:     if(ref($elem) eq 'ARRAY') {
 5991:       $result.=&arrayref2str($elem).'&';
 5992:     } elsif(ref($elem) eq 'HASH') {
 5993:       $result.=&hashref2str($elem).'&';
 5994:     } elsif(ref($elem)) {
 5995:       #print("Got a ref of ".(ref($elem))." skipping.");
 5996:     } else {
 5997:       $result.=&escape($elem).'&';
 5998:     }
 5999:   }
 6000:   $result=~s/\&$//;
 6001:   $result .= '__END_ARRAY_REF__';
 6002:   return $result;
 6003: }
 6004:                                                                                  
 6005: sub hash2str {
 6006:   my (%hash) = @_;
 6007:   my $result=&hashref2str(\%hash);
 6008:   $result=~s/^__HASH_REF__//;
 6009:   $result=~s/__END_HASH_REF__$//;
 6010:   return $result;
 6011: }
 6012:                                                                                  
 6013: sub hashref2str {
 6014:   my ($hashref)=@_;
 6015:   my $result='__HASH_REF__';
 6016:   foreach (sort(keys(%$hashref))) {
 6017:     if (ref($_) eq 'ARRAY') {
 6018:       $result.=&arrayref2str($_).'=';
 6019:     } elsif (ref($_) eq 'HASH') {
 6020:       $result.=&hashref2str($_).'=';
 6021:     } elsif (ref($_)) {
 6022:       $result.='=';
 6023:       #print("Got a ref of ".(ref($_))." skipping.");
 6024:     } else {
 6025:         if ($_) {$result.=&escape($_).'=';} else { last; }
 6026:     }
 6027: 
 6028:     if(ref($hashref->{$_}) eq 'ARRAY') {
 6029:       $result.=&arrayref2str($hashref->{$_}).'&';
 6030:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 6031:       $result.=&hashref2str($hashref->{$_}).'&';
 6032:     } elsif(ref($hashref->{$_})) {
 6033:        $result.='&';
 6034:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 6035:     } else {
 6036:       $result.=&escape($hashref->{$_}).'&';
 6037:     }
 6038:   }
 6039:   $result=~s/\&$//;
 6040:   $result .= '__END_HASH_REF__';
 6041:   return $result;
 6042: }
 6043: 
 6044: # ----------------------------------- POD (plain old documentation, CPAN style)
 6045: 
 6046: =head1 NAME
 6047: 
 6048: lond - "LON Daemon" Server (port "LOND" 5663)
 6049: 
 6050: =head1 SYNOPSIS
 6051: 
 6052: Usage: B<lond>
 6053: 
 6054: Should only be run as user=www.  This is a command-line script which
 6055: is invoked by B<loncron>.  There is no expectation that a typical user
 6056: will manually start B<lond> from the command-line.  (In other words,
 6057: DO NOT START B<lond> YOURSELF.)
 6058: 
 6059: =head1 DESCRIPTION
 6060: 
 6061: There are two characteristics associated with the running of B<lond>,
 6062: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 6063: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 6064: subscriptions, etc).  These are described in two large
 6065: sections below.
 6066: 
 6067: B<PROCESS MANAGEMENT>
 6068: 
 6069: Preforker - server who forks first. Runs as a daemon. HUPs.
 6070: Uses IDEA encryption
 6071: 
 6072: B<lond> forks off children processes that correspond to the other servers
 6073: in the network.  Management of these processes can be done at the
 6074: parent process level or the child process level.
 6075: 
 6076: B<logs/lond.log> is the location of log messages.
 6077: 
 6078: The process management is now explained in terms of linux shell commands,
 6079: subroutines internal to this code, and signal assignments:
 6080: 
 6081: =over 4
 6082: 
 6083: =item *
 6084: 
 6085: PID is stored in B<logs/lond.pid>
 6086: 
 6087: This is the process id number of the parent B<lond> process.
 6088: 
 6089: =item *
 6090: 
 6091: SIGTERM and SIGINT
 6092: 
 6093: Parent signal assignment:
 6094:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 6095: 
 6096: Child signal assignment:
 6097:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 6098: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 6099:  to restart a new child.)
 6100: 
 6101: Command-line invocations:
 6102:  B<kill> B<-s> SIGTERM I<PID>
 6103:  B<kill> B<-s> SIGINT I<PID>
 6104: 
 6105: Subroutine B<HUNTSMAN>:
 6106:  This is only invoked for the B<lond> parent I<PID>.
 6107: This kills all the children, and then the parent.
 6108: The B<lonc.pid> file is cleared.
 6109: 
 6110: =item *
 6111: 
 6112: SIGHUP
 6113: 
 6114: Current bug:
 6115:  This signal can only be processed the first time
 6116: on the parent process.  Subsequent SIGHUP signals
 6117: have no effect.
 6118: 
 6119: Parent signal assignment:
 6120:  $SIG{HUP}  = \&HUPSMAN;
 6121: 
 6122: Child signal assignment:
 6123:  none (nothing happens)
 6124: 
 6125: Command-line invocations:
 6126:  B<kill> B<-s> SIGHUP I<PID>
 6127: 
 6128: Subroutine B<HUPSMAN>:
 6129:  This is only invoked for the B<lond> parent I<PID>,
 6130: This kills all the children, and then the parent.
 6131: The B<lond.pid> file is cleared.
 6132: 
 6133: =item *
 6134: 
 6135: SIGUSR1
 6136: 
 6137: Parent signal assignment:
 6138:  $SIG{USR1} = \&USRMAN;
 6139: 
 6140: Child signal assignment:
 6141:  $SIG{USR1}= \&logstatus;
 6142: 
 6143: Command-line invocations:
 6144:  B<kill> B<-s> SIGUSR1 I<PID>
 6145: 
 6146: Subroutine B<USRMAN>:
 6147:  When invoked for the B<lond> parent I<PID>,
 6148: SIGUSR1 is sent to all the children, and the status of
 6149: each connection is logged.
 6150: 
 6151: =item *
 6152: 
 6153: SIGUSR2
 6154: 
 6155: Parent Signal assignment:
 6156:     $SIG{USR2} = \&UpdateHosts
 6157: 
 6158: Child signal assignment:
 6159:     NONE
 6160: 
 6161: 
 6162: =item *
 6163: 
 6164: SIGCHLD
 6165: 
 6166: Parent signal assignment:
 6167:  $SIG{CHLD} = \&REAPER;
 6168: 
 6169: Child signal assignment:
 6170:  none
 6171: 
 6172: Command-line invocations:
 6173:  B<kill> B<-s> SIGCHLD I<PID>
 6174: 
 6175: Subroutine B<REAPER>:
 6176:  This is only invoked for the B<lond> parent I<PID>.
 6177: Information pertaining to the child is removed.
 6178: The socket port is cleaned up.
 6179: 
 6180: =back
 6181: 
 6182: B<SERVER-SIDE ACTIVITIES>
 6183: 
 6184: Server-side information can be accepted in an encrypted or non-encrypted
 6185: method.
 6186: 
 6187: =over 4
 6188: 
 6189: =item ping
 6190: 
 6191: Query a client in the hosts.tab table; "Are you there?"
 6192: 
 6193: =item pong
 6194: 
 6195: Respond to a ping query.
 6196: 
 6197: =item ekey
 6198: 
 6199: Read in encrypted key, make cipher.  Respond with a buildkey.
 6200: 
 6201: =item load
 6202: 
 6203: Respond with CPU load based on a computation upon /proc/loadavg.
 6204: 
 6205: =item currentauth
 6206: 
 6207: Reply with current authentication information (only over an
 6208: encrypted channel).
 6209: 
 6210: =item auth
 6211: 
 6212: Only over an encrypted channel, reply as to whether a user's
 6213: authentication information can be validated.
 6214: 
 6215: =item passwd
 6216: 
 6217: Allow for a password to be set.
 6218: 
 6219: =item makeuser
 6220: 
 6221: Make a user.
 6222: 
 6223: =item passwd
 6224: 
 6225: Allow for authentication mechanism and password to be changed.
 6226: 
 6227: =item home
 6228: 
 6229: Respond to a question "are you the home for a given user?"
 6230: 
 6231: =item update
 6232: 
 6233: Update contents of a subscribed resource.
 6234: 
 6235: =item unsubscribe
 6236: 
 6237: The server is unsubscribing from a resource.
 6238: 
 6239: =item subscribe
 6240: 
 6241: The server is subscribing to a resource.
 6242: 
 6243: =item log
 6244: 
 6245: Place in B<logs/lond.log>
 6246: 
 6247: =item put
 6248: 
 6249: stores hash in namespace
 6250: 
 6251: =item rolesputy
 6252: 
 6253: put a role into a user's environment
 6254: 
 6255: =item get
 6256: 
 6257: returns hash with keys from array
 6258: reference filled in from namespace
 6259: 
 6260: =item eget
 6261: 
 6262: returns hash with keys from array
 6263: reference filled in from namesp (encrypts the return communication)
 6264: 
 6265: =item rolesget
 6266: 
 6267: get a role from a user's environment
 6268: 
 6269: =item del
 6270: 
 6271: deletes keys out of array from namespace
 6272: 
 6273: =item keys
 6274: 
 6275: returns namespace keys
 6276: 
 6277: =item dump
 6278: 
 6279: dumps the complete (or key matching regexp) namespace into a hash
 6280: 
 6281: =item store
 6282: 
 6283: stores hash permanently
 6284: for this url; hashref needs to be given and should be a \%hashname; the
 6285: remaining args aren't required and if they aren't passed or are '' they will
 6286: be derived from the ENV
 6287: 
 6288: =item restore
 6289: 
 6290: returns a hash for a given url
 6291: 
 6292: =item querysend
 6293: 
 6294: Tells client about the lonsql process that has been launched in response
 6295: to a sent query.
 6296: 
 6297: =item queryreply
 6298: 
 6299: Accept information from lonsql and make appropriate storage in temporary
 6300: file space.
 6301: 
 6302: =item idput
 6303: 
 6304: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 6305: for each student, defined perhaps by the institutional Registrar.)
 6306: 
 6307: =item idget
 6308: 
 6309: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 6310: for each student, defined perhaps by the institutional Registrar.)
 6311: 
 6312: =item tmpput
 6313: 
 6314: Accept and store information in temporary space.
 6315: 
 6316: =item tmpget
 6317: 
 6318: Send along temporarily stored information.
 6319: 
 6320: =item ls
 6321: 
 6322: List part of a user's directory.
 6323: 
 6324: =item pushtable
 6325: 
 6326: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 6327: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 6328: must be restored manually in case of a problem with the new table file.
 6329: pushtable requires that the request be encrypted and validated via
 6330: ValidateManager.  The form of the command is:
 6331: enc:pushtable tablename <tablecontents> \n
 6332: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 6333: cleartext newline.
 6334: 
 6335: =item Hanging up (exit or init)
 6336: 
 6337: What to do when a client tells the server that they (the client)
 6338: are leaving the network.
 6339: 
 6340: =item unknown command
 6341: 
 6342: If B<lond> is sent an unknown command (not in the list above),
 6343: it replys to the client "unknown_cmd".
 6344: 
 6345: 
 6346: =item UNKNOWN CLIENT
 6347: 
 6348: If the anti-spoofing algorithm cannot verify the client,
 6349: the client is rejected (with a "refused" message sent
 6350: to the client, and the connection is closed.
 6351: 
 6352: =back
 6353: 
 6354: =head1 PREREQUISITES
 6355: 
 6356: IO::Socket
 6357: IO::File
 6358: Apache::File
 6359: Symbol
 6360: POSIX
 6361: Crypt::IDEA
 6362: LWP::UserAgent()
 6363: GDBM_File
 6364: Authen::Krb4
 6365: Authen::Krb5
 6366: 
 6367: =head1 COREQUISITES
 6368: 
 6369: =head1 OSNAMES
 6370: 
 6371: linux
 6372: 
 6373: =head1 SCRIPT CATEGORIES
 6374: 
 6375: Server/Process
 6376: 
 6377: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>