Annotation of loncom/lond, revision 1.439

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

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