File:  [LON-CAPA] / loncom / lond
Revision 1.336: download - view: text, annotated - select for diffs
Tue Jul 11 02:28:17 2006 UTC (17 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_2_0, version_2_1_99_3, version_2_1_99_2, version_2_1_99_1, HEAD
Bug 4813.  Retain backwards compatibility with legacy courses in which only a course owner's username is stored in environment.internal.courseowner, and in the course's record in nohist_courseids.db.  New courses will include username:domain (escaped) in nohist_courseids.db.  MCRS can be used to update legacy course owner information (just click "Modify Settings" button, it will be necessary to select the correct course owner where the course domain is different from the owner's domain.

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

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