Annotation of loncom/lond, revision 1.479

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

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