File:  [LON-CAPA] / loncom / lond
Revision 1.311: download - view: text, annotated - select for diffs
Tue Jan 31 15:37:41 2006 UTC (18 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- centralizing the usage of untie

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

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