File:  [LON-CAPA] / loncom / lond
Revision 1.467.2.3: download - view: text, annotated - select for diffs
Sat May 14 17:14:29 2011 UTC (12 years, 11 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_0
Diff to branchpoint 1.467: preferred, unified
- Backport 1.471, 1.472, 1.473, 1.474.

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

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