File:  [LON-CAPA] / loncom / lond
Revision 1.286: download - view: text, annotated - select for diffs
Fri Jun 24 18:00:55 2005 UTC (18 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: version_1_99_0, HEAD
i- krb5 no longer has this function in some versions of the libraries

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

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