File:  [LON-CAPA] / loncom / lond
Revision 1.281: download - view: text, annotated - select for diffs
Sun Apr 3 19:33:34 2005 UTC (19 years ago) by matthew
Branches: MAIN
CVS tags: HEAD
Rewrote CopyFile to use File::Copy.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.281 2005/04/03 19:33:34 matthew 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.281 $'; #' 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: # 
 2364: #   Increment a profile entry in the user history file.
 2365: #   The history contains keyword value pairs.  In this case,
 2366: #   The value itself is a pair of numbers.  The first, the current value
 2367: #   the second an increment that this function applies to the current
 2368: #   value.
 2369: #
 2370: # Parameters:
 2371: #    $cmd      - The command that got us here.
 2372: #    $tail     - Tail of the command (remaining parameters).
 2373: #    $client   - File descriptor connected to client.
 2374: # Returns
 2375: #     0        - Requested to exit, caller should shut down.
 2376: #     1        - Continue processing.
 2377: #
 2378: sub increment_user_value_handler {
 2379:     my ($cmd, $tail, $client) = @_;
 2380:     
 2381:     my $userinput   = "$cmd:$tail";
 2382:     
 2383:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 2384:     if ($namespace ne 'roles') {
 2385:         chomp($what);
 2386: 	my $hashref = &tie_user_hash($udom, $uname,
 2387: 				     $namespace, &GDBM_WRCREAT(),
 2388: 				     "P",$what);
 2389: 	if ($hashref) {
 2390: 	    my @pairs=split(/\&/,$what);
 2391: 	    foreach my $pair (@pairs) {
 2392: 		my ($key,$value)=split(/=/,$pair);
 2393: 		# We could check that we have a number...
 2394: 		if (! defined($value) || $value eq '') {
 2395: 		    $value = 1;
 2396: 		}
 2397: 		$hashref->{$key}+=$value;
 2398: 	    }
 2399: 	    if (untie(%$hashref)) {
 2400: 		&Reply( $client, "ok\n", $userinput);
 2401: 	    } else {
 2402: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2403: 			 "while attempting inc\n", $userinput);
 2404: 	    }
 2405: 	} else {
 2406: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2407: 		     "while attempting inc\n", $userinput);
 2408: 	}
 2409:     } else {
 2410: 	&Failure($client, "refused\n", $userinput);
 2411:     }
 2412:     
 2413:     return 1;
 2414: }
 2415: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 2416: 
 2417: #
 2418: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 2419: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 2420: #   for a person grants the permissions packaged with that role
 2421: #   to that user when the role is selected.
 2422: #
 2423: # Parameters:
 2424: #    $cmd       - The command string (rolesput).
 2425: #    $tail      - The remainder of the request line.  For rolesput this
 2426: #                 consists of a colon separated list that contains:
 2427: #                 The domain and user that is granting the role (logged).
 2428: #                 The domain and user that is getting the role.
 2429: #                 The roles being granted as a set of & separated pairs.
 2430: #                 each pair a key value pair.
 2431: #    $client    - File descriptor connected to the client.
 2432: # Returns:
 2433: #     0         - If the daemon should exit
 2434: #     1         - To continue processing.
 2435: #
 2436: #
 2437: sub roles_put_handler {
 2438:     my ($cmd, $tail, $client) = @_;
 2439: 
 2440:     my $userinput  = "$cmd:$tail";
 2441: 
 2442:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 2443:     
 2444: 
 2445:     my $namespace='roles';
 2446:     chomp($what);
 2447:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2448: 				 &GDBM_WRCREAT(), "P",
 2449: 				 "$exedom:$exeuser:$what");
 2450:     #
 2451:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 2452:     #  handle is open for the minimal amount of time.  Since the flush
 2453:     #  is done on close this improves the chances the log will be an un-
 2454:     #  corrupted ordered thing.
 2455:     if ($hashref) {
 2456: 	my $pass_entry = &get_auth_type($udom, $uname);
 2457: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
 2458: 	$auth_type = $auth_type.":";
 2459: 	my @pairs=split(/\&/,$what);
 2460: 	foreach my $pair (@pairs) {
 2461: 	    my ($key,$value)=split(/=/,$pair);
 2462: 	    &manage_permissions($key, $udom, $uname,
 2463: 			       $auth_type);
 2464: 	    $hashref->{$key}=$value;
 2465: 	}
 2466: 	if (untie($hashref)) {
 2467: 	    &Reply($client, "ok\n", $userinput);
 2468: 	} else {
 2469: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2470: 		     "while attempting rolesput\n", $userinput);
 2471: 	}
 2472:     } else {
 2473: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2474: 		 "while attempting rolesput\n", $userinput);
 2475:     }
 2476:     return 1;
 2477: }
 2478: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 2479: 
 2480: #
 2481: #   Deletes (removes) a role for a user.   This is equivalent to removing
 2482: #  a permissions package associated with the role from the user's profile.
 2483: #
 2484: # Parameters:
 2485: #     $cmd                 - The command (rolesdel)
 2486: #     $tail                - The remainder of the request line. This consists
 2487: #                             of:
 2488: #                             The domain and user requesting the change (logged)
 2489: #                             The domain and user being changed.
 2490: #                             The roles being revoked.  These are shipped to us
 2491: #                             as a bunch of & separated role name keywords.
 2492: #     $client              - The file handle open on the client.
 2493: # Returns:
 2494: #     1                    - Continue processing
 2495: #     0                    - Exit.
 2496: #
 2497: sub roles_delete_handler {
 2498:     my ($cmd, $tail, $client)  = @_;
 2499: 
 2500:     my $userinput    = "$cmd:$tail";
 2501:    
 2502:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 2503:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 2504: 	   "what = ".$what);
 2505:     my $namespace='roles';
 2506:     chomp($what);
 2507:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2508: 				 &GDBM_WRCREAT(), "D",
 2509: 				 "$exedom:$exeuser:$what");
 2510:     
 2511:     if ($hashref) {
 2512: 	my @rolekeys=split(/\&/,$what);
 2513: 	
 2514: 	foreach my $key (@rolekeys) {
 2515: 	    delete $hashref->{$key};
 2516: 	}
 2517: 	if (untie(%$hashref)) {
 2518: 	    &Reply($client, "ok\n", $userinput);
 2519: 	} else {
 2520: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2521: 		     "while attempting rolesdel\n", $userinput);
 2522: 	}
 2523:     } else {
 2524:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2525: 		 "while attempting rolesdel\n", $userinput);
 2526:     }
 2527:     
 2528:     return 1;
 2529: }
 2530: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 2531: 
 2532: # Unencrypted get from a user's profile database.  See 
 2533: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 2534: # This function retrieves a keyed item from a specific named database in the
 2535: # user's directory.
 2536: #
 2537: # Parameters:
 2538: #   $cmd             - Command request keyword (get).
 2539: #   $tail            - Tail of the command.  This is a colon separated list
 2540: #                      consisting of the domain and username that uniquely
 2541: #                      identifies the profile,
 2542: #                      The 'namespace' which selects the gdbm file to 
 2543: #                      do the lookup in, 
 2544: #                      & separated list of keys to lookup.  Note that
 2545: #                      the values are returned as an & separated list too.
 2546: #   $client          - File descriptor open on the client.
 2547: # Returns:
 2548: #   1       - Continue processing.
 2549: #   0       - Exit.
 2550: #
 2551: sub get_profile_entry {
 2552:     my ($cmd, $tail, $client) = @_;
 2553: 
 2554:     my $userinput= "$cmd:$tail";
 2555:    
 2556:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 2557:     chomp($what);
 2558: 
 2559:     my $replystring = read_profile($udom, $uname, $namespace, $what);
 2560:     my ($first) = split(/:/,$replystring);
 2561:     if($first ne "error") {
 2562: 	&Reply($client, "$replystring\n", $userinput);
 2563:     } else {
 2564: 	&Failure($client, $replystring." while attempting get\n", $userinput);
 2565:     }
 2566:     return 1;
 2567: 
 2568: 
 2569: }
 2570: &register_handler("get", \&get_profile_entry, 0,1,0);
 2571: 
 2572: #
 2573: #  Process the encrypted get request.  Note that the request is sent
 2574: #  in clear, but the reply is encrypted.  This is a small covert channel:
 2575: #  information about the sensitive keys is given to the snooper.  Just not
 2576: #  information about the values of the sensitive key.  Hmm if I wanted to
 2577: #  know these I'd snoop for the egets. Get the profile item names from them
 2578: #  and then issue a get for them since there's no enforcement of the
 2579: #  requirement of an encrypted get for particular profile items.  If I
 2580: #  were re-doing this, I'd force the request to be encrypted as well as the
 2581: #  reply.  I'd also just enforce encrypted transactions for all gets since
 2582: #  that would prevent any covert channel snooping.
 2583: #
 2584: #  Parameters:
 2585: #     $cmd               - Command keyword of request (eget).
 2586: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
 2587: #     $client            - File open on the client.
 2588: #  Returns:
 2589: #     1      - Continue processing
 2590: #     0      - server should exit.
 2591: sub get_profile_entry_encrypted {
 2592:     my ($cmd, $tail, $client) = @_;
 2593: 
 2594:     my $userinput = "$cmd:$tail";
 2595:    
 2596:     my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
 2597:     chomp($what);
 2598:     my $qresult = read_profile($udom, $uname, $namespace, $what);
 2599:     my ($first) = split(/:/, $qresult);
 2600:     if($first ne "error") {
 2601: 	
 2602: 	if ($cipher) {
 2603: 	    my $cmdlength=length($qresult);
 2604: 	    $qresult.="         ";
 2605: 	    my $encqresult='';
 2606: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 2607: 		$encqresult.= unpack("H16", 
 2608: 				     $cipher->encrypt(substr($qresult,
 2609: 							     $encidx,
 2610: 							     8)));
 2611: 	    }
 2612: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 2613: 	} else {
 2614: 		&Failure( $client, "error:no_key\n", $userinput);
 2615: 	    }
 2616:     } else {
 2617: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
 2618: 
 2619:     }
 2620:     
 2621:     return 1;
 2622: }
 2623: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
 2624: 
 2625: #
 2626: #   Deletes a key in a user profile database.
 2627: #   
 2628: #   Parameters:
 2629: #       $cmd                  - Command keyword (del).
 2630: #       $tail                 - Command tail.  IN this case a colon
 2631: #                               separated list containing:
 2632: #                               The domain and user that identifies uniquely
 2633: #                               the identity of the user.
 2634: #                               The profile namespace (name of the profile
 2635: #                               database file).
 2636: #                               & separated list of keywords to delete.
 2637: #       $client              - File open on client socket.
 2638: # Returns:
 2639: #     1   - Continue processing
 2640: #     0   - Exit server.
 2641: #
 2642: #
 2643: sub delete_profile_entry {
 2644:     my ($cmd, $tail, $client) = @_;
 2645: 
 2646:     my $userinput = "cmd:$tail";
 2647: 
 2648:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 2649:     chomp($what);
 2650:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2651: 				 &GDBM_WRCREAT(),
 2652: 				 "D",$what);
 2653:     if ($hashref) {
 2654:         my @keys=split(/\&/,$what);
 2655: 	foreach my $key (@keys) {
 2656: 	    delete($hashref->{$key});
 2657: 	}
 2658: 	if (untie(%$hashref)) {
 2659: 	    &Reply($client, "ok\n", $userinput);
 2660: 	} else {
 2661: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2662: 		    "while attempting del\n", $userinput);
 2663: 	}
 2664:     } else {
 2665: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2666: 		 "while attempting del\n", $userinput);
 2667:     }
 2668:     return 1;
 2669: }
 2670: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 2671: 
 2672: #
 2673: #  List the set of keys that are defined in a profile database file.
 2674: #  A successful reply from this will contain an & separated list of
 2675: #  the keys. 
 2676: # Parameters:
 2677: #     $cmd              - Command request (keys).
 2678: #     $tail             - Remainder of the request, a colon separated
 2679: #                         list containing domain/user that identifies the
 2680: #                         user being queried, and the database namespace
 2681: #                         (database filename essentially).
 2682: #     $client           - File open on the client.
 2683: #  Returns:
 2684: #    1    - Continue processing.
 2685: #    0    - Exit the server.
 2686: #
 2687: sub get_profile_keys {
 2688:     my ($cmd, $tail, $client) = @_;
 2689: 
 2690:     my $userinput = "$cmd:$tail";
 2691: 
 2692:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 2693:     my $qresult='';
 2694:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2695: 				  &GDBM_READER());
 2696:     if ($hashref) {
 2697: 	foreach my $key (keys %$hashref) {
 2698: 	    $qresult.="$key&";
 2699: 	}
 2700: 	if (untie(%$hashref)) {
 2701: 	    $qresult=~s/\&$//;
 2702: 	    &Reply($client, "$qresult\n", $userinput);
 2703: 	} else {
 2704: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2705: 		    "while attempting keys\n", $userinput);
 2706: 	}
 2707:     } else {
 2708: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2709: 		 "while attempting keys\n", $userinput);
 2710:     }
 2711:    
 2712:     return 1;
 2713: }
 2714: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 2715: 
 2716: #
 2717: #   Dump the contents of a user profile database.
 2718: #   Note that this constitutes a very large covert channel too since
 2719: #   the dump will return sensitive information that is not encrypted.
 2720: #   The naive security assumption is that the session negotiation ensures
 2721: #   our client is trusted and I don't believe that's assured at present.
 2722: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 2723: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 2724: # 
 2725: #  Parameters:
 2726: #     $cmd           - The command request keyword (currentdump).
 2727: #     $tail          - Remainder of the request, consisting of a colon
 2728: #                      separated list that has the domain/username and
 2729: #                      the namespace to dump (database file).
 2730: #     $client        - file open on the remote client.
 2731: # Returns:
 2732: #     1    - Continue processing.
 2733: #     0    - Exit the server.
 2734: #
 2735: sub dump_profile_database {
 2736:     my ($cmd, $tail, $client) = @_;
 2737: 
 2738:     my $userinput = "$cmd:$tail";
 2739:    
 2740:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 2741:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2742: 				 &GDBM_READER());
 2743:     if ($hashref) {
 2744: 	# Structure of %data:
 2745: 	# $data{$symb}->{$parameter}=$value;
 2746: 	# $data{$symb}->{'v.'.$parameter}=$version;
 2747: 	# since $parameter will be unescaped, we do not
 2748:  	# have to worry about silly parameter names...
 2749: 	
 2750:         my $qresult='';
 2751: 	my %data = ();                     # A hash of anonymous hashes..
 2752: 	while (my ($key,$value) = each(%$hashref)) {
 2753: 	    my ($v,$symb,$param) = split(/:/,$key);
 2754: 	    next if ($v eq 'version' || $symb eq 'keys');
 2755: 	    next if (exists($data{$symb}) && 
 2756: 		     exists($data{$symb}->{$param}) &&
 2757: 		     $data{$symb}->{'v.'.$param} > $v);
 2758: 	    $data{$symb}->{$param}=$value;
 2759: 	    $data{$symb}->{'v.'.$param}=$v;
 2760: 	}
 2761: 	if (untie(%$hashref)) {
 2762: 	    while (my ($symb,$param_hash) = each(%data)) {
 2763: 		while(my ($param,$value) = each (%$param_hash)){
 2764: 		    next if ($param =~ /^v\./);       # Ignore versions...
 2765: 		    #
 2766: 		    #   Just dump the symb=value pairs separated by &
 2767: 		    #
 2768: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 2769: 		}
 2770: 	    }
 2771: 	    chop($qresult);
 2772: 	    &Reply($client , "$qresult\n", $userinput);
 2773: 	} else {
 2774: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2775: 		     "while attempting currentdump\n", $userinput);
 2776: 	}
 2777:     } else {
 2778: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2779: 		"while attempting currentdump\n", $userinput);
 2780:     }
 2781: 
 2782:     return 1;
 2783: }
 2784: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 2785: 
 2786: #
 2787: #   Dump a profile database with an optional regular expression
 2788: #   to match against the keys.  In this dump, no effort is made
 2789: #   to separate symb from version information. Presumably the
 2790: #   databases that are dumped by this command are of a different
 2791: #   structure.  Need to look at this and improve the documentation of
 2792: #   both this and the currentdump handler.
 2793: # Parameters:
 2794: #    $cmd                     - The command keyword.
 2795: #    $tail                    - All of the characters after the $cmd:
 2796: #                               These are expected to be a colon
 2797: #                               separated list containing:
 2798: #                               domain/user - identifying the user.
 2799: #                               namespace   - identifying the database.
 2800: #                               regexp      - optional regular expression
 2801: #                                             that is matched against
 2802: #                                             database keywords to do
 2803: #                                             selective dumps.
 2804: #   $client                   - Channel open on the client.
 2805: # Returns:
 2806: #    1    - Continue processing.
 2807: # Side effects:
 2808: #    response is written to $client.
 2809: #
 2810: sub dump_with_regexp {
 2811:     my ($cmd, $tail, $client) = @_;
 2812: 
 2813: 
 2814:     my $userinput = "$cmd:$tail";
 2815: 
 2816:     my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);
 2817:     if (defined($regexp)) {
 2818: 	$regexp=&unescape($regexp);
 2819:     } else {
 2820: 	$regexp='.';
 2821:     }
 2822:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2823: 				 &GDBM_READER());
 2824:     if ($hashref) {
 2825:         my $qresult='';
 2826: 	while (my ($key,$value) = each(%$hashref)) {
 2827: 	    if ($regexp eq '.') {
 2828: 		$qresult.=$key.'='.$value.'&';
 2829: 	    } else {
 2830: 		my $unescapeKey = &unescape($key);
 2831: 		if (eval('$unescapeKey=~/$regexp/')) {
 2832: 		    $qresult.="$key=$value&";
 2833: 		}
 2834: 	    }
 2835: 	}
 2836: 	if (untie(%$hashref)) {
 2837: 	    chop($qresult);
 2838: 	    &Reply($client, "$qresult\n", $userinput);
 2839: 	} else {
 2840: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2841: 		     "while attempting dump\n", $userinput);
 2842: 	}
 2843:     } else {
 2844: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2845: 		"while attempting dump\n", $userinput);
 2846:     }
 2847: 
 2848:     return 1;
 2849: }
 2850: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 2851: 
 2852: #  Store a set of key=value pairs associated with a versioned name.
 2853: #
 2854: #  Parameters:
 2855: #    $cmd                - Request command keyword.
 2856: #    $tail               - Tail of the request.  This is a colon
 2857: #                          separated list containing:
 2858: #                          domain/user - User and authentication domain.
 2859: #                          namespace   - Name of the database being modified
 2860: #                          rid         - Resource keyword to modify.
 2861: #                          what        - new value associated with rid.
 2862: #
 2863: #    $client             - Socket open on the client.
 2864: #
 2865: #
 2866: #  Returns:
 2867: #      1 (keep on processing).
 2868: #  Side-Effects:
 2869: #    Writes to the client
 2870: sub store_handler {
 2871:     my ($cmd, $tail, $client) = @_;
 2872:  
 2873:     my $userinput = "$cmd:$tail";
 2874: 
 2875:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
 2876:     if ($namespace ne 'roles') {
 2877: 
 2878: 	chomp($what);
 2879: 	my @pairs=split(/\&/,$what);
 2880: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 2881: 				       &GDBM_WRCREAT(), "S",
 2882: 				       "$rid:$what");
 2883: 	if ($hashref) {
 2884: 	    my $now = time;
 2885: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
 2886: 	    my $key;
 2887: 	    $hashref->{"version:$rid"}++;
 2888: 	    my $version=$hashref->{"version:$rid"};
 2889: 	    my $allkeys=''; 
 2890: 	    foreach my $pair (@pairs) {
 2891: 		my ($key,$value)=split(/=/,$pair);
 2892: 		$allkeys.=$key.':';
 2893: 		$hashref->{"$version:$rid:$key"}=$value;
 2894: 	    }
 2895: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 2896: 	    $allkeys.='timestamp';
 2897: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 2898: 	    if (untie($hashref)) {
 2899: 		&Reply($client, "ok\n", $userinput);
 2900: 	    } else {
 2901: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2902: 			"while attempting store\n", $userinput);
 2903: 	    }
 2904: 	} else {
 2905: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2906: 		     "while attempting store\n", $userinput);
 2907: 	}
 2908:     } else {
 2909: 	&Failure($client, "refused\n", $userinput);
 2910:     }
 2911: 
 2912:     return 1;
 2913: }
 2914: &register_handler("store", \&store_handler, 0, 1, 0);
 2915: 
 2916: #
 2917: #  Dump out all versions of a resource that has key=value pairs associated
 2918: # with it for each version.  These resources are built up via the store
 2919: # command.
 2920: #
 2921: #  Parameters:
 2922: #     $cmd               - Command keyword.
 2923: #     $tail              - Remainder of the request which consists of:
 2924: #                          domain/user   - User and auth. domain.
 2925: #                          namespace     - name of resource database.
 2926: #                          rid           - Resource id.
 2927: #    $client             - socket open on the client.
 2928: #
 2929: # Returns:
 2930: #      1  indicating the caller should not yet exit.
 2931: # Side-effects:
 2932: #   Writes a reply to the client.
 2933: #   The reply is a string of the following shape:
 2934: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 2935: #    Where the 1 above represents version 1.
 2936: #    this continues for all pairs of keys in all versions.
 2937: #
 2938: #
 2939: #    
 2940: #
 2941: sub restore_handler {
 2942:     my ($cmd, $tail, $client) = @_;
 2943: 
 2944:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 2945: 
 2946:     my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
 2947:     $namespace=~s/\//\_/g;
 2948:     $namespace=~s/\W//g;
 2949:     chomp($rid);
 2950:     my $proname=&propath($udom,$uname);
 2951:     my $qresult='';
 2952:     my %hash;
 2953:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
 2954: 	    &GDBM_READER(),0640)) {
 2955: 	my $version=$hash{"version:$rid"};
 2956: 	$qresult.="version=$version&";
 2957: 	my $scope;
 2958: 	for ($scope=1;$scope<=$version;$scope++) {
 2959: 	    my $vkeys=$hash{"$scope:keys:$rid"};
 2960: 	    my @keys=split(/:/,$vkeys);
 2961: 	    my $key;
 2962: 	    $qresult.="$scope:keys=$vkeys&";
 2963: 	    foreach $key (@keys) {
 2964: 		$qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 2965: 	    }                                  
 2966: 	}
 2967: 	if (untie(%hash)) {
 2968: 	    $qresult=~s/\&$//;
 2969: 	    &Reply( $client, "$qresult\n", $userinput);
 2970: 	} else {
 2971: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2972: 		    "while attempting restore\n", $userinput);
 2973: 	}
 2974:     } else {
 2975: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2976: 		"while attempting restore\n", $userinput);
 2977:     }
 2978:   
 2979:     return 1;
 2980: 
 2981: 
 2982: }
 2983: &register_handler("restore", \&restore_handler, 0,1,0);
 2984: 
 2985: #
 2986: #   Add a chat message to to a discussion board.
 2987: #
 2988: # Parameters:
 2989: #    $cmd                - Request keyword.
 2990: #    $tail               - Tail of the command. A colon separated list
 2991: #                          containing:
 2992: #                          cdom    - Domain on which the chat board lives
 2993: #                          cnum    - Identifier of the discussion group.
 2994: #                          post    - Body of the posting.
 2995: #   $client              - Socket open on the client.
 2996: # Returns:
 2997: #   1    - Indicating caller should keep on processing.
 2998: #
 2999: # Side-effects:
 3000: #   writes a reply to the client.
 3001: #
 3002: #
 3003: sub send_chat_handler {
 3004:     my ($cmd, $tail, $client) = @_;
 3005: 
 3006:     
 3007:     my $userinput = "$cmd:$tail";
 3008: 
 3009:     my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
 3010:     &chat_add($cdom,$cnum,$newpost);
 3011:     &Reply($client, "ok\n", $userinput);
 3012: 
 3013:     return 1;
 3014: }
 3015: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 3016: 
 3017: #
 3018: #   Retrieve the set of chat messagss from a discussion board.
 3019: #
 3020: #  Parameters:
 3021: #    $cmd             - Command keyword that initiated the request.
 3022: #    $tail            - Remainder of the request after the command
 3023: #                       keyword.  In this case a colon separated list of
 3024: #                       chat domain    - Which discussion board.
 3025: #                       chat id        - Discussion thread(?)
 3026: #                       domain/user    - Authentication domain and username
 3027: #                                        of the requesting person.
 3028: #   $client           - Socket open on the client program.
 3029: # Returns:
 3030: #    1     - continue processing
 3031: # Side effects:
 3032: #    Response is written to the client.
 3033: #
 3034: sub retrieve_chat_handler {
 3035:     my ($cmd, $tail, $client) = @_;
 3036: 
 3037: 
 3038:     my $userinput = "$cmd:$tail";
 3039: 
 3040:     my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
 3041:     my $reply='';
 3042:     foreach (&get_chat($cdom,$cnum,$udom,$uname)) {
 3043: 	$reply.=&escape($_).':';
 3044:     }
 3045:     $reply=~s/\:$//;
 3046:     &Reply($client, $reply."\n", $userinput);
 3047: 
 3048: 
 3049:     return 1;
 3050: }
 3051: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 3052: 
 3053: #
 3054: #  Initiate a query of an sql database.  SQL query repsonses get put in
 3055: #  a file for later retrieval.  This prevents sql query results from
 3056: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 3057: #  less of an issue since multiple outstanding requests can be concurrently
 3058: #  serviced.
 3059: #
 3060: #  Parameters:
 3061: #     $cmd       - COmmand keyword that initiated the request.
 3062: #     $tail      - Remainder of the command after the keyword.
 3063: #                  For this function, this consists of a query and
 3064: #                  3 arguments that are self-documentingly labelled
 3065: #                  in the original arg1, arg2, arg3.
 3066: #     $client    - Socket open on the client.
 3067: # Return:
 3068: #    1   - Indicating processing should continue.
 3069: # Side-effects:
 3070: #    a reply is written to $client.
 3071: #
 3072: sub send_query_handler {
 3073:     my ($cmd, $tail, $client) = @_;
 3074: 
 3075: 
 3076:     my $userinput = "$cmd:$tail";
 3077: 
 3078:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 3079:     $query=~s/\n*$//g;
 3080:     &Reply($client, "". &sql_reply("$clientname\&$query".
 3081: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 3082: 	  $userinput);
 3083:     
 3084:     return 1;
 3085: }
 3086: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 3087: 
 3088: #
 3089: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 3090: #   The query is submitted via a "querysend" transaction.
 3091: #   There it is passed on to the lonsql daemon, queued and issued to
 3092: #   mysql.
 3093: #     This transaction is invoked when the sql transaction is complete
 3094: #   it stores the query results in flie and indicates query completion.
 3095: #   presumably local software then fetches this response... I'm guessing
 3096: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 3097: #   lonsql on completion of the query interacts with the lond of our
 3098: #   client to do a query reply storing two files:
 3099: #    - id     - The results of the query.
 3100: #    - id.end - Indicating the transaction completed. 
 3101: #    NOTE: id is a unique id assigned to the query and querysend time.
 3102: # Parameters:
 3103: #    $cmd        - Command keyword that initiated this request.
 3104: #    $tail       - Remainder of the tail.  In this case that's a colon
 3105: #                  separated list containing the query Id and the 
 3106: #                  results of the query.
 3107: #    $client     - Socket open on the client.
 3108: # Return:
 3109: #    1           - Indicating that we should continue processing.
 3110: # Side effects:
 3111: #    ok written to the client.
 3112: #
 3113: sub reply_query_handler {
 3114:     my ($cmd, $tail, $client) = @_;
 3115: 
 3116: 
 3117:     my $userinput = "$cmd:$tail";
 3118: 
 3119:     my ($cmd,$id,$reply)=split(/:/,$userinput); 
 3120:     my $store;
 3121:     my $execdir=$perlvar{'lonDaemons'};
 3122:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 3123: 	$reply=~s/\&/\n/g;
 3124: 	print $store $reply;
 3125: 	close $store;
 3126: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 3127: 	print $store2 "done\n";
 3128: 	close $store2;
 3129: 	&Reply($client, "ok\n", $userinput);
 3130:     } else {
 3131: 	&Failure($client, "error: ".($!+0)
 3132: 		." IO::File->new Failed ".
 3133: 		"while attempting queryreply\n", $userinput);
 3134:     }
 3135:  
 3136: 
 3137:     return 1;
 3138: }
 3139: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 3140: 
 3141: #
 3142: #  Process the courseidput request.  Not quite sure what this means
 3143: #  at the system level sense.  It appears a gdbm file in the 
 3144: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 3145: #  a set of entries made in that database.
 3146: #
 3147: # Parameters:
 3148: #   $cmd      - The command keyword that initiated this request.
 3149: #   $tail     - Tail of the command.  In this case consists of a colon
 3150: #               separated list contaning the domain to apply this to and
 3151: #               an ampersand separated list of keyword=value pairs.
 3152: #               Each value is a colon separated list that includes:  
 3153: #               description, institutional code and course owner.
 3154: #               For backward compatibility with versions included
 3155: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
 3156: #               code and/or course owner are preserved from the existing 
 3157: #               record when writing a new record in response to 1.1 or 
 3158: #               1.2 implementations of lonnet::flushcourselogs().   
 3159: #                      
 3160: #   $client   - Socket open on the client.
 3161: # Returns:
 3162: #   1    - indicating that processing should continue
 3163: #
 3164: # Side effects:
 3165: #   reply is written to the client.
 3166: #
 3167: sub put_course_id_handler {
 3168:     my ($cmd, $tail, $client) = @_;
 3169: 
 3170: 
 3171:     my $userinput = "$cmd:$tail";
 3172: 
 3173:     my ($udom, $what) = split(/:/, $tail,2);
 3174:     chomp($what);
 3175:     my $now=time;
 3176:     my @pairs=split(/\&/,$what);
 3177: 
 3178:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3179:     if ($hashref) {
 3180: 	foreach my $pair (@pairs) {
 3181:             my ($key,$courseinfo) = split(/=/,$pair,2);
 3182:             $courseinfo =~ s/=/:/g;
 3183: 
 3184:             my @current_items = split(/:/,$hashref->{$key});
 3185:             shift(@current_items); # remove description
 3186:             pop(@current_items);   # remove last access
 3187:             my $numcurrent = scalar(@current_items);
 3188: 
 3189:             my @new_items = split(/:/,$courseinfo);
 3190:             my $numnew = scalar(@new_items);
 3191:             if ($numcurrent > 0) {
 3192:                 if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
 3193:                     $courseinfo .= ':'.join(':',@current_items);
 3194:                 } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
 3195:                     $courseinfo .= ':'.$current_items[$numcurrent-1];
 3196:                 }
 3197:             }
 3198: 	    $hashref->{$key}=$courseinfo.':'.$now;
 3199: 	}
 3200: 	if (untie(%$hashref)) {
 3201: 	    &Reply( $client, "ok\n", $userinput);
 3202: 	} else {
 3203: 	    &Failure($client, "error: ".($!+0)
 3204: 		     ." untie(GDBM) Failed ".
 3205: 		     "while attempting courseidput\n", $userinput);
 3206: 	}
 3207:     } else {
 3208: 	&Failure($client, "error: ".($!+0)
 3209: 		 ." tie(GDBM) Failed ".
 3210: 		 "while attempting courseidput\n", $userinput);
 3211:     }
 3212:     
 3213: 
 3214:     return 1;
 3215: }
 3216: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 3217: 
 3218: #  Retrieves the value of a course id resource keyword pattern
 3219: #  defined since a starting date.  Both the starting date and the
 3220: #  keyword pattern are optional.  If the starting date is not supplied it
 3221: #  is treated as the beginning of time.  If the pattern is not found,
 3222: #  it is treatred as "." matching everything.
 3223: #
 3224: #  Parameters:
 3225: #     $cmd     - Command keyword that resulted in us being dispatched.
 3226: #     $tail    - The remainder of the command that, in this case, consists
 3227: #                of a colon separated list of:
 3228: #                 domain   - The domain in which the course database is 
 3229: #                            defined.
 3230: #                 since    - Optional parameter describing the minimum
 3231: #                            time of definition(?) of the resources that
 3232: #                            will match the dump.
 3233: #                 description - regular expression that is used to filter
 3234: #                            the dump.  Only keywords matching this regexp
 3235: #                            will be used.
 3236: #                 institutional code - optional supplied code to filter 
 3237: #                            the dump. Only courses with an institutional code 
 3238: #                            that match the supplied code will be returned.
 3239: #                 owner    - optional supplied username of owner to filter
 3240: #                            the dump.  Only courses for which the course 
 3241: #                            owner matches the supplied username will be
 3242: #                            returned. Implicit assumption that owner
 3243: #                            is a user in the domain in which the
 3244: #                            course database is defined.
 3245: #     $client  - The socket open on the client.
 3246: # Returns:
 3247: #    1     - Continue processing.
 3248: # Side Effects:
 3249: #   a reply is written to $client.
 3250: sub dump_course_id_handler {
 3251:     my ($cmd, $tail, $client) = @_;
 3252: 
 3253:     my $userinput = "$cmd:$tail";
 3254: 
 3255:     my ($udom,$since,$description,$instcodefilter,$ownerfilter) =split(/:/,$tail);
 3256:     if (defined($description)) {
 3257: 	$description=&unescape($description);
 3258:     } else {
 3259: 	$description='.';
 3260:     }
 3261:     if (defined($instcodefilter)) {
 3262:         $instcodefilter=&unescape($instcodefilter);
 3263:     } else {
 3264:         $instcodefilter='.';
 3265:     }
 3266:     if (defined($ownerfilter)) {
 3267:         $ownerfilter=&unescape($ownerfilter);
 3268:     } else {
 3269:         $ownerfilter='.';
 3270:     }
 3271: 
 3272:     unless (defined($since)) { $since=0; }
 3273:     my $qresult='';
 3274:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3275:     if ($hashref) {
 3276: 	while (my ($key,$value) = each(%$hashref)) {
 3277: 	    my ($descr,$lasttime,$inst_code,$owner);
 3278:             my @courseitems = split(/:/,$value);
 3279:             $lasttime = pop(@courseitems);
 3280: 	    ($descr,$inst_code,$owner)=@courseitems;
 3281: 	    if ($lasttime<$since) { next; }
 3282:             my $match = 1;
 3283: 	    unless ($description eq '.') {
 3284: 		my $unescapeDescr = &unescape($descr);
 3285: 		unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
 3286:                     $match = 0;
 3287: 		}
 3288:             }
 3289:             unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
 3290:                 my $unescapeInstcode = &unescape($inst_code);
 3291:                 unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
 3292:                     $match = 0;
 3293:                 }
 3294: 	    }
 3295:             unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
 3296:                 my $unescapeOwner = &unescape($owner);
 3297:                 unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
 3298:                     $match = 0;
 3299:                 }
 3300:             }
 3301:             if ($match == 1) {
 3302:                 $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
 3303:             }
 3304: 	}
 3305: 	if (untie(%$hashref)) {
 3306: 	    chop($qresult);
 3307: 	    &Reply($client, "$qresult\n", $userinput);
 3308: 	} else {
 3309: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3310: 		    "while attempting courseiddump\n", $userinput);
 3311: 	}
 3312:     } else {
 3313: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3314: 		"while attempting courseiddump\n", $userinput);
 3315:     }
 3316: 
 3317: 
 3318:     return 1;
 3319: }
 3320: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 3321: 
 3322: #
 3323: #  Puts an id to a domains id database. 
 3324: #
 3325: #  Parameters:
 3326: #   $cmd     - The command that triggered us.
 3327: #   $tail    - Remainder of the request other than the command. This is a 
 3328: #              colon separated list containing:
 3329: #              $domain  - The domain for which we are writing the id.
 3330: #              $pairs  - The id info to write... this is and & separated list
 3331: #                        of keyword=value.
 3332: #   $client  - Socket open on the client.
 3333: #  Returns:
 3334: #    1   - Continue processing.
 3335: #  Side effects:
 3336: #     reply is written to $client.
 3337: #
 3338: sub put_id_handler {
 3339:     my ($cmd,$tail,$client) = @_;
 3340: 
 3341: 
 3342:     my $userinput = "$cmd:$tail";
 3343: 
 3344:     my ($udom,$what)=split(/:/,$tail);
 3345:     chomp($what);
 3346:     my @pairs=split(/\&/,$what);
 3347:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 3348: 				   "P", $what);
 3349:     if ($hashref) {
 3350: 	foreach my $pair (@pairs) {
 3351: 	    my ($key,$value)=split(/=/,$pair);
 3352: 	    $hashref->{$key}=$value;
 3353: 	}
 3354: 	if (untie(%$hashref)) {
 3355: 	    &Reply($client, "ok\n", $userinput);
 3356: 	} else {
 3357: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3358: 		     "while attempting idput\n", $userinput);
 3359: 	}
 3360:     } else {
 3361: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3362: 		  "while attempting idput\n", $userinput);
 3363:     }
 3364: 
 3365:     return 1;
 3366: }
 3367: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 3368: 
 3369: #
 3370: #  Retrieves a set of id values from the id database.
 3371: #  Returns an & separated list of results, one for each requested id to the
 3372: #  client.
 3373: #
 3374: # Parameters:
 3375: #   $cmd       - Command keyword that caused us to be dispatched.
 3376: #   $tail      - Tail of the command.  Consists of a colon separated:
 3377: #               domain - the domain whose id table we dump
 3378: #               ids      Consists of an & separated list of
 3379: #                        id keywords whose values will be fetched.
 3380: #                        nonexisting keywords will have an empty value.
 3381: #   $client    - Socket open on the client.
 3382: #
 3383: # Returns:
 3384: #    1 - indicating processing should continue.
 3385: # Side effects:
 3386: #   An & separated list of results is written to $client.
 3387: #
 3388: sub get_id_handler {
 3389:     my ($cmd, $tail, $client) = @_;
 3390: 
 3391:     
 3392:     my $userinput = "$client:$tail";
 3393:     
 3394:     my ($udom,$what)=split(/:/,$tail);
 3395:     chomp($what);
 3396:     my @queries=split(/\&/,$what);
 3397:     my $qresult='';
 3398:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 3399:     if ($hashref) {
 3400: 	for (my $i=0;$i<=$#queries;$i++) {
 3401: 	    $qresult.="$hashref->{$queries[$i]}&";
 3402: 	}
 3403: 	if (untie(%$hashref)) {
 3404: 	    $qresult=~s/\&$//;
 3405: 	    &Reply($client, "$qresult\n", $userinput);
 3406: 	} else {
 3407: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3408: 		      "while attempting idget\n",$userinput);
 3409: 	}
 3410:     } else {
 3411: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3412: 		 "while attempting idget\n",$userinput);
 3413:     }
 3414:     
 3415:     return 1;
 3416: }
 3417: &register_handler("idget", \&get_id_handler, 0, 1, 0);
 3418: 
 3419: #
 3420: #  Process the tmpput command I'm not sure what this does.. Seems to
 3421: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 3422: # where Id is the client's ip concatenated with a sequence number.
 3423: # The file will contain some value that is passed in.  Is this e.g.
 3424: # a login token?
 3425: #
 3426: # Parameters:
 3427: #    $cmd     - The command that got us dispatched.
 3428: #    $tail    - The remainder of the request following $cmd:
 3429: #               In this case this will be the contents of the file.
 3430: #    $client  - Socket connected to the client.
 3431: # Returns:
 3432: #    1 indicating processing can continue.
 3433: # Side effects:
 3434: #   A file is created in the local filesystem.
 3435: #   A reply is sent to the client.
 3436: sub tmp_put_handler {
 3437:     my ($cmd, $what, $client) = @_;
 3438: 
 3439:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 3440: 
 3441: 
 3442:     my $store;
 3443:     $tmpsnum++;
 3444:     my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 3445:     $id=~s/\W/\_/g;
 3446:     $what=~s/\n//g;
 3447:     my $execdir=$perlvar{'lonDaemons'};
 3448:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 3449: 	print $store $what;
 3450: 	close $store;
 3451: 	&Reply($client, "$id\n", $userinput);
 3452:     } else {
 3453: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 3454: 		  "while attempting tmpput\n", $userinput);
 3455:     }
 3456:     return 1;
 3457:   
 3458: }
 3459: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 3460: 
 3461: #   Processes the tmpget command.  This command returns the contents
 3462: #  of a temporary resource file(?) created via tmpput.
 3463: #
 3464: # Paramters:
 3465: #    $cmd      - Command that got us dispatched.
 3466: #    $id       - Tail of the command, contain the id of the resource
 3467: #                we want to fetch.
 3468: #    $client   - socket open on the client.
 3469: # Return:
 3470: #    1         - Inidcating processing can continue.
 3471: # Side effects:
 3472: #   A reply is sent to the client.
 3473: #
 3474: sub tmp_get_handler {
 3475:     my ($cmd, $id, $client) = @_;
 3476: 
 3477:     my $userinput = "$cmd:$id"; 
 3478:     
 3479: 
 3480:     $id=~s/\W/\_/g;
 3481:     my $store;
 3482:     my $execdir=$perlvar{'lonDaemons'};
 3483:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 3484: 	my $reply=<$store>;
 3485: 	&Reply( $client, "$reply\n", $userinput);
 3486: 	close $store;
 3487:     } else {
 3488: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 3489: 		  "while attempting tmpget\n", $userinput);
 3490:     }
 3491: 
 3492:     return 1;
 3493: }
 3494: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 3495: 
 3496: #
 3497: #  Process the tmpdel command.  This command deletes a temp resource
 3498: #  created by the tmpput command.
 3499: #
 3500: # Parameters:
 3501: #   $cmd      - Command that got us here.
 3502: #   $id       - Id of the temporary resource created.
 3503: #   $client   - socket open on the client process.
 3504: #
 3505: # Returns:
 3506: #   1     - Indicating processing should continue.
 3507: # Side Effects:
 3508: #   A file is deleted
 3509: #   A reply is sent to the client.
 3510: sub tmp_del_handler {
 3511:     my ($cmd, $id, $client) = @_;
 3512:     
 3513:     my $userinput= "$cmd:$id";
 3514:     
 3515:     chomp($id);
 3516:     $id=~s/\W/\_/g;
 3517:     my $execdir=$perlvar{'lonDaemons'};
 3518:     if (unlink("$execdir/tmp/$id.tmp")) {
 3519: 	&Reply($client, "ok\n", $userinput);
 3520:     } else {
 3521: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 3522: 		  "while attempting tmpdel\n", $userinput);
 3523:     }
 3524:     
 3525:     return 1;
 3526: 
 3527: }
 3528: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 3529: 
 3530: #
 3531: #   Processes the setannounce command.  This command
 3532: #   creates a file named announce.txt in the top directory of
 3533: #   the documentn root and sets its contents.  The announce.txt file is
 3534: #   printed in its entirety at the LonCAPA login page.  Note:
 3535: #   once the announcement.txt fileis created it cannot be deleted.
 3536: #   However, setting the contents of the file to empty removes the
 3537: #   announcement from the login page of loncapa so who cares.
 3538: #
 3539: # Parameters:
 3540: #    $cmd          - The command that got us dispatched.
 3541: #    $announcement - The text of the announcement.
 3542: #    $client       - Socket open on the client process.
 3543: # Retunrns:
 3544: #   1             - Indicating request processing should continue
 3545: # Side Effects:
 3546: #   The file {DocRoot}/announcement.txt is created.
 3547: #   A reply is sent to $client.
 3548: #
 3549: sub set_announce_handler {
 3550:     my ($cmd, $announcement, $client) = @_;
 3551:   
 3552:     my $userinput    = "$cmd:$announcement";
 3553: 
 3554:     chomp($announcement);
 3555:     $announcement=&unescape($announcement);
 3556:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 3557: 				'/announcement.txt')) {
 3558: 	print $store $announcement;
 3559: 	close $store;
 3560: 	&Reply($client, "ok\n", $userinput);
 3561:     } else {
 3562: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 3563:     }
 3564: 
 3565:     return 1;
 3566: }
 3567: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 3568: 
 3569: #
 3570: #  Return the version of the daemon.  This can be used to determine
 3571: #  the compatibility of cross version installations or, alternatively to
 3572: #  simply know who's out of date and who isn't.  Note that the version
 3573: #  is returned concatenated with the tail.
 3574: # Parameters:
 3575: #   $cmd        - the request that dispatched to us.
 3576: #   $tail       - Tail of the request (client's version?).
 3577: #   $client     - Socket open on the client.
 3578: #Returns:
 3579: #   1 - continue processing requests.
 3580: # Side Effects:
 3581: #   Replies with version to $client.
 3582: sub get_version_handler {
 3583:     my ($cmd, $tail, $client) = @_;
 3584: 
 3585:     my $userinput  = $cmd.$tail;
 3586:     
 3587:     &Reply($client, &version($userinput)."\n", $userinput);
 3588: 
 3589: 
 3590:     return 1;
 3591: }
 3592: &register_handler("version", \&get_version_handler, 0, 1, 0);
 3593: 
 3594: #  Set the current host and domain.  This is used to support
 3595: #  multihomed systems.  Each IP of the system, or even separate daemons
 3596: #  on the same IP can be treated as handling a separate lonCAPA virtual
 3597: #  machine.  This command selects the virtual lonCAPA.  The client always
 3598: #  knows the right one since it is lonc and it is selecting the domain/system
 3599: #  from the hosts.tab file.
 3600: # Parameters:
 3601: #    $cmd      - Command that dispatched us.
 3602: #    $tail     - Tail of the command (domain/host requested).
 3603: #    $socket   - Socket open on the client.
 3604: #
 3605: # Returns:
 3606: #     1   - Indicates the program should continue to process requests.
 3607: # Side-effects:
 3608: #     The default domain/system context is modified for this daemon.
 3609: #     a reply is sent to the client.
 3610: #
 3611: sub set_virtual_host_handler {
 3612:     my ($cmd, $tail, $socket) = @_;
 3613:   
 3614:     my $userinput  ="$cmd:$tail";
 3615: 
 3616:     &Reply($client, &sethost($userinput)."\n", $userinput);
 3617: 
 3618: 
 3619:     return 1;
 3620: }
 3621: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 3622: 
 3623: #  Process a request to exit:
 3624: #   - "bye" is sent to the client.
 3625: #   - The client socket is shutdown and closed.
 3626: #   - We indicate to the caller that we should exit.
 3627: # Formal Parameters:
 3628: #   $cmd                - The command that got us here.
 3629: #   $tail               - Tail of the command (empty).
 3630: #   $client             - Socket open on the tail.
 3631: # Returns:
 3632: #   0      - Indicating the program should exit!!
 3633: #
 3634: sub exit_handler {
 3635:     my ($cmd, $tail, $client) = @_;
 3636: 
 3637:     my $userinput = "$cmd:$tail";
 3638: 
 3639:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 3640:     &Reply($client, "bye\n", $userinput);
 3641:     $client->shutdown(2);        # shutdown the socket forcibly.
 3642:     $client->close();
 3643: 
 3644:     return 0;
 3645: }
 3646: &register_handler("exit", \&exit_handler, 0,1,1);
 3647: &register_handler("init", \&exit_handler, 0,1,1);
 3648: &register_handler("quit", \&exit_handler, 0,1,1);
 3649: 
 3650: #  Determine if auto-enrollment is enabled.
 3651: #  Note that the original had what I believe to be a defect.
 3652: #  The original returned 0 if the requestor was not a registerd client.
 3653: #  It should return "refused".
 3654: # Formal Parameters:
 3655: #   $cmd       - The command that invoked us.
 3656: #   $tail      - The tail of the command (Extra command parameters.
 3657: #   $client    - The socket open on the client that issued the request.
 3658: # Returns:
 3659: #    1         - Indicating processing should continue.
 3660: #
 3661: sub enrollment_enabled_handler {
 3662:     my ($cmd, $tail, $client) = @_;
 3663:     my $userinput = $cmd.":".$tail; # For logging purposes.
 3664: 
 3665:     
 3666:     my $cdom = split(/:/, $tail);   # Domain we're asking about.
 3667:     my $outcome  = &localenroll::run($cdom);
 3668:     &Reply($client, "$outcome\n", $userinput);
 3669: 
 3670:     return 1;
 3671: }
 3672: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 3673: 
 3674: #   Get the official sections for which auto-enrollment is possible.
 3675: #   Since the admin people won't know about 'unofficial sections' 
 3676: #   we cannot auto-enroll on them.
 3677: # Formal Parameters:
 3678: #    $cmd     - The command request that got us dispatched here.
 3679: #    $tail    - The remainder of the request.  In our case this
 3680: #               will be split into:
 3681: #               $coursecode   - The course name from the admin point of view.
 3682: #               $cdom         - The course's domain(?).
 3683: #    $client  - Socket open on the client.
 3684: # Returns:
 3685: #    1    - Indiciting processing should continue.
 3686: #
 3687: sub get_sections_handler {
 3688:     my ($cmd, $tail, $client) = @_;
 3689:     my $userinput = "$cmd:$tail";
 3690: 
 3691:     my ($coursecode, $cdom) = split(/:/, $tail);
 3692:     my @secs = &localenroll::get_sections($coursecode,$cdom);
 3693:     my $seclist = &escape(join(':',@secs));
 3694: 
 3695:     &Reply($client, "$seclist\n", $userinput);
 3696:     
 3697: 
 3698:     return 1;
 3699: }
 3700: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 3701: 
 3702: #   Validate the owner of a new course section.  
 3703: #
 3704: # Formal Parameters:
 3705: #   $cmd      - Command that got us dispatched.
 3706: #   $tail     - the remainder of the command.  For us this consists of a
 3707: #               colon separated string containing:
 3708: #                  $inst    - Course Id from the institutions point of view.
 3709: #                  $owner   - Proposed owner of the course.
 3710: #                  $cdom    - Domain of the course (from the institutions
 3711: #                             point of view?)..
 3712: #   $client   - Socket open on the client.
 3713: #
 3714: # Returns:
 3715: #   1        - Processing should continue.
 3716: #
 3717: sub validate_course_owner_handler {
 3718:     my ($cmd, $tail, $client)  = @_;
 3719:     my $userinput = "$cmd:$tail";
 3720:     my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
 3721: 
 3722:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
 3723:     &Reply($client, "$outcome\n", $userinput);
 3724: 
 3725: 
 3726: 
 3727:     return 1;
 3728: }
 3729: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 3730: 
 3731: #
 3732: #   Validate a course section in the official schedule of classes
 3733: #   from the institutions point of view (part of autoenrollment).
 3734: #
 3735: # Formal Parameters:
 3736: #   $cmd          - The command request that got us dispatched.
 3737: #   $tail         - The tail of the command.  In this case,
 3738: #                   this is a colon separated set of words that will be split
 3739: #                   into:
 3740: #                        $inst_course_id - The course/section id from the
 3741: #                                          institutions point of view.
 3742: #                        $cdom           - The domain from the institutions
 3743: #                                          point of view.
 3744: #   $client       - Socket open on the client.
 3745: # Returns:
 3746: #    1           - Indicating processing should continue.
 3747: #
 3748: sub validate_course_section_handler {
 3749:     my ($cmd, $tail, $client) = @_;
 3750:     my $userinput = "$cmd:$tail";
 3751:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 3752: 
 3753:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 3754:     &Reply($client, "$outcome\n", $userinput);
 3755: 
 3756: 
 3757:     return 1;
 3758: }
 3759: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 3760: 
 3761: #
 3762: #   Create a password for a new auto-enrollment user.
 3763: #   I think/guess, this password allows access to the institutions 
 3764: #   AIS class list server/services.  Stuart can correct this comment
 3765: #   when he finds out how wrong I am.
 3766: #
 3767: # Formal Parameters:
 3768: #    $cmd     - The command request that got us dispatched.
 3769: #    $tail    - The tail of the command.   In this case this is a colon separated
 3770: #               set of words that will be split into:
 3771: #               $authparam - An authentication parameter (username??).
 3772: #               $cdom      - The domain of the course from the institution's
 3773: #                            point of view.
 3774: #    $client  - The socket open on the client.
 3775: # Returns:
 3776: #    1 - continue processing.
 3777: #
 3778: sub create_auto_enroll_password_handler {
 3779:     my ($cmd, $tail, $client) = @_;
 3780:     my $userinput = "$cmd:$tail";
 3781: 
 3782:     my ($authparam, $cdom) = split(/:/, $userinput);
 3783: 
 3784:     my ($create_passwd,$authchk);
 3785:     ($authparam,
 3786:      $create_passwd,
 3787:      $authchk) = &localenroll::create_password($authparam,$cdom);
 3788: 
 3789:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 3790: 	   $userinput);
 3791: 
 3792: 
 3793:     return 1;
 3794: }
 3795: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 3796: 		  0, 1, 0);
 3797: 
 3798: #   Retrieve and remove temporary files created by/during autoenrollment.
 3799: #
 3800: # Formal Parameters:
 3801: #    $cmd      - The command that got us dispatched.
 3802: #    $tail     - The tail of the command.  In our case this is a colon 
 3803: #                separated list that will be split into:
 3804: #                $filename - The name of the file to remove.
 3805: #                            The filename is given as a path relative to
 3806: #                            the LonCAPA temp file directory.
 3807: #    $client   - Socket open on the client.
 3808: #
 3809: # Returns:
 3810: #   1     - Continue processing.
 3811: sub retrieve_auto_file_handler {
 3812:     my ($cmd, $tail, $client)    = @_;
 3813:     my $userinput                = "cmd:$tail";
 3814: 
 3815:     my ($filename)   = split(/:/, $tail);
 3816: 
 3817:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 3818:     if ( (-e $source) && ($filename ne '') ) {
 3819: 	my $reply = '';
 3820: 	if (open(my $fh,$source)) {
 3821: 	    while (<$fh>) {
 3822: 		chomp($_);
 3823: 		$_ =~ s/^\s+//g;
 3824: 		$_ =~ s/\s+$//g;
 3825: 		$reply .= $_;
 3826: 	    }
 3827: 	    close($fh);
 3828: 	    &Reply($client, &escape($reply)."\n", $userinput);
 3829: 
 3830: #   Does this have to be uncommented??!?  (RF).
 3831: #
 3832: #                                unlink($source);
 3833: 	} else {
 3834: 	    &Failure($client, "error\n", $userinput);
 3835: 	}
 3836:     } else {
 3837: 	&Failure($client, "error\n", $userinput);
 3838:     }
 3839:     
 3840: 
 3841:     return 1;
 3842: }
 3843: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 3844: 
 3845: #
 3846: #   Read and retrieve institutional code format (for support form).
 3847: # Formal Parameters:
 3848: #    $cmd        - Command that dispatched us.
 3849: #    $tail       - Tail of the command.  In this case it conatins 
 3850: #                  the course domain and the coursename.
 3851: #    $client     - Socket open on the client.
 3852: # Returns:
 3853: #    1     - Continue processing.
 3854: #
 3855: sub get_institutional_code_format_handler {
 3856:     my ($cmd, $tail, $client)   = @_;
 3857:     my $userinput               = "$cmd:$tail";
 3858: 
 3859:     my $reply;
 3860:     my($cdom,$course) = split(/:/,$tail);
 3861:     my @pairs = split/\&/,$course;
 3862:     my %instcodes = ();
 3863:     my %codes = ();
 3864:     my @codetitles = ();
 3865:     my %cat_titles = ();
 3866:     my %cat_order = ();
 3867:     foreach (@pairs) {
 3868: 	my ($key,$value) = split/=/,$_;
 3869: 	$instcodes{&unescape($key)} = &unescape($value);
 3870:     }
 3871:     my $formatreply = &localenroll::instcode_format($cdom,
 3872: 						    \%instcodes,
 3873: 						    \%codes,
 3874: 						    \@codetitles,
 3875: 						    \%cat_titles,
 3876: 						    \%cat_order);
 3877:     if ($formatreply eq 'ok') {
 3878: 	my $codes_str = &hash2str(%codes);
 3879: 	my $codetitles_str = &array2str(@codetitles);
 3880: 	my $cat_titles_str = &hash2str(%cat_titles);
 3881: 	my $cat_order_str = &hash2str(%cat_order);
 3882: 	&Reply($client,
 3883: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 3884: 	       .$cat_order_str."\n",
 3885: 	       $userinput);
 3886:     } else {
 3887: 	# this else branch added by RF since if not ok, lonc will
 3888: 	# hang waiting on reply until timeout.
 3889: 	#
 3890: 	&Reply($client, "format_error\n", $userinput);
 3891:     }
 3892:     
 3893:     return 1;
 3894: }
 3895: &register_handler("autoinstcodeformat",
 3896: 		  \&get_institutional_code_format_handler,0,1,0);
 3897: 
 3898: #
 3899: # Gets a student's photo to exist (in the correct image type) in the user's 
 3900: # directory.
 3901: # Formal Parameters:
 3902: #    $cmd     - The command request that got us dispatched.
 3903: #    $tail    - A colon separated set of words that will be split into:
 3904: #               $domain - student's domain
 3905: #               $uname  - student username
 3906: #               $type   - image type desired
 3907: #    $client  - The socket open on the client.
 3908: # Returns:
 3909: #    1 - continue processing.
 3910: sub student_photo_handler {
 3911:     my ($cmd, $tail, $client) = @_;
 3912:     my ($domain,$uname,$type) = split(/:/, $tail);
 3913: 
 3914:     my $path=&propath($domain,$uname).
 3915: 	'/userfiles/internal/studentphoto.'.$type;
 3916:     if (-e $path) {
 3917: 	&Reply($client,"ok\n","$cmd:$tail");
 3918: 	return 1;
 3919:     }
 3920:     &mkpath($path);
 3921:     my $file=&localstudentphoto::fetch($domain,$uname);
 3922:     if (!$file) {
 3923: 	&Failure($client,"unavailable\n","$cmd:$tail");
 3924: 	return 1;
 3925:     }
 3926:     if (!-e $path) { &convert_photo($file,$path); }
 3927:     if (-e $path) {
 3928: 	&Reply($client,"ok\n","$cmd:$tail");
 3929: 	return 1;
 3930:     }
 3931:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
 3932:     return 1;
 3933: }
 3934: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
 3935: 
 3936: # mkpath makes all directories for a file, expects an absolute path with a
 3937: # file or a trailing / if just a dir is passed
 3938: # returns 1 on success 0 on failure
 3939: sub mkpath {
 3940:     my ($file)=@_;
 3941:     my @parts=split(/\//,$file,-1);
 3942:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
 3943:     for (my $i=3;$i<= ($#parts-1);$i++) {
 3944: 	$now.='/'.$parts[$i]; 
 3945: 	if (!-e $now) {
 3946: 	    if  (!mkdir($now,0770)) { return 0; }
 3947: 	}
 3948:     }
 3949:     return 1;
 3950: }
 3951: 
 3952: #---------------------------------------------------------------
 3953: #
 3954: #   Getting, decoding and dispatching requests:
 3955: #
 3956: #
 3957: #   Get a Request:
 3958: #   Gets a Request message from the client.  The transaction
 3959: #   is defined as a 'line' of text.  We remove the new line
 3960: #   from the text line.  
 3961: #
 3962: sub get_request {
 3963:     my $input = <$client>;
 3964:     chomp($input);
 3965: 
 3966:     &Debug("get_request: Request = $input\n");
 3967: 
 3968:     &status('Processing '.$clientname.':'.$input);
 3969: 
 3970:     return $input;
 3971: }
 3972: #---------------------------------------------------------------
 3973: #
 3974: #  Process a request.  This sub should shrink as each action
 3975: #  gets farmed out into a separat sub that is registered 
 3976: #  with the dispatch hash.  
 3977: #
 3978: # Parameters:
 3979: #    user_input   - The request received from the client (lonc).
 3980: # Returns:
 3981: #    true to keep processing, false if caller should exit.
 3982: #
 3983: sub process_request {
 3984:     my ($userinput) = @_;      # Easier for now to break style than to
 3985:                                 # fix all the userinput -> user_input.
 3986:     my $wasenc    = 0;		# True if request was encrypted.
 3987: # ------------------------------------------------------------ See if encrypted
 3988:     if ($userinput =~ /^enc/) {
 3989: 	$userinput = decipher($userinput);
 3990: 	$wasenc=1;
 3991: 	if(!$userinput) {	# Cipher not defined.
 3992: 	    &Failure($client, "error: Encrypted data without negotated key\n");
 3993: 	    return 0;
 3994: 	}
 3995:     }
 3996:     Debug("process_request: $userinput\n");
 3997:     
 3998:     #  
 3999:     #   The 'correct way' to add a command to lond is now to
 4000:     #   write a sub to execute it and Add it to the command dispatch
 4001:     #   hash via a call to register_handler..  The comments to that
 4002:     #   sub should give you enough to go on to show how to do this
 4003:     #   along with the examples that are building up as this code
 4004:     #   is getting refactored.   Until all branches of the
 4005:     #   if/elseif monster below have been factored out into
 4006:     #   separate procesor subs, if the dispatch hash is missing
 4007:     #   the command keyword, we will fall through to the remainder
 4008:     #   of the if/else chain below in order to keep this thing in 
 4009:     #   working order throughout the transmogrification.
 4010: 
 4011:     my ($command, $tail) = split(/:/, $userinput, 2);
 4012:     chomp($command);
 4013:     chomp($tail);
 4014:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 4015:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 4016:     if(!$tail) {
 4017: 	$tail ="";		# defined but blank.
 4018:     }
 4019: 
 4020:     &Debug("Command received: $command, encoded = $wasenc");
 4021: 
 4022:     if(defined $Dispatcher{$command}) {
 4023: 
 4024: 	my $dispatch_info = $Dispatcher{$command};
 4025: 	my $handler       = $$dispatch_info[0];
 4026: 	my $need_encode   = $$dispatch_info[1];
 4027: 	my $client_types  = $$dispatch_info[2];
 4028: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 4029: 	      ."ClientType $client_types");
 4030:       
 4031: 	#  Validate the request:
 4032:       
 4033: 	my $ok = 1;
 4034: 	my $requesterprivs = 0;
 4035: 	if(&isClient()) {
 4036: 	    $requesterprivs |= $CLIENT_OK;
 4037: 	}
 4038: 	if(&isManager()) {
 4039: 	    $requesterprivs |= $MANAGER_OK;
 4040: 	}
 4041: 	if($need_encode && (!$wasenc)) {
 4042: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 4043: 	    $ok = 0;
 4044: 	}
 4045: 	if(($client_types & $requesterprivs) == 0) {
 4046: 	    Debug("Client not privileged to do this operation");
 4047: 	    $ok = 0;
 4048: 	}
 4049: 
 4050: 	if($ok) {
 4051: 	    Debug("Dispatching to handler $command $tail");
 4052: 	    my $keep_going = &$handler($command, $tail, $client);
 4053: 	    return $keep_going;
 4054: 	} else {
 4055: 	    Debug("Refusing to dispatch because client did not match requirements");
 4056: 	    Failure($client, "refused\n", $userinput);
 4057: 	    return 1;
 4058: 	}
 4059: 
 4060:     }    
 4061: 
 4062:     print $client "unknown_cmd\n";
 4063: # -------------------------------------------------------------------- complete
 4064:     Debug("process_request - returning 1");
 4065:     return 1;
 4066: }
 4067: #
 4068: #   Decipher encoded traffic
 4069: #  Parameters:
 4070: #     input      - Encoded data.
 4071: #  Returns:
 4072: #     Decoded data or undef if encryption key was not yet negotiated.
 4073: #  Implicit input:
 4074: #     cipher  - This global holds the negotiated encryption key.
 4075: #
 4076: sub decipher {
 4077:     my ($input)  = @_;
 4078:     my $output = '';
 4079:     
 4080:     
 4081:     if($cipher) {
 4082: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 4083: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 4084: 	    $output .= 
 4085: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 4086: 	}
 4087: 	return substr($output, 0, $enclength);
 4088:     } else {
 4089: 	return undef;
 4090:     }
 4091: }
 4092: 
 4093: #
 4094: #   Register a command processor.  This function is invoked to register a sub
 4095: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 4096: #   dispatch requests to an appropriate sub, and do the top level validity checking
 4097: #   as well:
 4098: #    - Is the keyword recognized.
 4099: #    - Is the proper client type attempting the request.
 4100: #    - Is the request encrypted if it has to be.
 4101: #   Parameters:
 4102: #    $request_name         - Name of the request being registered.
 4103: #                           This is the command request that will match
 4104: #                           against the hash keywords to lookup the information
 4105: #                           associated with the dispatch information.
 4106: #    $procedure           - Reference to a sub to call to process the request.
 4107: #                           All subs get called as follows:
 4108: #                             Procedure($cmd, $tail, $replyfd, $key)
 4109: #                             $cmd    - the actual keyword that invoked us.
 4110: #                             $tail   - the tail of the request that invoked us.
 4111: #                             $replyfd- File descriptor connected to the client
 4112: #    $must_encode          - True if the request must be encoded to be good.
 4113: #    $client_ok            - True if it's ok for a client to request this.
 4114: #    $manager_ok           - True if it's ok for a manager to request this.
 4115: # Side effects:
 4116: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 4117: #      - On failure, the program will die as it's a bad internal bug to try to 
 4118: #        register a duplicate command handler.
 4119: #
 4120: sub register_handler {
 4121:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 4122: 
 4123:     #  Don't allow duplication#
 4124:    
 4125:     if (defined $Dispatcher{$request_name}) {
 4126: 	die "Attempting to define a duplicate request handler for $request_name\n";
 4127:     }
 4128:     #   Build the client type mask:
 4129:     
 4130:     my $client_type_mask = 0;
 4131:     if($client_ok) {
 4132: 	$client_type_mask  |= $CLIENT_OK;
 4133:     }
 4134:     if($manager_ok) {
 4135: 	$client_type_mask  |= $MANAGER_OK;
 4136:     }
 4137:    
 4138:     #  Enter the hash:
 4139:       
 4140:     my @entry = ($procedure, $must_encode, $client_type_mask);
 4141:    
 4142:     $Dispatcher{$request_name} = \@entry;
 4143:    
 4144: }
 4145: 
 4146: 
 4147: #------------------------------------------------------------------
 4148: 
 4149: 
 4150: 
 4151: 
 4152: #
 4153: #  Convert an error return code from lcpasswd to a string value.
 4154: #
 4155: sub lcpasswdstrerror {
 4156:     my $ErrorCode = shift;
 4157:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 4158: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 4159:     } else {
 4160: 	return $passwderrors[$ErrorCode];
 4161:     }
 4162: }
 4163: 
 4164: #
 4165: # Convert an error return code from lcuseradd to a string value:
 4166: #
 4167: sub lcuseraddstrerror {
 4168:     my $ErrorCode = shift;
 4169:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
 4170: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
 4171:     } else {
 4172: 	return $adderrors[$ErrorCode];
 4173:     }
 4174: }
 4175: 
 4176: # grabs exception and records it to log before exiting
 4177: sub catchexception {
 4178:     my ($error)=@_;
 4179:     $SIG{'QUIT'}='DEFAULT';
 4180:     $SIG{__DIE__}='DEFAULT';
 4181:     &status("Catching exception");
 4182:     &logthis("<font color='red'>CRITICAL: "
 4183:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
 4184:      ."a crash with this error msg->[$error]</font>");
 4185:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 4186:     if ($client) { print $client "error: $error\n"; }
 4187:     $server->close();
 4188:     die($error);
 4189: }
 4190: sub timeout {
 4191:     &status("Handling Timeout");
 4192:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 4193:     &catchexception('Timeout');
 4194: }
 4195: # -------------------------------- Set signal handlers to record abnormal exits
 4196: 
 4197: 
 4198: $SIG{'QUIT'}=\&catchexception;
 4199: $SIG{__DIE__}=\&catchexception;
 4200: 
 4201: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 4202: &status("Read loncapa.conf and loncapa_apache.conf");
 4203: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 4204: %perlvar=%{$perlvarref};
 4205: undef $perlvarref;
 4206: 
 4207: # ----------------------------- Make sure this process is running from user=www
 4208: my $wwwid=getpwnam('www');
 4209: if ($wwwid!=$<) {
 4210:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 4211:    my $subj="LON: $currenthostid User ID mismatch";
 4212:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
 4213:  mailto $emailto -s '$subj' > /dev/null");
 4214:    exit 1;
 4215: }
 4216: 
 4217: # --------------------------------------------- Check if other instance running
 4218: 
 4219: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 4220: 
 4221: if (-e $pidfile) {
 4222:    my $lfh=IO::File->new("$pidfile");
 4223:    my $pide=<$lfh>;
 4224:    chomp($pide);
 4225:    if (kill 0 => $pide) { die "already running"; }
 4226: }
 4227: 
 4228: # ------------------------------------------------------------- Read hosts file
 4229: 
 4230: 
 4231: 
 4232: # establish SERVER socket, bind and listen.
 4233: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 4234:                                 Type      => SOCK_STREAM,
 4235:                                 Proto     => 'tcp',
 4236:                                 Reuse     => 1,
 4237:                                 Listen    => 10 )
 4238:   or die "making socket: $@\n";
 4239: 
 4240: # --------------------------------------------------------- Do global variables
 4241: 
 4242: # global variables
 4243: 
 4244: my %children               = ();       # keys are current child process IDs
 4245: 
 4246: sub REAPER {                        # takes care of dead children
 4247:     $SIG{CHLD} = \&REAPER;
 4248:     &status("Handling child death");
 4249:     my $pid;
 4250:     do {
 4251: 	$pid = waitpid(-1,&WNOHANG());
 4252: 	if (defined($children{$pid})) {
 4253: 	    &logthis("Child $pid died");
 4254: 	    delete($children{$pid});
 4255: 	} elsif ($pid > 0) {
 4256: 	    &logthis("Unknown Child $pid died");
 4257: 	}
 4258:     } while ( $pid > 0 );
 4259:     foreach my $child (keys(%children)) {
 4260: 	$pid = waitpid($child,&WNOHANG());
 4261: 	if ($pid > 0) {
 4262: 	    &logthis("Child $child - $pid looks like we missed it's death");
 4263: 	    delete($children{$pid});
 4264: 	}
 4265:     }
 4266:     &status("Finished Handling child death");
 4267: }
 4268: 
 4269: sub HUNTSMAN {                      # signal handler for SIGINT
 4270:     &status("Killing children (INT)");
 4271:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 4272:     kill 'INT' => keys %children;
 4273:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 4274:     my $execdir=$perlvar{'lonDaemons'};
 4275:     unlink("$execdir/logs/lond.pid");
 4276:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 4277:     &status("Done killing children");
 4278:     exit;                           # clean up with dignity
 4279: }
 4280: 
 4281: sub HUPSMAN {                      # signal handler for SIGHUP
 4282:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 4283:     &status("Killing children for restart (HUP)");
 4284:     kill 'INT' => keys %children;
 4285:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 4286:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 4287:     my $execdir=$perlvar{'lonDaemons'};
 4288:     unlink("$execdir/logs/lond.pid");
 4289:     &status("Restarting self (HUP)");
 4290:     exec("$execdir/lond");         # here we go again
 4291: }
 4292: 
 4293: #
 4294: #    Kill off hashes that describe the host table prior to re-reading it.
 4295: #    Hashes affected are:
 4296: #       %hostid, %hostdom %hostip %hostdns.
 4297: #
 4298: sub KillHostHashes {
 4299:     foreach my $key (keys %hostid) {
 4300: 	delete $hostid{$key};
 4301:     }
 4302:     foreach my $key (keys %hostdom) {
 4303: 	delete $hostdom{$key};
 4304:     }
 4305:     foreach my $key (keys %hostip) {
 4306: 	delete $hostip{$key};
 4307:     }
 4308:     foreach my $key (keys %hostdns) {
 4309: 	delete $hostdns{$key};
 4310:     }
 4311: }
 4312: #
 4313: #   Read in the host table from file and distribute it into the various hashes:
 4314: #
 4315: #    - %hostid  -  Indexed by IP, the loncapa hostname.
 4316: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
 4317: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
 4318: sub ReadHostTable {
 4319: 
 4320:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
 4321:     my $myloncapaname = $perlvar{'lonHostID'};
 4322:     Debug("My loncapa name is : $myloncapaname");
 4323:     while (my $configline=<CONFIG>) {
 4324: 	if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
 4325: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 4326: 	    $name=~s/\s//g;
 4327: 	    my $ip = gethostbyname($name);
 4328: 	    if (length($ip) ne 4) {
 4329: 		&logthis("Skipping host $id name $name no IP $ip found\n");
 4330: 		next;
 4331: 	    }
 4332: 	    $ip=inet_ntoa($ip);
 4333: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
 4334: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
 4335: 	    $hostip{$id}=$ip;         # IP address of host.
 4336: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
 4337: 
 4338: 	    if ($id eq $perlvar{'lonHostID'}) { 
 4339: 		Debug("Found me in the host table: $name");
 4340: 		$thisserver=$name; 
 4341: 	    }
 4342: 	}
 4343:     }
 4344:     close(CONFIG);
 4345: }
 4346: #
 4347: #  Reload the Apache daemon's state.
 4348: #  This is done by invoking /home/httpd/perl/apachereload
 4349: #  a setuid perl script that can be root for us to do this job.
 4350: #
 4351: sub ReloadApache {
 4352:     my $execdir = $perlvar{'lonDaemons'};
 4353:     my $script  = $execdir."/apachereload";
 4354:     system($script);
 4355: }
 4356: 
 4357: #
 4358: #   Called in response to a USR2 signal.
 4359: #   - Reread hosts.tab
 4360: #   - All children connected to hosts that were removed from hosts.tab
 4361: #     are killed via SIGINT
 4362: #   - All children connected to previously existing hosts are sent SIGUSR1
 4363: #   - Our internal hosts hash is updated to reflect the new contents of
 4364: #     hosts.tab causing connections from hosts added to hosts.tab to
 4365: #     now be honored.
 4366: #
 4367: sub UpdateHosts {
 4368:     &status("Reload hosts.tab");
 4369:     logthis('<font color="blue"> Updating connections </font>');
 4370:     #
 4371:     #  The %children hash has the set of IP's we currently have children
 4372:     #  on.  These need to be matched against records in the hosts.tab
 4373:     #  Any ip's no longer in the table get killed off they correspond to
 4374:     #  either dropped or changed hosts.  Note that the re-read of the table
 4375:     #  will take care of new and changed hosts as connections come into being.
 4376: 
 4377: 
 4378:     KillHostHashes;
 4379:     ReadHostTable;
 4380: 
 4381:     foreach my $child (keys %children) {
 4382: 	my $childip = $children{$child};
 4383: 	if(!$hostid{$childip}) {
 4384: 	    logthis('<font color="blue"> UpdateHosts killing child '
 4385: 		    ." $child for ip $childip </font>");
 4386: 	    kill('INT', $child);
 4387: 	} else {
 4388: 	    logthis('<font color="green"> keeping child for ip '
 4389: 		    ." $childip (pid=$child) </font>");
 4390: 	}
 4391:     }
 4392:     ReloadApache;
 4393:     &status("Finished reloading hosts.tab");
 4394: }
 4395: 
 4396: 
 4397: sub checkchildren {
 4398:     &status("Checking on the children (sending signals)");
 4399:     &initnewstatus();
 4400:     &logstatus();
 4401:     &logthis('Going to check on the children');
 4402:     my $docdir=$perlvar{'lonDocRoot'};
 4403:     foreach (sort keys %children) {
 4404: 	#sleep 1;
 4405:         unless (kill 'USR1' => $_) {
 4406: 	    &logthis ('Child '.$_.' is dead');
 4407:             &logstatus($$.' is dead');
 4408: 	    delete($children{$_});
 4409:         } 
 4410:     }
 4411:     sleep 5;
 4412:     $SIG{ALRM} = sub { Debug("timeout"); 
 4413: 		       die "timeout";  };
 4414:     $SIG{__DIE__} = 'DEFAULT';
 4415:     &status("Checking on the children (waiting for reports)");
 4416:     foreach (sort keys %children) {
 4417:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 4418:           eval {
 4419:             alarm(300);
 4420: 	    &logthis('Child '.$_.' did not respond');
 4421: 	    kill 9 => $_;
 4422: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 4423: 	    #$subj="LON: $currenthostid killed lond process $_";
 4424: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 4425: 	    #$execdir=$perlvar{'lonDaemons'};
 4426: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 4427: 	    delete($children{$_});
 4428: 	    alarm(0);
 4429: 	  }
 4430:         }
 4431:     }
 4432:     $SIG{ALRM} = 'DEFAULT';
 4433:     $SIG{__DIE__} = \&catchexception;
 4434:     &status("Finished checking children");
 4435:     &logthis('Finished Checking children');
 4436: }
 4437: 
 4438: # --------------------------------------------------------------------- Logging
 4439: 
 4440: sub logthis {
 4441:     my $message=shift;
 4442:     my $execdir=$perlvar{'lonDaemons'};
 4443:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 4444:     my $now=time;
 4445:     my $local=localtime($now);
 4446:     $lastlog=$local.': '.$message;
 4447:     print $fh "$local ($$): $message\n";
 4448: }
 4449: 
 4450: # ------------------------- Conditional log if $DEBUG true.
 4451: sub Debug {
 4452:     my $message = shift;
 4453:     if($DEBUG) {
 4454: 	&logthis($message);
 4455:     }
 4456: }
 4457: 
 4458: #
 4459: #   Sub to do replies to client.. this gives a hook for some
 4460: #   debug tracing too:
 4461: #  Parameters:
 4462: #     fd      - File open on client.
 4463: #     reply   - Text to send to client.
 4464: #     request - Original request from client.
 4465: #
 4466: sub Reply {
 4467:     my ($fd, $reply, $request) = @_;
 4468:     print $fd $reply;
 4469:     Debug("Request was $request  Reply was $reply");
 4470: 
 4471:     $Transactions++;
 4472: 
 4473: 
 4474: }
 4475: 
 4476: 
 4477: #
 4478: #    Sub to report a failure.
 4479: #    This function:
 4480: #     -   Increments the failure statistic counters.
 4481: #     -   Invokes Reply to send the error message to the client.
 4482: # Parameters:
 4483: #    fd       - File descriptor open on the client
 4484: #    reply    - Reply text to emit.
 4485: #    request  - The original request message (used by Reply
 4486: #               to debug if that's enabled.
 4487: # Implicit outputs:
 4488: #    $Failures- The number of failures is incremented.
 4489: #    Reply (invoked here) sends a message to the 
 4490: #    client:
 4491: #
 4492: sub Failure {
 4493:     my $fd      = shift;
 4494:     my $reply   = shift;
 4495:     my $request = shift;
 4496:    
 4497:     $Failures++;
 4498:     Reply($fd, $reply, $request);      # That's simple eh?
 4499: }
 4500: # ------------------------------------------------------------------ Log status
 4501: 
 4502: sub logstatus {
 4503:     &status("Doing logging");
 4504:     my $docdir=$perlvar{'lonDocRoot'};
 4505:     {
 4506: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 4507:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 4508:         $fh->close();
 4509:     }
 4510:     &status("Finished $$.txt");
 4511:     {
 4512: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 4513: 	flock(LOG,LOCK_EX);
 4514: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 4515: 	    .$status."\t".$lastlog."\t $keymode\n";
 4516: 	flock(LOG,LOCK_UN);
 4517: 	close(LOG);
 4518:     }
 4519:     &status("Finished logging");
 4520: }
 4521: 
 4522: sub initnewstatus {
 4523:     my $docdir=$perlvar{'lonDocRoot'};
 4524:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 4525:     my $now=time;
 4526:     my $local=localtime($now);
 4527:     print $fh "LOND status $local - parent $$\n\n";
 4528:     opendir(DIR,"$docdir/lon-status/londchld");
 4529:     while (my $filename=readdir(DIR)) {
 4530:         unlink("$docdir/lon-status/londchld/$filename");
 4531:     }
 4532:     closedir(DIR);
 4533: }
 4534: 
 4535: # -------------------------------------------------------------- Status setting
 4536: 
 4537: sub status {
 4538:     my $what=shift;
 4539:     my $now=time;
 4540:     my $local=localtime($now);
 4541:     $status=$local.': '.$what;
 4542:     $0='lond: '.$what.' '.$local;
 4543: }
 4544: 
 4545: # -------------------------------------------------------- Escape Special Chars
 4546: 
 4547: sub escape {
 4548:     my $str=shift;
 4549:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 4550:     return $str;
 4551: }
 4552: 
 4553: # ----------------------------------------------------- Un-Escape Special Chars
 4554: 
 4555: sub unescape {
 4556:     my $str=shift;
 4557:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 4558:     return $str;
 4559: }
 4560: 
 4561: # ----------------------------------------------------------- Send USR1 to lonc
 4562: 
 4563: sub reconlonc {
 4564:     my $peerfile=shift;
 4565:     &logthis("Trying to reconnect for $peerfile");
 4566:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
 4567:     if (my $fh=IO::File->new("$loncfile")) {
 4568: 	my $loncpid=<$fh>;
 4569:         chomp($loncpid);
 4570:         if (kill 0 => $loncpid) {
 4571: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
 4572:             kill USR1 => $loncpid;
 4573:         } else {
 4574: 	    &logthis(
 4575:               "<font color='red'>CRITICAL: "
 4576:              ."lonc at pid $loncpid not responding, giving up</font>");
 4577:         }
 4578:     } else {
 4579:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
 4580:     }
 4581: }
 4582: 
 4583: # -------------------------------------------------- Non-critical communication
 4584: 
 4585: sub subreply {
 4586:     my ($cmd,$server)=@_;
 4587:     my $peerfile="$perlvar{'lonSockDir'}/$server";
 4588:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 4589:                                       Type    => SOCK_STREAM,
 4590:                                       Timeout => 10)
 4591:        or return "con_lost";
 4592:     print $sclient "$cmd\n";
 4593:     my $answer=<$sclient>;
 4594:     chomp($answer);
 4595:     if (!$answer) { $answer="con_lost"; }
 4596:     return $answer;
 4597: }
 4598: 
 4599: sub reply {
 4600:   my ($cmd,$server)=@_;
 4601:   my $answer;
 4602:   if ($server ne $currenthostid) { 
 4603:     $answer=subreply($cmd,$server);
 4604:     if ($answer eq 'con_lost') {
 4605: 	$answer=subreply("ping",$server);
 4606:         if ($answer ne $server) {
 4607: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
 4608:            &reconlonc("$perlvar{'lonSockDir'}/$server");
 4609:         }
 4610:         $answer=subreply($cmd,$server);
 4611:     }
 4612:   } else {
 4613:     $answer='self_reply';
 4614:   } 
 4615:   return $answer;
 4616: }
 4617: 
 4618: # -------------------------------------------------------------- Talk to lonsql
 4619: 
 4620: sub sql_reply {
 4621:     my ($cmd)=@_;
 4622:     my $answer=&sub_sql_reply($cmd);
 4623:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 4624:     return $answer;
 4625: }
 4626: 
 4627: sub sub_sql_reply {
 4628:     my ($cmd)=@_;
 4629:     my $unixsock="mysqlsock";
 4630:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 4631:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 4632:                                       Type    => SOCK_STREAM,
 4633:                                       Timeout => 10)
 4634:        or return "con_lost";
 4635:     print $sclient "$cmd\n";
 4636:     my $answer=<$sclient>;
 4637:     chomp($answer);
 4638:     if (!$answer) { $answer="con_lost"; }
 4639:     return $answer;
 4640: }
 4641: 
 4642: # -------------------------------------------- Return path to profile directory
 4643: 
 4644: sub propath {
 4645:     my ($udom,$uname)=@_;
 4646:     $udom=~s/\W//g;
 4647:     $uname=~s/\W//g;
 4648:     my $subdir=$uname.'__';
 4649:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 4650:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
 4651:     return $proname;
 4652: } 
 4653: 
 4654: # --------------------------------------- Is this the home server of an author?
 4655: 
 4656: sub ishome {
 4657:     my $author=shift;
 4658:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 4659:     my ($udom,$uname)=split(/\//,$author);
 4660:     my $proname=propath($udom,$uname);
 4661:     if (-e $proname) {
 4662: 	return 'owner';
 4663:     } else {
 4664:         return 'not_owner';
 4665:     }
 4666: }
 4667: 
 4668: # ======================================================= Continue main program
 4669: # ---------------------------------------------------- Fork once and dissociate
 4670: 
 4671: my $fpid=fork;
 4672: exit if $fpid;
 4673: die "Couldn't fork: $!" unless defined ($fpid);
 4674: 
 4675: POSIX::setsid() or die "Can't start new session: $!";
 4676: 
 4677: # ------------------------------------------------------- Write our PID on disk
 4678: 
 4679: my $execdir=$perlvar{'lonDaemons'};
 4680: open (PIDSAVE,">$execdir/logs/lond.pid");
 4681: print PIDSAVE "$$\n";
 4682: close(PIDSAVE);
 4683: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 4684: &status('Starting');
 4685: 
 4686: 
 4687: 
 4688: # ----------------------------------------------------- Install signal handlers
 4689: 
 4690: 
 4691: $SIG{CHLD} = \&REAPER;
 4692: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 4693: $SIG{HUP}  = \&HUPSMAN;
 4694: $SIG{USR1} = \&checkchildren;
 4695: $SIG{USR2} = \&UpdateHosts;
 4696: 
 4697: #  Read the host hashes:
 4698: 
 4699: ReadHostTable;
 4700: 
 4701: # --------------------------------------------------------------
 4702: #   Accept connections.  When a connection comes in, it is validated
 4703: #   and if good, a child process is created to process transactions
 4704: #   along the connection.
 4705: 
 4706: while (1) {
 4707:     &status('Starting accept');
 4708:     $client = $server->accept() or next;
 4709:     &status('Accepted '.$client.' off to spawn');
 4710:     make_new_child($client);
 4711:     &status('Finished spawning');
 4712: }
 4713: 
 4714: sub make_new_child {
 4715:     my $pid;
 4716: #    my $cipher;     # Now global
 4717:     my $sigset;
 4718: 
 4719:     $client = shift;
 4720:     &status('Starting new child '.$client);
 4721:     &logthis('<font color="green"> Attempting to start child ('.$client.
 4722: 	     ")</font>");    
 4723:     # block signal for fork
 4724:     $sigset = POSIX::SigSet->new(SIGINT);
 4725:     sigprocmask(SIG_BLOCK, $sigset)
 4726:         or die "Can't block SIGINT for fork: $!\n";
 4727: 
 4728:     die "fork: $!" unless defined ($pid = fork);
 4729: 
 4730:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 4731: 	                               # connection liveness.
 4732: 
 4733:     #
 4734:     #  Figure out who we're talking to so we can record the peer in 
 4735:     #  the pid hash.
 4736:     #
 4737:     my $caller = getpeername($client);
 4738:     my ($port,$iaddr);
 4739:     if (defined($caller) && length($caller) > 0) {
 4740: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 4741:     } else {
 4742: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 4743:     }
 4744:     if (defined($iaddr)) {
 4745: 	$clientip  = inet_ntoa($iaddr);
 4746: 	Debug("Connected with $clientip");
 4747:     } else {
 4748: 	&logthis("Unable to determine clientip");
 4749: 	$clientip='Unavailable';
 4750:     }
 4751:     
 4752:     if ($pid) {
 4753:         # Parent records the child's birth and returns.
 4754:         sigprocmask(SIG_UNBLOCK, $sigset)
 4755:             or die "Can't unblock SIGINT for fork: $!\n";
 4756:         $children{$pid} = $clientip;
 4757:         &status('Started child '.$pid);
 4758:         return;
 4759:     } else {
 4760:         # Child can *not* return from this subroutine.
 4761:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 4762:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 4763:                                 #don't get intercepted
 4764:         $SIG{USR1}= \&logstatus;
 4765:         $SIG{ALRM}= \&timeout;
 4766:         $lastlog='Forked ';
 4767:         $status='Forked';
 4768: 
 4769:         # unblock signals
 4770:         sigprocmask(SIG_UNBLOCK, $sigset)
 4771:             or die "Can't unblock SIGINT for fork: $!\n";
 4772: 
 4773: #        my $tmpsnum=0;            # Now global
 4774: #---------------------------------------------------- kerberos 5 initialization
 4775:         &Authen::Krb5::init_context();
 4776:         &Authen::Krb5::init_ets();
 4777: 
 4778: 	&status('Accepted connection');
 4779: # =============================================================================
 4780:             # do something with the connection
 4781: # -----------------------------------------------------------------------------
 4782: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 4783: 
 4784: 	ReadManagerTable;	# May also be a manager!!
 4785: 	
 4786: 	my $outsideip=$clientip;
 4787: 	if ($clientip eq '127.0.0.1') {
 4788: 	    $outsideip=$hostip{$perlvar{'lonHostID'}};
 4789: 	}
 4790: 
 4791: 	my $clientrec=($hostid{$outsideip}     ne undef);
 4792: 	my $ismanager=($managers{$outsideip}    ne undef);
 4793: 	$clientname  = "[unknonwn]";
 4794: 	if($clientrec) {	# Establish client type.
 4795: 	    $ConnectionType = "client";
 4796: 	    $clientname = $hostid{$outsideip};
 4797: 	    if($ismanager) {
 4798: 		$ConnectionType = "both";
 4799: 	    }
 4800: 	} else {
 4801: 	    $ConnectionType = "manager";
 4802: 	    $clientname = $managers{$outsideip};
 4803: 	}
 4804: 	my $clientok;
 4805: 
 4806: 	if ($clientrec || $ismanager) {
 4807: 	    &status("Waiting for init from $clientip $clientname");
 4808: 	    &logthis('<font color="yellow">INFO: Connection, '.
 4809: 		     $clientip.
 4810: 		  " ($clientname) connection type = $ConnectionType </font>" );
 4811: 	    &status("Connecting $clientip  ($clientname))"); 
 4812: 	    my $remotereq=<$client>;
 4813: 	    chomp($remotereq);
 4814: 	    Debug("Got init: $remotereq");
 4815: 	    my $inikeyword = split(/:/, $remotereq);
 4816: 	    if ($remotereq =~ /^init/) {
 4817: 		&sethost("sethost:$perlvar{'lonHostID'}");
 4818: 		#
 4819: 		#  If the remote is attempting a local init... give that a try:
 4820: 		#
 4821: 		my ($i, $inittype) = split(/:/, $remotereq);
 4822: 
 4823: 		# If the connection type is ssl, but I didn't get my
 4824: 		# certificate files yet, then I'll drop  back to 
 4825: 		# insecure (if allowed).
 4826: 		
 4827: 		if($inittype eq "ssl") {
 4828: 		    my ($ca, $cert) = lonssl::CertificateFile;
 4829: 		    my $kfile       = lonssl::KeyFile;
 4830: 		    if((!$ca)   || 
 4831: 		       (!$cert) || 
 4832: 		       (!$kfile)) {
 4833: 			$inittype = ""; # This forces insecure attempt.
 4834: 			&logthis("<font color=\"blue\"> Certificates not "
 4835: 				 ."installed -- trying insecure auth</font>");
 4836: 		    } else {	# SSL certificates are in place so
 4837: 		    }		# Leave the inittype alone.
 4838: 		}
 4839: 
 4840: 		if($inittype eq "local") {
 4841: 		    my $key = LocalConnection($client, $remotereq);
 4842: 		    if($key) {
 4843: 			Debug("Got local key $key");
 4844: 			$clientok     = 1;
 4845: 			my $cipherkey = pack("H32", $key);
 4846: 			$cipher       = new IDEA($cipherkey);
 4847: 			print $client "ok:local\n";
 4848: 			&logthis('<font color="green"'
 4849: 				 . "Successful local authentication </font>");
 4850: 			$keymode = "local"
 4851: 		    } else {
 4852: 			Debug("Failed to get local key");
 4853: 			$clientok = 0;
 4854: 			shutdown($client, 3);
 4855: 			close $client;
 4856: 		    }
 4857: 		} elsif ($inittype eq "ssl") {
 4858: 		    my $key = SSLConnection($client);
 4859: 		    if ($key) {
 4860: 			$clientok = 1;
 4861: 			my $cipherkey = pack("H32", $key);
 4862: 			$cipher       = new IDEA($cipherkey);
 4863: 			&logthis('<font color="green">'
 4864: 				 ."Successfull ssl authentication with $clientname </font>");
 4865: 			$keymode = "ssl";
 4866: 	     
 4867: 		    } else {
 4868: 			$clientok = 0;
 4869: 			close $client;
 4870: 		    }
 4871: 	   
 4872: 		} else {
 4873: 		    my $ok = InsecureConnection($client);
 4874: 		    if($ok) {
 4875: 			$clientok = 1;
 4876: 			&logthis('<font color="green">'
 4877: 				 ."Successful insecure authentication with $clientname </font>");
 4878: 			print $client "ok\n";
 4879: 			$keymode = "insecure";
 4880: 		    } else {
 4881: 			&logthis('<font color="yellow">'
 4882: 				  ."Attempted insecure connection disallowed </font>");
 4883: 			close $client;
 4884: 			$clientok = 0;
 4885: 			
 4886: 		    }
 4887: 		}
 4888: 	    } else {
 4889: 		&logthis(
 4890: 			 "<font color='blue'>WARNING: "
 4891: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 4892: 		&status('No init '.$clientip);
 4893: 	    }
 4894: 	    
 4895: 	} else {
 4896: 	    &logthis(
 4897: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 4898: 	    &status('Hung up on '.$clientip);
 4899: 	}
 4900:  
 4901: 	if ($clientok) {
 4902: # ---------------- New known client connecting, could mean machine online again
 4903: 	    
 4904: 	    foreach my $id (keys(%hostip)) {
 4905: 		if ($hostip{$id} ne $clientip ||
 4906: 		    $hostip{$currenthostid} eq $clientip) {
 4907: 		    # no need to try to do recon's to myself
 4908: 		    next;
 4909: 		}
 4910: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
 4911: 	    }
 4912: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 4913: 	    &status('Will listen to '.$clientname);
 4914: # ------------------------------------------------------------ Process requests
 4915: 	    my $keep_going = 1;
 4916: 	    my $user_input;
 4917: 	    while(($user_input = get_request) && $keep_going) {
 4918: 		alarm(120);
 4919: 		Debug("Main: Got $user_input\n");
 4920: 		$keep_going = &process_request($user_input);
 4921: 		alarm(0);
 4922: 		&status('Listening to '.$clientname." ($keymode)");	   
 4923: 	    }
 4924: 
 4925: # --------------------------------------------- client unknown or fishy, refuse
 4926: 	}  else {
 4927: 	    print $client "refused\n";
 4928: 	    $client->close();
 4929: 	    &logthis("<font color='blue'>WARNING: "
 4930: 		     ."Rejected client $clientip, closing connection</font>");
 4931: 	}
 4932:     }            
 4933:     
 4934: # =============================================================================
 4935:     
 4936:     &logthis("<font color='red'>CRITICAL: "
 4937: 	     ."Disconnect from $clientip ($clientname)</font>");    
 4938:     
 4939:     
 4940:     # this exit is VERY important, otherwise the child will become
 4941:     # a producer of more and more children, forking yourself into
 4942:     # process death.
 4943:     exit;
 4944:     
 4945: }
 4946: #
 4947: #   Determine if a user is an author for the indicated domain.
 4948: #
 4949: # Parameters:
 4950: #    domain          - domain to check in .
 4951: #    user            - Name of user to check.
 4952: #
 4953: # Return:
 4954: #     1             - User is an author for domain.
 4955: #     0             - User is not an author for domain.
 4956: sub is_author {
 4957:     my ($domain, $user) = @_;
 4958: 
 4959:     &Debug("is_author: $user @ $domain");
 4960: 
 4961:     my $hashref = &tie_user_hash($domain, $user, "roles",
 4962: 				 &GDBM_READER());
 4963: 
 4964:     #  Author role should show up as a key /domain/_au
 4965: 
 4966:     my $key   = "/$domain/_au";
 4967:     my $value = $hashref->{$key};
 4968: 
 4969:     if(defined($value)) {
 4970: 	&Debug("$user @ $domain is an author");
 4971:     }
 4972: 
 4973:     return defined($value);
 4974: }
 4975: #
 4976: #   Checks to see if the input roleput request was to set
 4977: # an author role.  If so, invokes the lchtmldir script to set
 4978: # up a correct public_html 
 4979: # Parameters:
 4980: #    request   - The request sent to the rolesput subchunk.
 4981: #                We're looking for  /domain/_au
 4982: #    domain    - The domain in which the user is having roles doctored.
 4983: #    user      - Name of the user for which the role is being put.
 4984: #    authtype  - The authentication type associated with the user.
 4985: #
 4986: sub manage_permissions
 4987: {
 4988: 
 4989: 
 4990:     my ($request, $domain, $user, $authtype) = @_;
 4991: 
 4992:     &Debug("manage_permissions: $request $domain $user $authtype");
 4993: 
 4994:     # See if the request is of the form /$domain/_au
 4995:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
 4996: 	my $execdir = $perlvar{'lonDaemons'};
 4997: 	my $userhome= "/home/$user" ;
 4998: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
 4999: 	&Debug("Setting homedir permissions for $userhome");
 5000: 	system("$execdir/lchtmldir $userhome $user $authtype");
 5001:     }
 5002: }
 5003: 
 5004: 
 5005: #
 5006: #  Return the full path of a user password file, whether it exists or not.
 5007: # Parameters:
 5008: #   domain     - Domain in which the password file lives.
 5009: #   user       - name of the user.
 5010: # Returns:
 5011: #    Full passwd path:
 5012: #
 5013: sub password_path {
 5014:     my ($domain, $user) = @_;
 5015:     return &propath($domain, $user).'/passwd';
 5016: }
 5017: 
 5018: #   Password Filename
 5019: #   Returns the path to a passwd file given domain and user... only if
 5020: #  it exists.
 5021: # Parameters:
 5022: #   domain    - Domain in which to search.
 5023: #   user      - username.
 5024: # Returns:
 5025: #   - If the password file exists returns its path.
 5026: #   - If the password file does not exist, returns undefined.
 5027: #
 5028: sub password_filename {
 5029:     my ($domain, $user) = @_;
 5030: 
 5031:     Debug ("PasswordFilename called: dom = $domain user = $user");
 5032: 
 5033:     my $path  = &password_path($domain, $user);
 5034:     Debug("PasswordFilename got path: $path");
 5035:     if(-e $path) {
 5036: 	return $path;
 5037:     } else {
 5038: 	return undef;
 5039:     }
 5040: }
 5041: 
 5042: #
 5043: #   Rewrite the contents of the user's passwd file.
 5044: #  Parameters:
 5045: #    domain    - domain of the user.
 5046: #    name      - User's name.
 5047: #    contents  - New contents of the file.
 5048: # Returns:
 5049: #   0    - Failed.
 5050: #   1    - Success.
 5051: #
 5052: sub rewrite_password_file {
 5053:     my ($domain, $user, $contents) = @_;
 5054: 
 5055:     my $file = &password_filename($domain, $user);
 5056:     if (defined $file) {
 5057: 	my $pf = IO::File->new(">$file");
 5058: 	if($pf) {
 5059: 	    print $pf "$contents\n";
 5060: 	    return 1;
 5061: 	} else {
 5062: 	    return 0;
 5063: 	}
 5064:     } else {
 5065: 	return 0;
 5066:     }
 5067: 
 5068: }
 5069: 
 5070: #
 5071: #   get_auth_type - Determines the authorization type of a user in a domain.
 5072: 
 5073: #     Returns the authorization type or nouser if there is no such user.
 5074: #
 5075: sub get_auth_type 
 5076: {
 5077: 
 5078:     my ($domain, $user)  = @_;
 5079: 
 5080:     Debug("get_auth_type( $domain, $user ) \n");
 5081:     my $proname    = &propath($domain, $user); 
 5082:     my $passwdfile = "$proname/passwd";
 5083:     if( -e $passwdfile ) {
 5084: 	my $pf = IO::File->new($passwdfile);
 5085: 	my $realpassword = <$pf>;
 5086: 	chomp($realpassword);
 5087: 	Debug("Password info = $realpassword\n");
 5088: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 5089: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 5090: 	return "$authtype:$contentpwd";     
 5091:     } else {
 5092: 	Debug("Returning nouser");
 5093: 	return "nouser";
 5094:     }
 5095: }
 5096: 
 5097: #
 5098: #  Validate a user given their domain, name and password.  This utility
 5099: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 5100: #  to validate the login credentials of a user.
 5101: # Parameters:
 5102: #    $domain    - The domain being logged into (this is required due to
 5103: #                 the capability for multihomed systems.
 5104: #    $user      - The name of the user being validated.
 5105: #    $password  - The user's propoposed password.
 5106: #
 5107: # Returns:
 5108: #     1        - The domain,user,pasword triplet corresponds to a valid
 5109: #                user.
 5110: #     0        - The domain,user,password triplet is not a valid user.
 5111: #
 5112: sub validate_user {
 5113:     my ($domain, $user, $password) = @_;
 5114: 
 5115: 
 5116:     # Why negative ~pi you may well ask?  Well this function is about
 5117:     # authentication, and therefore very important to get right.
 5118:     # I've initialized the flag that determines whether or not I've 
 5119:     # validated correctly to a value it's not supposed to get.
 5120:     # At the end of this function. I'll ensure that it's not still that
 5121:     # value so we don't just wind up returning some accidental value
 5122:     # as a result of executing an unforseen code path that
 5123:     # did not set $validated.  At the end of valid execution paths,
 5124:     # validated shoule be 1 for success or 0 for failuer.
 5125: 
 5126:     my $validated = -3.14159;
 5127: 
 5128:     #  How we authenticate is determined by the type of authentication
 5129:     #  the user has been assigned.  If the authentication type is
 5130:     #  "nouser", the user does not exist so we will return 0.
 5131: 
 5132:     my $contents = &get_auth_type($domain, $user);
 5133:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 5134: 
 5135:     my $null = pack("C",0);	# Used by kerberos auth types.
 5136: 
 5137:     if ($howpwd ne 'nouser') {
 5138: 
 5139: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 5140: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
 5141: 	}
 5142: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 5143: 	    $contentpwd = (getpwnam($user))[1];
 5144: 	    if($contentpwd) {
 5145: 		if($contentpwd eq 'x') { # Shadow password file...
 5146: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 5147: 		    open PWAUTH,  "|$pwauth_path" or
 5148: 			die "Cannot invoke authentication";
 5149: 		    print PWAUTH "$user\n$password\n";
 5150: 		    close PWAUTH;
 5151: 		    $validated = ! $?;
 5152: 
 5153: 		} else { 	         # Passwords in /etc/passwd. 
 5154: 		    $validated = (crypt($password,
 5155: 					$contentpwd) eq $contentpwd);
 5156: 		}
 5157: 	    } else {
 5158: 		$validated = 0;
 5159: 	    }
 5160: 	}
 5161: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 5162: 	    if(! ($password =~ /$null/) ) {
 5163: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 5164: 							   "",
 5165: 							   $contentpwd,,
 5166: 							   'krbtgt',
 5167: 							   $contentpwd,
 5168: 							   1,
 5169: 							   $password);
 5170: 		if(!$k4error) {
 5171: 		    $validated = 1;
 5172: 		} else {
 5173: 		    $validated = 0;
 5174: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
 5175: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 5176: 		}
 5177: 	    } else {
 5178: 		$validated = 0; # Password has a match with null.
 5179: 	    }
 5180: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 5181: 	    if(!($password =~ /$null/)) { # Null password not allowed.
 5182: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
 5183: 							  .$contentpwd);
 5184: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 5185: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 5186: 		my $credentials= &Authen::Krb5::cc_default();
 5187: 		$credentials->initialize($krbclient);
 5188: 		my $krbreturn  = &Authen::Krb5::get_in_tkt_with_password($krbclient,
 5189: 									 $krbserver,
 5190: 									 $password,
 5191: 									 $credentials);
 5192: 		$validated = ($krbreturn == 1);
 5193: 	    } else {
 5194: 		$validated = 0;
 5195: 	    }
 5196: 	} elsif ($howpwd eq "localauth") { 
 5197: 	    #  Authenticate via installation specific authentcation method:
 5198: 	    $validated = &localauth::localauth($user, 
 5199: 					       $password, 
 5200: 					       $contentpwd);
 5201: 	} else {			# Unrecognized auth is also bad.
 5202: 	    $validated = 0;
 5203: 	}
 5204:     } else {
 5205: 	$validated = 0;
 5206:     }
 5207:     #
 5208:     #  $validated has the correct stat of the authentication:
 5209:     #
 5210: 
 5211:     unless ($validated != -3.14159) {
 5212: 	#  I >really really< want to know if this happens.
 5213: 	#  since it indicates that user authentication is badly
 5214: 	#  broken in some code path.
 5215:         #
 5216: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
 5217:     }
 5218:     return $validated;
 5219: }
 5220: 
 5221: 
 5222: sub addline {
 5223:     my ($fname,$hostid,$ip,$newline)=@_;
 5224:     my $contents;
 5225:     my $found=0;
 5226:     my $expr='^'.$hostid.':'.$ip.':';
 5227:     $expr =~ s/\./\\\./g;
 5228:     my $sh;
 5229:     if ($sh=IO::File->new("$fname.subscription")) {
 5230: 	while (my $subline=<$sh>) {
 5231: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 5232: 	}
 5233: 	$sh->close();
 5234:     }
 5235:     $sh=IO::File->new(">$fname.subscription");
 5236:     if ($contents) { print $sh $contents; }
 5237:     if ($newline) { print $sh $newline; }
 5238:     $sh->close();
 5239:     return $found;
 5240: }
 5241: 
 5242: sub get_chat {
 5243:     my ($cdom,$cname,$udom,$uname)=@_;
 5244:     my %hash;
 5245:     my $proname=&propath($cdom,$cname);
 5246:     my @entries=();
 5247:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 5248: 	    &GDBM_READER(),0640)) {
 5249: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 5250: 	untie %hash;
 5251:     }
 5252:     my @participants=();
 5253:     my $cutoff=time-60;
 5254:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
 5255: 	    &GDBM_WRCREAT(),0640)) {
 5256:         $hash{$uname.':'.$udom}=time;
 5257:         foreach (sort keys %hash) {
 5258: 	    if ($hash{$_}>$cutoff) {
 5259: 		$participants[$#participants+1]='active_participant:'.$_;
 5260:             }
 5261:         }
 5262:         untie %hash;
 5263:     }
 5264:     return (@participants,@entries);
 5265: }
 5266: 
 5267: sub chat_add {
 5268:     my ($cdom,$cname,$newchat)=@_;
 5269:     my %hash;
 5270:     my $proname=&propath($cdom,$cname);
 5271:     my @entries=();
 5272:     my $time=time;
 5273:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 5274: 	    &GDBM_WRCREAT(),0640)) {
 5275: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 5276: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 5277: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 5278: 	my $newid=$time.'_000000';
 5279: 	if ($thentime==$time) {
 5280: 	    $idnum=~s/^0+//;
 5281: 	    $idnum++;
 5282: 	    $idnum=substr('000000'.$idnum,-6,6);
 5283: 	    $newid=$time.'_'.$idnum;
 5284: 	}
 5285: 	$hash{$newid}=$newchat;
 5286: 	my $expired=$time-3600;
 5287: 	foreach (keys %hash) {
 5288: 	    my ($thistime)=($_=~/(\d+)\_/);
 5289: 	    if ($thistime<$expired) {
 5290: 		delete $hash{$_};
 5291: 	    }
 5292: 	}
 5293: 	untie %hash;
 5294:     }
 5295:     {
 5296: 	my $hfh;
 5297: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
 5298: 	    print $hfh "$time:".&unescape($newchat)."\n";
 5299: 	}
 5300:     }
 5301: }
 5302: 
 5303: sub unsub {
 5304:     my ($fname,$clientip)=@_;
 5305:     my $result;
 5306:     my $unsubs = 0;		# Number of successful unsubscribes:
 5307: 
 5308: 
 5309:     # An old way subscriptions were handled was to have a 
 5310:     # subscription marker file:
 5311: 
 5312:     Debug("Attempting unlink of $fname.$clientname");
 5313:     if (unlink("$fname.$clientname")) {
 5314: 	$unsubs++;		# Successful unsub via marker file.
 5315:     } 
 5316: 
 5317:     # The more modern way to do it is to have a subscription list
 5318:     # file:
 5319: 
 5320:     if (-e "$fname.subscription") {
 5321: 	my $found=&addline($fname,$clientname,$clientip,'');
 5322: 	if ($found) { 
 5323: 	    $unsubs++;
 5324: 	}
 5325:     } 
 5326: 
 5327:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 5328:     #  resource we can return ok:
 5329: 
 5330:     if($unsubs) {
 5331: 	$result = "ok\n";
 5332:     } else {
 5333: 	$result = "not_subscribed\n";
 5334:     }
 5335: 
 5336:     return $result;
 5337: }
 5338: 
 5339: sub currentversion {
 5340:     my $fname=shift;
 5341:     my $version=-1;
 5342:     my $ulsdir='';
 5343:     if ($fname=~/^(.+)\/[^\/]+$/) {
 5344:        $ulsdir=$1;
 5345:     }
 5346:     my ($fnamere1,$fnamere2);
 5347:     # remove version if already specified
 5348:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 5349:     # get the bits that go before and after the version number
 5350:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 5351: 	$fnamere1=$1;
 5352: 	$fnamere2='.'.$2;
 5353:     }
 5354:     if (-e $fname) { $version=1; }
 5355:     if (-e $ulsdir) {
 5356: 	if(-d $ulsdir) {
 5357: 	    if (opendir(LSDIR,$ulsdir)) {
 5358: 		my $ulsfn;
 5359: 		while ($ulsfn=readdir(LSDIR)) {
 5360: # see if this is a regular file (ignore links produced earlier)
 5361: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 5362: 		    unless (-l $thisfile) {
 5363: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 5364: 			    if ($1>$version) { $version=$1; }
 5365: 			}
 5366: 		    }
 5367: 		}
 5368: 		closedir(LSDIR);
 5369: 		$version++;
 5370: 	    }
 5371: 	}
 5372:     }
 5373:     return $version;
 5374: }
 5375: 
 5376: sub thisversion {
 5377:     my $fname=shift;
 5378:     my $version=-1;
 5379:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 5380: 	$version=$1;
 5381:     }
 5382:     return $version;
 5383: }
 5384: 
 5385: sub subscribe {
 5386:     my ($userinput,$clientip)=@_;
 5387:     my $result;
 5388:     my ($cmd,$fname)=split(/:/,$userinput);
 5389:     my $ownership=&ishome($fname);
 5390:     if ($ownership eq 'owner') {
 5391: # explitly asking for the current version?
 5392:         unless (-e $fname) {
 5393:             my $currentversion=&currentversion($fname);
 5394: 	    if (&thisversion($fname)==$currentversion) {
 5395:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 5396: 		    my $root=$1;
 5397:                     my $extension=$2;
 5398:                     symlink($root.'.'.$extension,
 5399:                             $root.'.'.$currentversion.'.'.$extension);
 5400:                     unless ($extension=~/\.meta$/) {
 5401:                        symlink($root.'.'.$extension.'.meta',
 5402:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 5403: 		    }
 5404:                 }
 5405:             }
 5406:         }
 5407: 	if (-e $fname) {
 5408: 	    if (-d $fname) {
 5409: 		$result="directory\n";
 5410: 	    } else {
 5411: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 5412: 		my $now=time;
 5413: 		my $found=&addline($fname,$clientname,$clientip,
 5414: 				   "$clientname:$clientip:$now\n");
 5415: 		if ($found) { $result="$fname\n"; }
 5416: 		# if they were subscribed to only meta data, delete that
 5417:                 # subscription, when you subscribe to a file you also get
 5418:                 # the metadata
 5419: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 5420: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 5421: 		$fname="http://$thisserver/".$fname;
 5422: 		$result="$fname\n";
 5423: 	    }
 5424: 	} else {
 5425: 	    $result="not_found\n";
 5426: 	}
 5427:     } else {
 5428: 	$result="rejected\n";
 5429:     }
 5430:     return $result;
 5431: }
 5432: 
 5433: sub make_passwd_file {
 5434:     my ($uname, $umode,$npass,$passfilename)=@_;
 5435:     my $result="ok\n";
 5436:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 5437: 	{
 5438: 	    my $pf = IO::File->new(">$passfilename");
 5439: 	    if ($pf) {
 5440: 		print $pf "$umode:$npass\n";
 5441: 	    } else {
 5442: 		$result = "pass_file_failed_error";
 5443: 	    }
 5444: 	}
 5445:     } elsif ($umode eq 'internal') {
 5446: 	my $salt=time;
 5447: 	$salt=substr($salt,6,2);
 5448: 	my $ncpass=crypt($npass,$salt);
 5449: 	{
 5450: 	    &Debug("Creating internal auth");
 5451: 	    my $pf = IO::File->new(">$passfilename");
 5452: 	    if($pf) {
 5453: 		print $pf "internal:$ncpass\n"; 
 5454: 	    } else {
 5455: 		$result = "pass_file_failed_error";
 5456: 	    }
 5457: 	}
 5458:     } elsif ($umode eq 'localauth') {
 5459: 	{
 5460: 	    my $pf = IO::File->new(">$passfilename");
 5461: 	    if($pf) {
 5462: 		print $pf "localauth:$npass\n";
 5463: 	    } else {
 5464: 		$result = "pass_file_failed_error";
 5465: 	    }
 5466: 	}
 5467:     } elsif ($umode eq 'unix') {
 5468: 	{
 5469: 	    #
 5470: 	    #  Don't allow the creation of privileged accounts!!! that would
 5471: 	    #  be real bad!!!
 5472: 	    #
 5473: 	    my $uid = getpwnam($uname);
 5474: 	    if((defined $uid) && ($uid == 0)) {
 5475: 		&logthis(">>>Attempted to create privilged account blocked");
 5476: 		return "no_priv_account_error\n";
 5477: 	    }
 5478: 
 5479: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
 5480: 
 5481: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
 5482: 	    {
 5483: 		&Debug("Executing external: ".$execpath);
 5484: 		&Debug("user  = ".$uname.", Password =". $npass);
 5485: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
 5486: 		print $se "$uname\n";
 5487: 		print $se "$npass\n";
 5488: 		print $se "$npass\n";
 5489: 		print $se "$lc_error_file\n"; # Status -> unique file.
 5490: 	    }
 5491: 	    my $error = IO::File->new("< $lc_error_file");
 5492: 	    my $useraddok = <$error>;
 5493: 	    $error->close;
 5494: 	    unlink($lc_error_file);
 5495: 
 5496: 	    chomp $useraddok;
 5497: 
 5498: 	    if($useraddok > 0) {
 5499: 		my $error_text = &lcuseraddstrerror($useraddok);
 5500: 		&logthis("Failed lcuseradd: $error_text");
 5501: 		$result = "lcuseradd_failed:$error_text\n";
 5502: 	    }  else {
 5503: 		my $pf = IO::File->new(">$passfilename");
 5504: 		if($pf) {
 5505: 		    print $pf "unix:\n";
 5506: 		} else {
 5507: 		    $result = "pass_file_failed_error";
 5508: 		}
 5509: 	    }
 5510: 	}
 5511:     } elsif ($umode eq 'none') {
 5512: 	{
 5513: 	    my $pf = IO::File->new("> $passfilename");
 5514: 	    if($pf) {
 5515: 		print $pf "none:\n";
 5516: 	    } else {
 5517: 		$result = "pass_file_failed_error";
 5518: 	    }
 5519: 	}
 5520:     } else {
 5521: 	$result="auth_mode_error\n";
 5522:     }
 5523:     return $result;
 5524: }
 5525: 
 5526: sub convert_photo {
 5527:     my ($start,$dest)=@_;
 5528:     system("convert $start $dest");
 5529: }
 5530: 
 5531: sub sethost {
 5532:     my ($remotereq) = @_;
 5533:     my (undef,$hostid)=split(/:/,$remotereq);
 5534:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 5535:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
 5536: 	$currenthostid  =$hostid;
 5537: 	$currentdomainid=$hostdom{$hostid};
 5538: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 5539:     } else {
 5540: 	&logthis("Requested host id $hostid not an alias of ".
 5541: 		 $perlvar{'lonHostID'}." refusing connection");
 5542: 	return 'unable_to_set';
 5543:     }
 5544:     return 'ok';
 5545: }
 5546: 
 5547: sub version {
 5548:     my ($userinput)=@_;
 5549:     $remoteVERSION=(split(/:/,$userinput))[1];
 5550:     return "version:$VERSION";
 5551: }
 5552: 
 5553: #There is a copy of this in lonnet.pm
 5554: sub userload {
 5555:     my $numusers=0;
 5556:     {
 5557: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 5558: 	my $filename;
 5559: 	my $curtime=time;
 5560: 	while ($filename=readdir(LONIDS)) {
 5561: 	    if ($filename eq '.' || $filename eq '..') {next;}
 5562: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 5563: 	    if ($curtime-$mtime < 1800) { $numusers++; }
 5564: 	}
 5565: 	closedir(LONIDS);
 5566:     }
 5567:     my $userloadpercent=0;
 5568:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 5569:     if ($maxuserload) {
 5570: 	$userloadpercent=100*$numusers/$maxuserload;
 5571:     }
 5572:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 5573:     return $userloadpercent;
 5574: }
 5575: 
 5576: # Routines for serializing arrays and hashes (copies from lonnet)
 5577: 
 5578: sub array2str {
 5579:   my (@array) = @_;
 5580:   my $result=&arrayref2str(\@array);
 5581:   $result=~s/^__ARRAY_REF__//;
 5582:   $result=~s/__END_ARRAY_REF__$//;
 5583:   return $result;
 5584: }
 5585:                                                                                  
 5586: sub arrayref2str {
 5587:   my ($arrayref) = @_;
 5588:   my $result='__ARRAY_REF__';
 5589:   foreach my $elem (@$arrayref) {
 5590:     if(ref($elem) eq 'ARRAY') {
 5591:       $result.=&arrayref2str($elem).'&';
 5592:     } elsif(ref($elem) eq 'HASH') {
 5593:       $result.=&hashref2str($elem).'&';
 5594:     } elsif(ref($elem)) {
 5595:       #print("Got a ref of ".(ref($elem))." skipping.");
 5596:     } else {
 5597:       $result.=&escape($elem).'&';
 5598:     }
 5599:   }
 5600:   $result=~s/\&$//;
 5601:   $result .= '__END_ARRAY_REF__';
 5602:   return $result;
 5603: }
 5604:                                                                                  
 5605: sub hash2str {
 5606:   my (%hash) = @_;
 5607:   my $result=&hashref2str(\%hash);
 5608:   $result=~s/^__HASH_REF__//;
 5609:   $result=~s/__END_HASH_REF__$//;
 5610:   return $result;
 5611: }
 5612:                                                                                  
 5613: sub hashref2str {
 5614:   my ($hashref)=@_;
 5615:   my $result='__HASH_REF__';
 5616:   foreach (sort(keys(%$hashref))) {
 5617:     if (ref($_) eq 'ARRAY') {
 5618:       $result.=&arrayref2str($_).'=';
 5619:     } elsif (ref($_) eq 'HASH') {
 5620:       $result.=&hashref2str($_).'=';
 5621:     } elsif (ref($_)) {
 5622:       $result.='=';
 5623:       #print("Got a ref of ".(ref($_))." skipping.");
 5624:     } else {
 5625:         if ($_) {$result.=&escape($_).'=';} else { last; }
 5626:     }
 5627: 
 5628:     if(ref($hashref->{$_}) eq 'ARRAY') {
 5629:       $result.=&arrayref2str($hashref->{$_}).'&';
 5630:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 5631:       $result.=&hashref2str($hashref->{$_}).'&';
 5632:     } elsif(ref($hashref->{$_})) {
 5633:        $result.='&';
 5634:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 5635:     } else {
 5636:       $result.=&escape($hashref->{$_}).'&';
 5637:     }
 5638:   }
 5639:   $result=~s/\&$//;
 5640:   $result .= '__END_HASH_REF__';
 5641:   return $result;
 5642: }
 5643: 
 5644: # ----------------------------------- POD (plain old documentation, CPAN style)
 5645: 
 5646: =head1 NAME
 5647: 
 5648: lond - "LON Daemon" Server (port "LOND" 5663)
 5649: 
 5650: =head1 SYNOPSIS
 5651: 
 5652: Usage: B<lond>
 5653: 
 5654: Should only be run as user=www.  This is a command-line script which
 5655: is invoked by B<loncron>.  There is no expectation that a typical user
 5656: will manually start B<lond> from the command-line.  (In other words,
 5657: DO NOT START B<lond> YOURSELF.)
 5658: 
 5659: =head1 DESCRIPTION
 5660: 
 5661: There are two characteristics associated with the running of B<lond>,
 5662: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 5663: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 5664: subscriptions, etc).  These are described in two large
 5665: sections below.
 5666: 
 5667: B<PROCESS MANAGEMENT>
 5668: 
 5669: Preforker - server who forks first. Runs as a daemon. HUPs.
 5670: Uses IDEA encryption
 5671: 
 5672: B<lond> forks off children processes that correspond to the other servers
 5673: in the network.  Management of these processes can be done at the
 5674: parent process level or the child process level.
 5675: 
 5676: B<logs/lond.log> is the location of log messages.
 5677: 
 5678: The process management is now explained in terms of linux shell commands,
 5679: subroutines internal to this code, and signal assignments:
 5680: 
 5681: =over 4
 5682: 
 5683: =item *
 5684: 
 5685: PID is stored in B<logs/lond.pid>
 5686: 
 5687: This is the process id number of the parent B<lond> process.
 5688: 
 5689: =item *
 5690: 
 5691: SIGTERM and SIGINT
 5692: 
 5693: Parent signal assignment:
 5694:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 5695: 
 5696: Child signal assignment:
 5697:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 5698: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 5699:  to restart a new child.)
 5700: 
 5701: Command-line invocations:
 5702:  B<kill> B<-s> SIGTERM I<PID>
 5703:  B<kill> B<-s> SIGINT I<PID>
 5704: 
 5705: Subroutine B<HUNTSMAN>:
 5706:  This is only invoked for the B<lond> parent I<PID>.
 5707: This kills all the children, and then the parent.
 5708: The B<lonc.pid> file is cleared.
 5709: 
 5710: =item *
 5711: 
 5712: SIGHUP
 5713: 
 5714: Current bug:
 5715:  This signal can only be processed the first time
 5716: on the parent process.  Subsequent SIGHUP signals
 5717: have no effect.
 5718: 
 5719: Parent signal assignment:
 5720:  $SIG{HUP}  = \&HUPSMAN;
 5721: 
 5722: Child signal assignment:
 5723:  none (nothing happens)
 5724: 
 5725: Command-line invocations:
 5726:  B<kill> B<-s> SIGHUP I<PID>
 5727: 
 5728: Subroutine B<HUPSMAN>:
 5729:  This is only invoked for the B<lond> parent I<PID>,
 5730: This kills all the children, and then the parent.
 5731: The B<lond.pid> file is cleared.
 5732: 
 5733: =item *
 5734: 
 5735: SIGUSR1
 5736: 
 5737: Parent signal assignment:
 5738:  $SIG{USR1} = \&USRMAN;
 5739: 
 5740: Child signal assignment:
 5741:  $SIG{USR1}= \&logstatus;
 5742: 
 5743: Command-line invocations:
 5744:  B<kill> B<-s> SIGUSR1 I<PID>
 5745: 
 5746: Subroutine B<USRMAN>:
 5747:  When invoked for the B<lond> parent I<PID>,
 5748: SIGUSR1 is sent to all the children, and the status of
 5749: each connection is logged.
 5750: 
 5751: =item *
 5752: 
 5753: SIGUSR2
 5754: 
 5755: Parent Signal assignment:
 5756:     $SIG{USR2} = \&UpdateHosts
 5757: 
 5758: Child signal assignment:
 5759:     NONE
 5760: 
 5761: 
 5762: =item *
 5763: 
 5764: SIGCHLD
 5765: 
 5766: Parent signal assignment:
 5767:  $SIG{CHLD} = \&REAPER;
 5768: 
 5769: Child signal assignment:
 5770:  none
 5771: 
 5772: Command-line invocations:
 5773:  B<kill> B<-s> SIGCHLD I<PID>
 5774: 
 5775: Subroutine B<REAPER>:
 5776:  This is only invoked for the B<lond> parent I<PID>.
 5777: Information pertaining to the child is removed.
 5778: The socket port is cleaned up.
 5779: 
 5780: =back
 5781: 
 5782: B<SERVER-SIDE ACTIVITIES>
 5783: 
 5784: Server-side information can be accepted in an encrypted or non-encrypted
 5785: method.
 5786: 
 5787: =over 4
 5788: 
 5789: =item ping
 5790: 
 5791: Query a client in the hosts.tab table; "Are you there?"
 5792: 
 5793: =item pong
 5794: 
 5795: Respond to a ping query.
 5796: 
 5797: =item ekey
 5798: 
 5799: Read in encrypted key, make cipher.  Respond with a buildkey.
 5800: 
 5801: =item load
 5802: 
 5803: Respond with CPU load based on a computation upon /proc/loadavg.
 5804: 
 5805: =item currentauth
 5806: 
 5807: Reply with current authentication information (only over an
 5808: encrypted channel).
 5809: 
 5810: =item auth
 5811: 
 5812: Only over an encrypted channel, reply as to whether a user's
 5813: authentication information can be validated.
 5814: 
 5815: =item passwd
 5816: 
 5817: Allow for a password to be set.
 5818: 
 5819: =item makeuser
 5820: 
 5821: Make a user.
 5822: 
 5823: =item passwd
 5824: 
 5825: Allow for authentication mechanism and password to be changed.
 5826: 
 5827: =item home
 5828: 
 5829: Respond to a question "are you the home for a given user?"
 5830: 
 5831: =item update
 5832: 
 5833: Update contents of a subscribed resource.
 5834: 
 5835: =item unsubscribe
 5836: 
 5837: The server is unsubscribing from a resource.
 5838: 
 5839: =item subscribe
 5840: 
 5841: The server is subscribing to a resource.
 5842: 
 5843: =item log
 5844: 
 5845: Place in B<logs/lond.log>
 5846: 
 5847: =item put
 5848: 
 5849: stores hash in namespace
 5850: 
 5851: =item rolesputy
 5852: 
 5853: put a role into a user's environment
 5854: 
 5855: =item get
 5856: 
 5857: returns hash with keys from array
 5858: reference filled in from namespace
 5859: 
 5860: =item eget
 5861: 
 5862: returns hash with keys from array
 5863: reference filled in from namesp (encrypts the return communication)
 5864: 
 5865: =item rolesget
 5866: 
 5867: get a role from a user's environment
 5868: 
 5869: =item del
 5870: 
 5871: deletes keys out of array from namespace
 5872: 
 5873: =item keys
 5874: 
 5875: returns namespace keys
 5876: 
 5877: =item dump
 5878: 
 5879: dumps the complete (or key matching regexp) namespace into a hash
 5880: 
 5881: =item store
 5882: 
 5883: stores hash permanently
 5884: for this url; hashref needs to be given and should be a \%hashname; the
 5885: remaining args aren't required and if they aren't passed or are '' they will
 5886: be derived from the ENV
 5887: 
 5888: =item restore
 5889: 
 5890: returns a hash for a given url
 5891: 
 5892: =item querysend
 5893: 
 5894: Tells client about the lonsql process that has been launched in response
 5895: to a sent query.
 5896: 
 5897: =item queryreply
 5898: 
 5899: Accept information from lonsql and make appropriate storage in temporary
 5900: file space.
 5901: 
 5902: =item idput
 5903: 
 5904: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 5905: for each student, defined perhaps by the institutional Registrar.)
 5906: 
 5907: =item idget
 5908: 
 5909: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 5910: for each student, defined perhaps by the institutional Registrar.)
 5911: 
 5912: =item tmpput
 5913: 
 5914: Accept and store information in temporary space.
 5915: 
 5916: =item tmpget
 5917: 
 5918: Send along temporarily stored information.
 5919: 
 5920: =item ls
 5921: 
 5922: List part of a user's directory.
 5923: 
 5924: =item pushtable
 5925: 
 5926: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 5927: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 5928: must be restored manually in case of a problem with the new table file.
 5929: pushtable requires that the request be encrypted and validated via
 5930: ValidateManager.  The form of the command is:
 5931: enc:pushtable tablename <tablecontents> \n
 5932: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 5933: cleartext newline.
 5934: 
 5935: =item Hanging up (exit or init)
 5936: 
 5937: What to do when a client tells the server that they (the client)
 5938: are leaving the network.
 5939: 
 5940: =item unknown command
 5941: 
 5942: If B<lond> is sent an unknown command (not in the list above),
 5943: it replys to the client "unknown_cmd".
 5944: 
 5945: 
 5946: =item UNKNOWN CLIENT
 5947: 
 5948: If the anti-spoofing algorithm cannot verify the client,
 5949: the client is rejected (with a "refused" message sent
 5950: to the client, and the connection is closed.
 5951: 
 5952: =back
 5953: 
 5954: =head1 PREREQUISITES
 5955: 
 5956: IO::Socket
 5957: IO::File
 5958: Apache::File
 5959: Symbol
 5960: POSIX
 5961: Crypt::IDEA
 5962: LWP::UserAgent()
 5963: GDBM_File
 5964: Authen::Krb4
 5965: Authen::Krb5
 5966: 
 5967: =head1 COREQUISITES
 5968: 
 5969: =head1 OSNAMES
 5970: 
 5971: linux
 5972: 
 5973: =head1 SCRIPT CATEGORIES
 5974: 
 5975: Server/Process
 5976: 
 5977: =cut

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