Annotation of loncom/lond, revision 1.467.2.8

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

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