Annotation of loncom/lond, revision 1.472

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

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