File:  [LON-CAPA] / loncom / lond
Revision 1.267: download - view: text, annotated - select for diffs
Wed Dec 8 22:45:33 2004 UTC (19 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: version_1_2_99_1, HEAD
Sub-directories were not being made for user uploads where ufile argument included a directory, e.g.,  aboutme/myphoto.gif.  Correction to refactoring from v1.264

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

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