Annotation of loncom/lond, revision 1.422

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

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