File:  [LON-CAPA] / loncom / lond
Revision 1.279: download - view: text, annotated - select for diffs
Thu Feb 17 08:57:51 2005 UTC (19 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- cleaner call to gethostbyname

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

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