Annotation of loncom/lond, revision 1.477

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

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