File:  [LON-CAPA] / loncom / lond
Revision 1.305.2.3: download - view: text, annotated - select for diffs
Tue Feb 7 16:43:22 2006 UTC (18 years, 2 months ago) by albertel
Branches: version_2_1_X
- backport 1.317 1.318

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

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