File:  [LON-CAPA] / loncom / lond
Revision 1.263: download - view: text, annotated - select for diffs
Thu Oct 21 16:05:50 2004 UTC (19 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- cleanup some ws and &

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

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