Annotation of loncom/lond, revision 1.496

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

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