Annotation of loncom/lond, revision 1.469

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

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