Annotation of loncom/lond, revision 1.471

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

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