File:  [LON-CAPA] / loncom / lond
Revision 1.295: download - view: text, annotated - select for diffs
Wed Aug 31 22:38:57 2005 UTC (18 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Fix typo.

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

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