Annotation of loncom/lond, revision 1.428

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

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