File:  [LON-CAPA] / loncom / lond
Revision 1.412: download - view: text, annotated - select for diffs
Tue Mar 3 12:08:07 2009 UTC (15 years, 2 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Debugged lond/lcinstallfile support for cluster administration of
dns_hosts.tab and dns_domain.tab  see also clusteradmin in this directory..

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

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