Annotation of loncom/lond, revision 1.448

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

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