File:  [LON-CAPA] / loncom / lond
Revision 1.305.2.6: download - view: text, annotated - select for diffs
Thu May 18 19:58:36 2006 UTC (18 years ago) by albertel
Branches: version_2_1_X
- backport 1.330

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

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