Annotation of loncom/lond, revision 1.438

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

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