File:  [LON-CAPA] / loncom / lond
Revision 1.317: download - view: text, annotated - select for diffs
Tue Feb 7 05:08:27 2006 UTC (18 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Add support for student photo import from an institutional repository. Availability of photos of registered students in a course controlled by course environment parameter: 'internal.studentphoto'.  This may be configured to require initial acceptance of conditions of use by course owner.  View classlist in ENRL, and Automated Enrollment Manager now includes option to display thumbnails of student photos.  Nightly enrollment update can import student photos for students added to a course.  Student photos can be updated via the Automated Enrollment Manager.

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

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