Annotation of loncom/lond, revision 1.467.2.7

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

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