Annotation of loncom/lond, revision 1.467.2.5

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

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