File:  [LON-CAPA] / loncom / lond
Revision 1.258: download - view: text, annotated - select for diffs
Tue Sep 14 20:18:41 2004 UTC (20 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- removing logthis

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

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