File:  [LON-CAPA] / loncom / lond
Revision 1.253: download - view: text, annotated - select for diffs
Tue Sep 14 09:30:07 2004 UTC (19 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
- Fix a stupid cut/paste omission in courseid put and
- Add a few comments where I thought  it needed them

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

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