File:  [LON-CAPA] / loncom / lond
Revision 1.304: download - view: text, annotated - select for diffs
Sat Dec 10 00:46:23 2005 UTC (18 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_1_1, version_2_1_0, version_2_0_99_1, HEAD
Use lonmsg::unpackmsgid() to split msgid for sentmail.  remove some unnecessary unescaping from lond.

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

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