File:  [LON-CAPA] / loncom / lond
Revision 1.313: download - view: text, annotated - select for diffs
Tue Jan 31 16:12:12 2006 UTC (18 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#4608 & BUG#4476, lond now should block for up to 13 seconds waiting for  lock on a db file

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

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