Annotation of loncom/lond, revision 1.474

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

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