Annotation of loncom/lond, revision 1.331

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.331   ! www         5: # $Id: lond,v 1.330 2006/05/18 19:57:59 albertel 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.3       www        43: use GDBM_File;
                     44: use Authen::Krb4;
1.91      albertel   45: use Authen::Krb5;
1.49      albertel   46: use lib '/home/httpd/lib/perl/';
                     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.169     foxr       52: use LONCAPA::ConfigFileEdit;
1.200     matthew    53: use LONCAPA::lonlocal;
                     54: use LONCAPA::lonssl;
1.221     albertel   55: use Fcntl qw(:flock);
1.1       albertel   56: 
1.239     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.331   ! www        62: my $VERSION='$Revision: 1.330 $'; #' 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: my $thisserver;			# DNS of us.
                     73: 
                     74: my $keymode;
1.198     foxr       75: 
1.207     foxr       76: my $cipher;			# Cipher key negotiated with client
                     77: my $tmpsnum = 0;		# Id of tmpputs.
                     78: 
1.178     foxr       79: # 
                     80: #   Connection type is:
                     81: #      client                   - All client actions are allowed
                     82: #      manager                  - only management functions allowed.
                     83: #      both                     - Both management and client actions are allowed
                     84: #
1.161     foxr       85: 
1.178     foxr       86: my $ConnectionType;
1.161     foxr       87: 
1.200     matthew    88: my %hostid;			# ID's for hosts in cluster by ip.
                     89: my %hostdom;			# LonCAPA domain for hosts in cluster.
1.307     albertel   90: my %hostname;			# DNSname -> ID's mapping.
1.200     matthew    91: my %hostip;			# IPs for hosts in cluster.
                     92: my %hostdns;			# ID's of hosts looked up by DNS name.
1.161     foxr       93: 
1.178     foxr       94: my %managers;			# Ip -> manager names
1.161     foxr       95: 
1.178     foxr       96: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel   97: 
1.178     foxr       98: #
1.207     foxr       99: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                    100: #    Each element of the hash contains a reference to an array that contains:
                    101: #          A reference to a sub that executes the request corresponding to the keyword.
                    102: #          A flag that is true if the request must be encoded to be acceptable.
                    103: #          A mask with bits as follows:
                    104: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    105: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    106: #
                    107: my $CLIENT_OK  = 1;
                    108: my $MANAGER_OK = 2;
                    109: my %Dispatcher;
                    110: 
                    111: 
                    112: #
1.178     foxr      113: #  The array below are password error strings."
                    114: #
                    115: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    116: my @passwderrors = ("ok",
1.287     foxr      117: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
                    118: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
                    119: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
                    120: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
                    121: 		   "pwchange_failure - lcpasswd User does not exist.",
                    122: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
                    123: 		   "pwchange_failure - lcpasswd Unable to su to root.",
                    124: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
                    125: 		   "pwchange_failure - lcpasswd Username has invalid characters",
                    126: 		   "pwchange_failure - lcpasswd Invalid characters in password",
                    127: 		   "pwchange_failure - lcpasswd User already exists", 
                    128:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
                    129: 		   "pwchange_failure - lcpasswd Password mismatch",
                    130: 		   "pwchange_failure - lcpasswd Error filename is invalid");
1.97      foxr      131: 
                    132: 
1.178     foxr      133: #  The array below are lcuseradd error strings.:
1.97      foxr      134: 
1.178     foxr      135: my $lastadderror = 13;
                    136: my @adderrors    = ("ok",
                    137: 		    "User ID mismatch, lcuseradd must run as user www",
                    138: 		    "lcuseradd Incorrect number of command line parameters must be 3",
                    139: 		    "lcuseradd Incorrect number of stdinput lines, must be 3",
                    140: 		    "lcuseradd Too many other simultaneous pwd changes in progress",
                    141: 		    "lcuseradd User does not exist",
                    142: 		    "lcuseradd Unable to make www member of users's group",
                    143: 		    "lcuseradd Unable to su to root",
                    144: 		    "lcuseradd Unable to set password",
                    145: 		    "lcuseradd Usrname has invalid characters",
                    146: 		    "lcuseradd Password has an invalid character",
                    147: 		    "lcuseradd User already exists",
                    148: 		    "lcuseradd Could not add user.",
                    149: 		    "lcuseradd Password mismatch");
1.97      foxr      150: 
1.96      foxr      151: 
1.207     foxr      152: 
                    153: #
                    154: #   Statistics that are maintained and dislayed in the status line.
                    155: #
1.212     foxr      156: my $Transactions = 0;		# Number of attempted transactions.
                    157: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      158: 
                    159: #   ResetStatistics: 
                    160: #      Resets the statistics counters:
                    161: #
                    162: sub ResetStatistics {
                    163:     $Transactions = 0;
                    164:     $Failures     = 0;
                    165: }
                    166: 
1.200     matthew   167: #------------------------------------------------------------------------
                    168: #
                    169: #   LocalConnection
                    170: #     Completes the formation of a locally authenticated connection.
                    171: #     This function will ensure that the 'remote' client is really the
                    172: #     local host.  If not, the connection is closed, and the function fails.
                    173: #     If so, initcmd is parsed for the name of a file containing the
                    174: #     IDEA session key.  The fie is opened, read, deleted and the session
                    175: #     key returned to the caller.
                    176: #
                    177: # Parameters:
                    178: #   $Socket      - Socket open on client.
                    179: #   $initcmd     - The full text of the init command.
                    180: #
                    181: # Implicit inputs:
                    182: #    $thisserver - Our DNS name.
                    183: #
                    184: # Returns:
                    185: #     IDEA session key on success.
                    186: #     undef on failure.
                    187: #
                    188: sub LocalConnection {
                    189:     my ($Socket, $initcmd) = @_;
1.277     albertel  190:     Debug("Attempting local connection: $initcmd client: $clientip me: $thisserver");
                    191:     if($clientip ne "127.0.0.1") {
1.200     matthew   192: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.277     albertel  193: 		 ."$clientip ne $thisserver </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: 
                    411:     #   Clean out the old table first..
                    412: 
1.166     foxr      413:    foreach my $key (keys %managers) {
                    414:       delete $managers{$key};
                    415:    }
                    416: 
                    417:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    418:    if (!open (MANAGERS, $tablename)) {
                    419:       logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    420:       return;
                    421:    }
                    422:    while(my $host = <MANAGERS>) {
                    423:       chomp($host);
                    424:       if ($host =~ "^#") {                  # Comment line.
                    425:          next;
                    426:       }
                    427:       if (!defined $hostip{$host}) { # This is a non cluster member
1.161     foxr      428: 	    #  The entry is of the form:
                    429: 	    #    cluname:hostname
                    430: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    431: 	    #            the host key.
                    432: 	    #  hostname- The dns name of the host.
                    433: 	    #
1.166     foxr      434:           my($cluname, $dnsname) = split(/:/, $host);
                    435:           
                    436:           my $ip = gethostbyname($dnsname);
                    437:           if(defined($ip)) {                 # bad names don't deserve entry.
                    438:             my $hostip = inet_ntoa($ip);
                    439:             $managers{$hostip} = $cluname;
                    440:             logthis('<font color="green"> registering manager '.
                    441:                     "$dnsname as $cluname with $hostip </font>\n");
                    442:          }
                    443:       } else {
                    444:          logthis('<font color="green"> existing host'." $host</font>\n");
                    445:          $managers{$hostip{$host}} = $host;  # Use info from cluster tab if clumemeber
                    446:       }
                    447:    }
1.156     foxr      448: }
1.140     foxr      449: 
                    450: #
                    451: #  ValidManager: Determines if a given certificate represents a valid manager.
                    452: #                in this primitive implementation, the 'certificate' is
                    453: #                just the connecting loncapa client name.  This is checked
                    454: #                against a valid client list in the configuration.
                    455: #
                    456: #                  
                    457: sub ValidManager {
                    458:     my $certificate = shift; 
                    459: 
1.163     foxr      460:     return isManager;
1.140     foxr      461: }
                    462: #
1.143     foxr      463: #  CopyFile:  Called as part of the process of installing a 
                    464: #             new configuration file.  This function copies an existing
                    465: #             file to a backup file.
                    466: # Parameters:
                    467: #     oldfile  - Name of the file to backup.
                    468: #     newfile  - Name of the backup file.
                    469: # Return:
                    470: #     0   - Failure (errno has failure reason).
                    471: #     1   - Success.
                    472: #
                    473: sub CopyFile {
1.192     foxr      474: 
                    475:     my ($oldfile, $newfile) = @_;
1.143     foxr      476: 
1.281     matthew   477:     if (! copy($oldfile,$newfile)) {
                    478:         return 0;
1.143     foxr      479:     }
1.281     matthew   480:     chmod(0660, $newfile);
                    481:     return 1;
1.143     foxr      482: }
1.157     foxr      483: #
                    484: #  Host files are passed out with externally visible host IPs.
                    485: #  If, for example, we are behind a fire-wall or NAT host, our 
                    486: #  internally visible IP may be different than the externally
                    487: #  visible IP.  Therefore, we always adjust the contents of the
                    488: #  host file so that the entry for ME is the IP that we believe
                    489: #  we have.  At present, this is defined as the entry that
                    490: #  DNS has for us.  If by some chance we are not able to get a
                    491: #  DNS translation for us, then we assume that the host.tab file
                    492: #  is correct.  
                    493: #    BUGBUGBUG - in the future, we really should see if we can
                    494: #       easily query the interface(s) instead.
                    495: # Parameter(s):
                    496: #     contents    - The contents of the host.tab to check.
                    497: # Returns:
                    498: #     newcontents - The adjusted contents.
                    499: #
                    500: #
                    501: sub AdjustHostContents {
                    502:     my $contents  = shift;
                    503:     my $adjusted;
                    504:     my $me        = $perlvar{'lonHostID'};
                    505: 
1.166     foxr      506:  foreach my $line (split(/\n/,$contents)) {
1.157     foxr      507: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
                    508: 	    chomp($line);
                    509: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    510: 	    if ($id eq $me) {
1.166     foxr      511:           my $ip = gethostbyname($name);
                    512:           my $ipnew = inet_ntoa($ip);
                    513:          $ip = $ipnew;
1.157     foxr      514: 		#  Reconstruct the host line and append to adjusted:
                    515: 		
1.166     foxr      516: 		   my $newline = "$id:$domain:$role:$name:$ip";
                    517: 		   if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    518: 		     $newline .= ":$maxcon:$idleto:$mincon";
                    519: 		   }
                    520: 		   $adjusted .= $newline."\n";
1.157     foxr      521: 		
1.166     foxr      522:       } else {		# Not me, pass unmodified.
                    523: 		   $adjusted .= $line."\n";
                    524:       }
1.157     foxr      525: 	} else {                  # Blank or comment never re-written.
                    526: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    527: 	}
1.166     foxr      528:  }
                    529:  return $adjusted;
1.157     foxr      530: }
1.143     foxr      531: #
                    532: #   InstallFile: Called to install an administrative file:
                    533: #       - The file is created with <name>.tmp
                    534: #       - The <name>.tmp file is then mv'd to <name>
                    535: #   This lugubrious procedure is done to ensure that we are never without
                    536: #   a valid, even if dated, version of the file regardless of who crashes
                    537: #   and when the crash occurs.
                    538: #
                    539: #  Parameters:
                    540: #       Name of the file
                    541: #       File Contents.
                    542: #  Return:
                    543: #      nonzero - success.
                    544: #      0       - failure and $! has an errno.
                    545: #
                    546: sub InstallFile {
1.192     foxr      547: 
                    548:     my ($Filename, $Contents) = @_;
1.143     foxr      549:     my $TempFile = $Filename.".tmp";
                    550: 
                    551:     #  Open the file for write:
                    552: 
                    553:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    554:     if(!(defined $fh)) {
                    555: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    556: 	return 0;
                    557:     }
                    558:     #  write the contents of the file:
                    559: 
                    560:     print $fh ($Contents); 
                    561:     $fh->close;			# In case we ever have a filesystem w. locking
                    562: 
                    563:     chmod(0660, $TempFile);
                    564: 
                    565:     # Now we can move install the file in position.
                    566:     
                    567:     move($TempFile, $Filename);
                    568: 
                    569:     return 1;
                    570: }
1.200     matthew   571: 
                    572: 
1.169     foxr      573: #
                    574: #   ConfigFileFromSelector: converts a configuration file selector
                    575: #                 (one of host or domain at this point) into a 
                    576: #                 configuration file pathname.
                    577: #
                    578: #  Parameters:
                    579: #      selector  - Configuration file selector.
                    580: #  Returns:
                    581: #      Full path to the file or undef if the selector is invalid.
                    582: #
                    583: sub ConfigFileFromSelector {
                    584:     my $selector   = shift;
                    585:     my $tablefile;
                    586: 
                    587:     my $tabledir = $perlvar{'lonTabDir'}.'/';
                    588:     if ($selector eq "hosts") {
                    589: 	$tablefile = $tabledir."hosts.tab";
                    590:     } elsif ($selector eq "domain") {
                    591: 	$tablefile = $tabledir."domain.tab";
                    592:     } else {
                    593: 	return undef;
                    594:     }
                    595:     return $tablefile;
1.143     foxr      596: 
1.169     foxr      597: }
1.143     foxr      598: #
1.141     foxr      599: #   PushFile:  Called to do an administrative push of a file.
                    600: #              - Ensure the file being pushed is one we support.
                    601: #              - Backup the old file to <filename.saved>
                    602: #              - Separate the contents of the new file out from the
                    603: #                rest of the request.
                    604: #              - Write the new file.
                    605: #  Parameter:
                    606: #     Request - The entire user request.  This consists of a : separated
                    607: #               string pushfile:tablename:contents.
                    608: #     NOTE:  The contents may have :'s in it as well making things a bit
                    609: #            more interesting... but not much.
                    610: #  Returns:
                    611: #     String to send to client ("ok" or "refused" if bad file).
                    612: #
                    613: sub PushFile {
                    614:     my $request = shift;    
                    615:     my ($command, $filename, $contents) = split(":", $request, 3);
                    616:     
                    617:     #  At this point in time, pushes for only the following tables are
                    618:     #  supported:
                    619:     #   hosts.tab  ($filename eq host).
                    620:     #   domain.tab ($filename eq domain).
                    621:     # Construct the destination filename or reject the request.
                    622:     #
                    623:     # lonManage is supposed to ensure this, however this session could be
                    624:     # part of some elaborate spoof that managed somehow to authenticate.
                    625:     #
                    626: 
1.169     foxr      627: 
                    628:     my $tablefile = ConfigFileFromSelector($filename);
                    629:     if(! (defined $tablefile)) {
1.141     foxr      630: 	return "refused";
                    631:     }
                    632:     #
                    633:     # >copy< the old table to the backup table
                    634:     #        don't rename in case system crashes/reboots etc. in the time
                    635:     #        window between a rename and write.
                    636:     #
                    637:     my $backupfile = $tablefile;
                    638:     $backupfile    =~ s/\.tab$/.old/;
1.143     foxr      639:     if(!CopyFile($tablefile, $backupfile)) {
                    640: 	&logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
                    641: 	return "error:$!";
                    642:     }
1.141     foxr      643:     &logthis('<font color="green"> Pushfile: backed up '
                    644: 	    .$tablefile." to $backupfile</font>");
                    645:     
1.157     foxr      646:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    647:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    648:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    649:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    650:     #  that possibilty.
                    651: 
                    652:     if($filename eq "host") {
                    653: 	$contents = AdjustHostContents($contents);
                    654:     }
                    655: 
1.141     foxr      656:     #  Install the new file:
                    657: 
1.143     foxr      658:     if(!InstallFile($tablefile, $contents)) {
                    659: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      660: 	 .$tablefile." $! </font>");
1.143     foxr      661: 	return "error:$!";
1.224     foxr      662:     } else {
1.143     foxr      663: 	&logthis('<font color="green"> Installed new '.$tablefile
                    664: 		 ."</font>");
                    665: 
                    666:     }
                    667: 
1.141     foxr      668: 
                    669:     #  Indicate success:
                    670:  
                    671:     return "ok";
                    672: 
                    673: }
1.145     foxr      674: 
                    675: #
                    676: #  Called to re-init either lonc or lond.
                    677: #
                    678: #  Parameters:
                    679: #    request   - The full request by the client.  This is of the form
                    680: #                reinit:<process>  
                    681: #                where <process> is allowed to be either of 
                    682: #                lonc or lond
                    683: #
                    684: #  Returns:
                    685: #     The string to be sent back to the client either:
                    686: #   ok         - Everything worked just fine.
                    687: #   error:why  - There was a failure and why describes the reason.
                    688: #
                    689: #
                    690: sub ReinitProcess {
                    691:     my $request = shift;
                    692: 
1.146     foxr      693: 
                    694:     # separate the request (reinit) from the process identifier and
                    695:     # validate it producing the name of the .pid file for the process.
                    696:     #
                    697:     #
                    698:     my ($junk, $process) = split(":", $request);
1.147     foxr      699:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      700:     if($process eq 'lonc') {
                    701: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      702: 	if (!open(PIDFILE, "< $processpidfile")) {
                    703: 	    return "error:Open failed for $processpidfile";
                    704: 	}
                    705: 	my $loncpid = <PIDFILE>;
                    706: 	close(PIDFILE);
                    707: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    708: 		."</font>");
                    709: 	kill("USR2", $loncpid);
1.146     foxr      710:     } elsif ($process eq 'lond') {
1.147     foxr      711: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    712: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      713:     } else {
                    714: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    715: 		 ."</font>");
                    716: 	return "error:Invalid process identifier $process";
                    717:     }
1.145     foxr      718:     return 'ok';
                    719: }
1.168     foxr      720: #   Validate a line in a configuration file edit script:
                    721: #   Validation includes:
                    722: #     - Ensuring the command is valid.
                    723: #     - Ensuring the command has sufficient parameters
                    724: #   Parameters:
                    725: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      726: #
1.168     foxr      727: #   Return:
                    728: #      0     - Invalid scriptline.
                    729: #      1     - Valid scriptline
                    730: #  NOTE:
                    731: #     Only the command syntax is checked, not the executability of the
                    732: #     command.
                    733: #
                    734: sub isValidEditCommand {
                    735:     my $scriptline = shift;
                    736: 
                    737:     #   Line elements are pipe separated:
                    738: 
                    739:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                    740:     &logthis('<font color="green"> isValideditCommand checking: '.
                    741: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                    742:     
                    743:     if ($command eq "delete") {
                    744: 	#
                    745: 	#   key with no newline.
                    746: 	#
                    747: 	if( ($key eq "") || ($newline ne "")) {
                    748: 	    return 0;		# Must have key but no newline.
                    749: 	} else {
                    750: 	    return 1;		# Valid syntax.
                    751: 	}
1.169     foxr      752:     } elsif ($command eq "replace") {
1.168     foxr      753: 	#
                    754: 	#   key and newline:
                    755: 	#
                    756: 	if (($key eq "") || ($newline eq "")) {
                    757: 	    return 0;
                    758: 	} else {
                    759: 	    return 1;
                    760: 	}
1.169     foxr      761:     } elsif ($command eq "append") {
                    762: 	if (($key ne "") && ($newline eq "")) {
                    763: 	    return 1;
                    764: 	} else {
                    765: 	    return 0;
                    766: 	}
1.168     foxr      767:     } else {
                    768: 	return 0;		# Invalid command.
                    769:     }
                    770:     return 0;			# Should not get here!!!
                    771: }
1.169     foxr      772: #
                    773: #   ApplyEdit - Applies an edit command to a line in a configuration 
                    774: #               file.  It is the caller's responsiblity to validate the
                    775: #               edit line.
                    776: #   Parameters:
                    777: #      $directive - A single edit directive to apply.  
                    778: #                   Edit directives are of the form:
                    779: #                  append|newline      - Appends a new line to the file.
                    780: #                  replace|key|newline - Replaces the line with key value 'key'
                    781: #                  delete|key          - Deletes the line with key value 'key'.
                    782: #      $editor   - A config file editor object that contains the
                    783: #                  file being edited.
                    784: #
                    785: sub ApplyEdit {
1.192     foxr      786: 
                    787:     my ($directive, $editor) = @_;
1.169     foxr      788: 
                    789:     # Break the directive down into its command and its parameters
                    790:     # (at most two at this point.  The meaning of the parameters, if in fact
                    791:     #  they exist depends on the command).
                    792: 
                    793:     my ($command, $p1, $p2) = split(/\|/, $directive);
                    794: 
                    795:     if($command eq "append") {
                    796: 	$editor->Append($p1);	          # p1 - key p2 null.
                    797:     } elsif ($command eq "replace") {
                    798: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                    799:     } elsif ($command eq "delete") {
                    800: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                    801:     } else {			          # Should not get here!!!
                    802: 	die "Invalid command given to ApplyEdit $command"
                    803:     }
                    804: }
                    805: #
                    806: # AdjustOurHost:
                    807: #           Adjusts a host file stored in a configuration file editor object
                    808: #           for the true IP address of this host. This is necessary for hosts
                    809: #           that live behind a firewall.
                    810: #           Those hosts have a publicly distributed IP of the firewall, but
                    811: #           internally must use their actual IP.  We assume that a given
                    812: #           host only has a single IP interface for now.
                    813: # Formal Parameters:
                    814: #     editor   - The configuration file editor to adjust.  This
                    815: #                editor is assumed to contain a hosts.tab file.
                    816: # Strategy:
                    817: #    - Figure out our hostname.
                    818: #    - Lookup the entry for this host.
                    819: #    - Modify the line to contain our IP
                    820: #    - Do a replace for this host.
                    821: sub AdjustOurHost {
                    822:     my $editor        = shift;
                    823: 
                    824:     # figure out who I am.
                    825: 
                    826:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                    827: 
                    828:     #  Get my host file entry.
                    829: 
                    830:     my $ConfigLine    = $editor->Find($myHostName);
                    831:     if(! (defined $ConfigLine)) {
                    832: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                    833:     }
                    834:     # figure out my IP:
                    835:     #   Use the config line to get my hostname.
                    836:     #   Use gethostbyname to translate that into an IP address.
                    837:     #
                    838:     my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
                    839:     my $BinaryIp = gethostbyname($name);
                    840:     my $ip       = inet_ntoa($ip);
                    841:     #
                    842:     #  Reassemble the config line from the elements in the list.
                    843:     #  Note that if the loncnew items were not present before, they will
                    844:     #  be now even if they would be empty
                    845:     #
                    846:     my $newConfigLine = $id;
                    847:     foreach my $item ($domain, $role, $name, $ip, $maxcon, $idleto, $mincon) {
                    848: 	$newConfigLine .= ":".$item;
                    849:     }
                    850:     #  Replace the line:
                    851: 
                    852:     $editor->ReplaceLine($id, $newConfigLine);
                    853:     
                    854: }
                    855: #
                    856: #   ReplaceConfigFile:
                    857: #              Replaces a configuration file with the contents of a
                    858: #              configuration file editor object.
                    859: #              This is done by:
                    860: #              - Copying the target file to <filename>.old
                    861: #              - Writing the new file to <filename>.tmp
                    862: #              - Moving <filename.tmp>  -> <filename>
                    863: #              This laborious process ensures that the system is never without
                    864: #              a configuration file that's at least valid (even if the contents
                    865: #              may be dated).
                    866: #   Parameters:
                    867: #        filename   - Name of the file to modify... this is a full path.
                    868: #        editor     - Editor containing the file.
                    869: #
                    870: sub ReplaceConfigFile {
1.192     foxr      871:     
                    872:     my ($filename, $editor) = @_;
1.168     foxr      873: 
1.169     foxr      874:     CopyFile ($filename, $filename.".old");
                    875: 
                    876:     my $contents  = $editor->Get(); # Get the contents of the file.
                    877: 
                    878:     InstallFile($filename, $contents);
                    879: }
1.168     foxr      880: #   
                    881: #
                    882: #   Called to edit a configuration table  file
1.167     foxr      883: #   Parameters:
                    884: #      request           - The entire command/request sent by lonc or lonManage
                    885: #   Return:
                    886: #      The reply to send to the client.
1.168     foxr      887: #
1.167     foxr      888: sub EditFile {
                    889:     my $request = shift;
                    890: 
                    891:     #  Split the command into it's pieces:  edit:filetype:script
                    892: 
1.168     foxr      893:     my ($request, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr      894: 
                    895:     #  Check the pre-coditions for success:
                    896: 
                    897:     if($request != "edit") {	# Something is amiss afoot alack.
                    898: 	return "error:edit request detected, but request != 'edit'\n";
                    899:     }
                    900:     if( ($filetype ne "hosts")  &&
                    901: 	($filetype ne "domain")) {
                    902: 	return "error:edit requested with invalid file specifier: $filetype \n";
                    903:     }
                    904: 
                    905:     #   Split the edit script and check it's validity.
1.168     foxr      906: 
                    907:     my @scriptlines = split(/\n/, $script);  # one line per element.
                    908:     my $linecount   = scalar(@scriptlines);
                    909:     for(my $i = 0; $i < $linecount; $i++) {
                    910: 	chomp($scriptlines[$i]);
                    911: 	if(!isValidEditCommand($scriptlines[$i])) {
                    912: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                    913: 	}
                    914:     }
1.145     foxr      915: 
1.167     foxr      916:     #   Execute the edit operation.
1.169     foxr      917:     #   - Create a config file editor for the appropriate file and 
                    918:     #   - execute each command in the script:
                    919:     #
                    920:     my $configfile = ConfigFileFromSelector($filetype);
                    921:     if (!(defined $configfile)) {
                    922: 	return "refused\n";
                    923:     }
                    924:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr      925: 
1.169     foxr      926:     for (my $i = 0; $i < $linecount; $i++) {
                    927: 	ApplyEdit($scriptlines[$i], $editor);
                    928:     }
                    929:     # If the file is the host file, ensure that our host is
                    930:     # adjusted to have our ip:
                    931:     #
                    932:     if($filetype eq "host") {
                    933: 	AdjustOurHost($editor);
                    934:     }
                    935:     #  Finally replace the current file with our file.
                    936:     #
                    937:     ReplaceConfigFile($configfile, $editor);
1.167     foxr      938: 
                    939:     return "ok\n";
                    940: }
1.207     foxr      941: 
1.255     foxr      942: #   read_profile
                    943: #
                    944: #   Returns a set of specific entries from a user's profile file.
                    945: #   this is a utility function that is used by both get_profile_entry and
                    946: #   get_profile_entry_encrypted.
                    947: #
                    948: # Parameters:
                    949: #    udom       - Domain in which the user exists.
                    950: #    uname      - User's account name (loncapa account)
                    951: #    namespace  - The profile namespace to open.
                    952: #    what       - A set of & separated queries.
                    953: # Returns:
                    954: #    If all ok: - The string that needs to be shipped back to the user.
                    955: #    If failure - A string that starts with error: followed by the failure
                    956: #                 reason.. note that this probabyl gets shipped back to the
                    957: #                 user as well.
                    958: #
                    959: sub read_profile {
                    960:     my ($udom, $uname, $namespace, $what) = @_;
                    961:     
                    962:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                    963: 				 &GDBM_READER());
                    964:     if ($hashref) {
                    965:         my @queries=split(/\&/,$what);
                    966:         my $qresult='';
                    967: 	
                    968: 	for (my $i=0;$i<=$#queries;$i++) {
                    969: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                    970: 	}
                    971: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel  972: 	if (&untie_user_hash($hashref)) {
1.255     foxr      973: 	    return $qresult;
                    974: 	} else {
                    975: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                    976: 	}
                    977:     } else {
                    978: 	if ($!+0 == 2) {
                    979: 	    return "error:No such file or GDBM reported bad block error";
                    980: 	} else {
                    981: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                    982: 	}
                    983:     }
                    984: 
                    985: }
1.214     foxr      986: #--------------------- Request Handlers --------------------------------------------
                    987: #
1.215     foxr      988: #   By convention each request handler registers itself prior to the sub 
                    989: #   declaration:
1.214     foxr      990: #
                    991: 
1.216     foxr      992: #++
                    993: #
1.214     foxr      994: #  Handles ping requests.
                    995: #  Parameters:
                    996: #      $cmd    - the actual keyword that invoked us.
                    997: #      $tail   - the tail of the request that invoked us.
                    998: #      $replyfd- File descriptor connected to the client
                    999: #  Implicit Inputs:
                   1000: #      $currenthostid - Global variable that carries the name of the host we are
                   1001: #                       known as.
                   1002: #  Returns:
                   1003: #      1       - Ok to continue processing.
                   1004: #      0       - Program should exit.
                   1005: #  Side effects:
                   1006: #      Reply information is sent to the client.
                   1007: sub ping_handler {
                   1008:     my ($cmd, $tail, $client) = @_;
                   1009:     Debug("$cmd $tail $client .. $currenthostid:");
                   1010:    
                   1011:     Reply( $client,"$currenthostid\n","$cmd:$tail");
                   1012:    
                   1013:     return 1;
                   1014: }
                   1015: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1016: 
1.216     foxr     1017: #++
1.215     foxr     1018: #
                   1019: # Handles pong requests.  Pong replies with our current host id, and
                   1020: #                         the results of a ping sent to us via our lonc.
                   1021: #
                   1022: # Parameters:
                   1023: #      $cmd    - the actual keyword that invoked us.
                   1024: #      $tail   - the tail of the request that invoked us.
                   1025: #      $replyfd- File descriptor connected to the client
                   1026: #  Implicit Inputs:
                   1027: #      $currenthostid - Global variable that carries the name of the host we are
                   1028: #                       connected to.
                   1029: #  Returns:
                   1030: #      1       - Ok to continue processing.
                   1031: #      0       - Program should exit.
                   1032: #  Side effects:
                   1033: #      Reply information is sent to the client.
                   1034: sub pong_handler {
                   1035:     my ($cmd, $tail, $replyfd) = @_;
                   1036: 
                   1037:     my $reply=&reply("ping",$clientname);
                   1038:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1039:     return 1;
                   1040: }
                   1041: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1042: 
1.216     foxr     1043: #++
                   1044: #      Called to establish an encrypted session key with the remote client.
                   1045: #      Note that with secure lond, in most cases this function is never
                   1046: #      invoked.  Instead, the secure session key is established either
                   1047: #      via a local file that's locked down tight and only lives for a short
                   1048: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1049: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1050: #      by this sub.  This sub is only used in the old-style insecure
                   1051: #      key negotiation.
                   1052: # Parameters:
                   1053: #      $cmd    - the actual keyword that invoked us.
                   1054: #      $tail   - the tail of the request that invoked us.
                   1055: #      $replyfd- File descriptor connected to the client
                   1056: #  Implicit Inputs:
                   1057: #      $currenthostid - Global variable that carries the name of the host
                   1058: #                       known as.
                   1059: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
                   1060: #  Returns:
                   1061: #      1       - Ok to continue processing.
                   1062: #      0       - Program should exit.
                   1063: #  Implicit Outputs:
                   1064: #      Reply information is sent to the client.
                   1065: #      $cipher is set with a reference to a new IDEA encryption object.
                   1066: #
                   1067: sub establish_key_handler {
                   1068:     my ($cmd, $tail, $replyfd) = @_;
                   1069: 
                   1070:     my $buildkey=time.$$.int(rand 100000);
                   1071:     $buildkey=~tr/1-6/A-F/;
                   1072:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1073:     my $key=$currenthostid.$clientname;
                   1074:     $key=~tr/a-z/A-Z/;
                   1075:     $key=~tr/G-P/0-9/;
                   1076:     $key=~tr/Q-Z/0-9/;
                   1077:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1078:     $key=substr($key,0,32);
                   1079:     my $cipherkey=pack("H32",$key);
                   1080:     $cipher=new IDEA $cipherkey;
                   1081:     &Reply($replyfd, "$buildkey\n", "$cmd:$tail"); 
                   1082:    
                   1083:     return 1;
                   1084: 
                   1085: }
                   1086: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1087: 
1.217     foxr     1088: #     Handler for the load command.  Returns the current system load average
                   1089: #     to the requestor.
                   1090: #
                   1091: # Parameters:
                   1092: #      $cmd    - the actual keyword that invoked us.
                   1093: #      $tail   - the tail of the request that invoked us.
                   1094: #      $replyfd- File descriptor connected to the client
                   1095: #  Implicit Inputs:
                   1096: #      $currenthostid - Global variable that carries the name of the host
                   1097: #                       known as.
                   1098: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
                   1099: #  Returns:
                   1100: #      1       - Ok to continue processing.
                   1101: #      0       - Program should exit.
                   1102: #  Side effects:
                   1103: #      Reply information is sent to the client.
                   1104: sub load_handler {
                   1105:     my ($cmd, $tail, $replyfd) = @_;
                   1106: 
                   1107:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1108:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1109: 
                   1110:     my $loadavg;
                   1111:     my $loadfile=IO::File->new('/proc/loadavg');
                   1112:    
                   1113:     $loadavg=<$loadfile>;
                   1114:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1115:    
                   1116:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1117: 
                   1118:     &Reply( $replyfd, "$loadpercent\n", "$cmd:$tail");
                   1119:    
                   1120:     return 1;
                   1121: }
1.263     albertel 1122: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1123: 
                   1124: #
                   1125: #   Process the userload request.  This sub returns to the client the current
                   1126: #  user load average.  It can be invoked either by clients or managers.
                   1127: #
                   1128: # Parameters:
                   1129: #      $cmd    - the actual keyword that invoked us.
                   1130: #      $tail   - the tail of the request that invoked us.
                   1131: #      $replyfd- File descriptor connected to the client
                   1132: #  Implicit Inputs:
                   1133: #      $currenthostid - Global variable that carries the name of the host
                   1134: #                       known as.
                   1135: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
                   1136: #  Returns:
                   1137: #      1       - Ok to continue processing.
                   1138: #      0       - Program should exit
                   1139: # Implicit inputs:
                   1140: #     whatever the userload() function requires.
                   1141: #  Implicit outputs:
                   1142: #     the reply is written to the client.
                   1143: #
                   1144: sub user_load_handler {
                   1145:     my ($cmd, $tail, $replyfd) = @_;
                   1146: 
                   1147:     my $userloadpercent=&userload();
                   1148:     &Reply($replyfd, "$userloadpercent\n", "$cmd:$tail");
                   1149:     
                   1150:     return 1;
                   1151: }
1.263     albertel 1152: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1153: 
1.218     foxr     1154: #   Process a request for the authorization type of a user:
                   1155: #   (userauth).
                   1156: #
                   1157: # Parameters:
                   1158: #      $cmd    - the actual keyword that invoked us.
                   1159: #      $tail   - the tail of the request that invoked us.
                   1160: #      $replyfd- File descriptor connected to the client
                   1161: #  Returns:
                   1162: #      1       - Ok to continue processing.
                   1163: #      0       - Program should exit
                   1164: # Implicit outputs:
                   1165: #    The user authorization type is written to the client.
                   1166: #
                   1167: sub user_authorization_type {
                   1168:     my ($cmd, $tail, $replyfd) = @_;
                   1169:    
                   1170:     my $userinput = "$cmd:$tail";
                   1171:    
                   1172:     #  Pull the domain and username out of the command tail.
1.222     foxr     1173:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1174:    
                   1175:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1176:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1177:     if($result eq "nouser") {
                   1178: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1179:     } else {
                   1180: 	#
1.222     foxr     1181: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1182: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1183: 	# password for internals e.g.
                   1184: 	#
                   1185: 	my ($type,$otherinfo) = split(/:/,$result);
                   1186: 	if($type =~ /^krb/) {
                   1187: 	    $type = $result;
1.269     raeburn  1188: 	} else {
                   1189:             $type .= ':';
                   1190:         }
                   1191: 	&Reply( $replyfd, "$type\n", $userinput);
1.218     foxr     1192:     }
                   1193:   
                   1194:     return 1;
                   1195: }
                   1196: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1197: 
                   1198: #   Process a request by a manager to push a hosts or domain table 
                   1199: #   to us.  We pick apart the command and pass it on to the subs
                   1200: #   that already exist to do this.
                   1201: #
                   1202: # Parameters:
                   1203: #      $cmd    - the actual keyword that invoked us.
                   1204: #      $tail   - the tail of the request that invoked us.
                   1205: #      $client - File descriptor connected to the client
                   1206: #  Returns:
                   1207: #      1       - Ok to continue processing.
                   1208: #      0       - Program should exit
                   1209: # Implicit Output:
                   1210: #    a reply is written to the client.
                   1211: sub push_file_handler {
                   1212:     my ($cmd, $tail, $client) = @_;
                   1213: 
                   1214:     my $userinput = "$cmd:$tail";
                   1215: 
                   1216:     # At this time we only know that the IP of our partner is a valid manager
                   1217:     # the code below is a hook to do further authentication (e.g. to resolve
                   1218:     # spoofing).
                   1219: 
                   1220:     my $cert = &GetCertificate($userinput);
                   1221:     if(&ValidManager($cert)) { 
                   1222: 
                   1223: 	# Now presumably we have the bona fides of both the peer host and the
                   1224: 	# process making the request.
                   1225:       
                   1226: 	my $reply = &PushFile($userinput);
                   1227: 	&Reply($client, "$reply\n", $userinput);
                   1228: 
                   1229:     } else {
                   1230: 	&Failure( $client, "refused\n", $userinput);
                   1231:     } 
1.219     foxr     1232:     return 1;
1.218     foxr     1233: }
                   1234: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1235: 
1.243     banghart 1236: #
                   1237: #   du  - list the disk usuage of a directory recursively. 
                   1238: #    
                   1239: #   note: stolen code from the ls file handler
                   1240: #   under construction by Rick Banghart 
                   1241: #    .
                   1242: # Parameters:
                   1243: #    $cmd        - The command that dispatched us (du).
                   1244: #    $ududir     - The directory path to list... I'm not sure what this
                   1245: #                  is relative as things like ls:. return e.g.
                   1246: #                  no_such_dir.
                   1247: #    $client     - Socket open on the client.
                   1248: # Returns:
                   1249: #     1 - indicating that the daemon should not disconnect.
                   1250: # Side Effects:
                   1251: #   The reply is written to  $client.
                   1252: #
                   1253: sub du_handler {
                   1254:     my ($cmd, $ududir, $client) = @_;
1.251     foxr     1255:     my ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
                   1256:     my $userinput = "$cmd:$ududir";
                   1257: 
1.245     albertel 1258:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1259: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1260: 	return 1;
                   1261:     }
1.249     foxr     1262:     #  Since $ududir could have some nasties in it,
                   1263:     #  we will require that ududir is a valid
                   1264:     #  directory.  Just in case someone tries to
                   1265:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1266:     #  etc.
                   1267:     #
                   1268:     if (-d $ududir) {
1.292     albertel 1269: 	my $total_size=0;
                   1270: 	my $code=sub { 
                   1271: 	    if ($_=~/\.\d+\./) { return;} 
                   1272: 	    if ($_=~/\.meta$/) { return;}
                   1273: 	    $total_size+=(stat($_))[7];
                   1274: 	};
1.295     raeburn  1275: 	chdir($ududir);
1.292     albertel 1276: 	find($code,$ududir);
                   1277: 	$total_size=int($total_size/1024);
                   1278: 	&Reply($client,"$total_size\n","$cmd:$ududir");
1.249     foxr     1279:     } else {
1.251     foxr     1280: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1281:     }
1.243     banghart 1282:     return 1;
                   1283: }
                   1284: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1285: 
1.239     foxr     1286: #
1.280     matthew  1287: # The ls_handler routine should be considered obosolete and is retained
                   1288: # for communication with legacy servers.  Please see the ls2_handler.
                   1289: #
1.239     foxr     1290: #   ls  - list the contents of a directory.  For each file in the
                   1291: #    selected directory the filename followed by the full output of
                   1292: #    the stat function is returned.  The returned info for each
                   1293: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1294: # Parameters:
                   1295: #    $cmd        - The command that dispatched us (ls).
                   1296: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1297: #                  is relative as things like ls:. return e.g.
                   1298: #                  no_such_dir.
                   1299: #    $client     - Socket open on the client.
                   1300: # Returns:
                   1301: #     1 - indicating that the daemon should not disconnect.
                   1302: # Side Effects:
                   1303: #   The reply is written to  $client.
                   1304: #
                   1305: sub ls_handler {
1.280     matthew  1306:     # obsoleted by ls2_handler
1.239     foxr     1307:     my ($cmd, $ulsdir, $client) = @_;
                   1308: 
                   1309:     my $userinput = "$cmd:$ulsdir";
                   1310: 
                   1311:     my $obs;
                   1312:     my $rights;
                   1313:     my $ulsout='';
                   1314:     my $ulsfn;
                   1315:     if (-e $ulsdir) {
                   1316: 	if(-d $ulsdir) {
                   1317: 	    if (opendir(LSDIR,$ulsdir)) {
                   1318: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1319: 		    undef($obs);
                   1320: 		    undef($rights); 
1.239     foxr     1321: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1322: 		    #We do some obsolete checking here
                   1323: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1324: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1325: 			my @obsolete=<FILE>;
                   1326: 			foreach my $obsolete (@obsolete) {
1.301     www      1327: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1328: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1329: 			}
                   1330: 		    }
                   1331: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1332: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1333: 		    else { $ulsout.="&0"; }
                   1334: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1335: 		    else { $ulsout.="&0:"; }
                   1336: 		}
                   1337: 		closedir(LSDIR);
                   1338: 	    }
                   1339: 	} else {
                   1340: 	    my @ulsstats=stat($ulsdir);
                   1341: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1342: 	}
                   1343:     } else {
                   1344: 	$ulsout='no_such_dir';
                   1345:     }
                   1346:     if ($ulsout eq '') { $ulsout='empty'; }
1.249     foxr     1347:     &Reply($client, "$ulsout\n", $userinput); # This supports debug logging.
1.239     foxr     1348:     
                   1349:     return 1;
                   1350: 
                   1351: }
                   1352: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1353: 
1.280     matthew  1354: #
                   1355: # Please also see the ls_handler, which this routine obosolets.
                   1356: # ls2_handler differs from ls_handler in that it escapes its return 
                   1357: # values before concatenating them together with ':'s.
                   1358: #
                   1359: #   ls2  - list the contents of a directory.  For each file in the
                   1360: #    selected directory the filename followed by the full output of
                   1361: #    the stat function is returned.  The returned info for each
                   1362: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1363: # Parameters:
                   1364: #    $cmd        - The command that dispatched us (ls).
                   1365: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1366: #                  is relative as things like ls:. return e.g.
                   1367: #                  no_such_dir.
                   1368: #    $client     - Socket open on the client.
                   1369: # Returns:
                   1370: #     1 - indicating that the daemon should not disconnect.
                   1371: # Side Effects:
                   1372: #   The reply is written to  $client.
                   1373: #
                   1374: sub ls2_handler {
                   1375:     my ($cmd, $ulsdir, $client) = @_;
                   1376: 
                   1377:     my $userinput = "$cmd:$ulsdir";
                   1378: 
                   1379:     my $obs;
                   1380:     my $rights;
                   1381:     my $ulsout='';
                   1382:     my $ulsfn;
                   1383:     if (-e $ulsdir) {
                   1384:         if(-d $ulsdir) {
                   1385:             if (opendir(LSDIR,$ulsdir)) {
                   1386:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1387:                     undef($obs);
                   1388: 		    undef($rights); 
1.280     matthew  1389:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1390:                     #We do some obsolete checking here
                   1391:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1392:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1393:                         my @obsolete=<FILE>;
                   1394:                         foreach my $obsolete (@obsolete) {
1.301     www      1395:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1396:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1397:                                 $rights = 1;
                   1398:                             }
                   1399:                         }
                   1400:                     }
                   1401:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1402:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1403:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1404:                     $ulsout.= &escape($tmp).':';
                   1405:                 }
                   1406:                 closedir(LSDIR);
                   1407:             }
                   1408:         } else {
                   1409:             my @ulsstats=stat($ulsdir);
                   1410:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1411:         }
                   1412:     } else {
                   1413:         $ulsout='no_such_dir';
                   1414:    }
                   1415:    if ($ulsout eq '') { $ulsout='empty'; }
                   1416:    &Reply($client, "$ulsout\n", $userinput); # This supports debug logging.
                   1417:    return 1;
                   1418: }
                   1419: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
                   1420: 
1.218     foxr     1421: #   Process a reinit request.  Reinit requests that either
                   1422: #   lonc or lond be reinitialized so that an updated 
                   1423: #   host.tab or domain.tab can be processed.
                   1424: #
                   1425: # Parameters:
                   1426: #      $cmd    - the actual keyword that invoked us.
                   1427: #      $tail   - the tail of the request that invoked us.
                   1428: #      $client - File descriptor connected to the client
                   1429: #  Returns:
                   1430: #      1       - Ok to continue processing.
                   1431: #      0       - Program should exit
                   1432: #  Implicit output:
                   1433: #     a reply is sent to the client.
                   1434: #
                   1435: sub reinit_process_handler {
                   1436:     my ($cmd, $tail, $client) = @_;
                   1437:    
                   1438:     my $userinput = "$cmd:$tail";
                   1439:    
                   1440:     my $cert = &GetCertificate($userinput);
                   1441:     if(&ValidManager($cert)) {
                   1442: 	chomp($userinput);
                   1443: 	my $reply = &ReinitProcess($userinput);
                   1444: 	&Reply( $client,  "$reply\n", $userinput);
                   1445:     } else {
                   1446: 	&Failure( $client, "refused\n", $userinput);
                   1447:     }
                   1448:     return 1;
                   1449: }
                   1450: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   1451: 
                   1452: #  Process the editing script for a table edit operation.
                   1453: #  the editing operation must be encrypted and requested by
                   1454: #  a manager host.
                   1455: #
                   1456: # Parameters:
                   1457: #      $cmd    - the actual keyword that invoked us.
                   1458: #      $tail   - the tail of the request that invoked us.
                   1459: #      $client - File descriptor connected to the client
                   1460: #  Returns:
                   1461: #      1       - Ok to continue processing.
                   1462: #      0       - Program should exit
                   1463: #  Implicit output:
                   1464: #     a reply is sent to the client.
                   1465: #
                   1466: sub edit_table_handler {
                   1467:     my ($command, $tail, $client) = @_;
                   1468:    
                   1469:     my $userinput = "$command:$tail";
                   1470: 
                   1471:     my $cert = &GetCertificate($userinput);
                   1472:     if(&ValidManager($cert)) {
                   1473: 	my($filetype, $script) = split(/:/, $tail);
                   1474: 	if (($filetype eq "hosts") || 
                   1475: 	    ($filetype eq "domain")) {
                   1476: 	    if($script ne "") {
                   1477: 		&Reply($client,              # BUGBUG - EditFile
                   1478: 		      &EditFile($userinput), #   could fail.
                   1479: 		      $userinput);
                   1480: 	    } else {
                   1481: 		&Failure($client,"refused\n",$userinput);
                   1482: 	    }
                   1483: 	} else {
                   1484: 	    &Failure($client,"refused\n",$userinput);
                   1485: 	}
                   1486:     } else {
                   1487: 	&Failure($client,"refused\n",$userinput);
                   1488:     }
                   1489:     return 1;
                   1490: }
1.263     albertel 1491: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     1492: 
1.220     foxr     1493: #
                   1494: #   Authenticate a user against the LonCAPA authentication
                   1495: #   database.  Note that there are several authentication
                   1496: #   possibilities:
                   1497: #   - unix     - The user can be authenticated against the unix
                   1498: #                password file.
                   1499: #   - internal - The user can be authenticated against a purely 
                   1500: #                internal per user password file.
                   1501: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   1502: #                ticket granting authority.
                   1503: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   1504: #                mechanism that is per system.
                   1505: #
                   1506: # Parameters:
                   1507: #    $cmd      - The command that got us here.
                   1508: #    $tail     - Tail of the command (remaining parameters).
                   1509: #    $client   - File descriptor connected to client.
                   1510: # Returns
                   1511: #     0        - Requested to exit, caller should shut down.
                   1512: #     1        - Continue processing.
                   1513: # Implicit inputs:
                   1514: #    The authentication systems describe above have their own forms of implicit
                   1515: #    input into the authentication process that are described above.
                   1516: #
                   1517: sub authenticate_handler {
                   1518:     my ($cmd, $tail, $client) = @_;
                   1519: 
                   1520:     
                   1521:     #  Regenerate the full input line 
                   1522:     
                   1523:     my $userinput  = $cmd.":".$tail;
                   1524:     
                   1525:     #  udom    - User's domain.
                   1526:     #  uname   - Username.
                   1527:     #  upass   - User's password.
                   1528:     
                   1529:     my ($udom,$uname,$upass)=split(/:/,$tail);
                   1530:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass");
                   1531:     chomp($upass);
                   1532:     $upass=&unescape($upass);
                   1533: 
                   1534:     my $pwdcorrect = &validate_user($udom, $uname, $upass);
                   1535:     if($pwdcorrect) {
                   1536: 	&Reply( $client, "authorized\n", $userinput);
                   1537: 	#
                   1538: 	#  Bad credentials: Failed to authorize
                   1539: 	#
                   1540:     } else {
                   1541: 	&Failure( $client, "non_authorized\n", $userinput);
                   1542:     }
                   1543: 
                   1544:     return 1;
                   1545: }
1.263     albertel 1546: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     1547: 
1.222     foxr     1548: #
                   1549: #   Change a user's password.  Note that this function is complicated by
                   1550: #   the fact that a user may be authenticated in more than one way:
                   1551: #   At present, we are not able to change the password for all types of
                   1552: #   authentication methods.  Only for:
                   1553: #      unix    - unix password or shadow passoword style authentication.
                   1554: #      local   - Locally written authentication mechanism.
                   1555: #   For now, kerb4 and kerb5 password changes are not supported and result
                   1556: #   in an error.
                   1557: # FUTURE WORK:
                   1558: #    Support kerberos passwd changes?
                   1559: # Parameters:
                   1560: #    $cmd      - The command that got us here.
                   1561: #    $tail     - Tail of the command (remaining parameters).
                   1562: #    $client   - File descriptor connected to client.
                   1563: # Returns
                   1564: #     0        - Requested to exit, caller should shut down.
                   1565: #     1        - Continue processing.
                   1566: # Implicit inputs:
                   1567: #    The authentication systems describe above have their own forms of implicit
                   1568: #    input into the authentication process that are described above.
                   1569: sub change_password_handler {
                   1570:     my ($cmd, $tail, $client) = @_;
                   1571: 
                   1572:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   1573: 
                   1574:     #
                   1575:     #  udom  - user's domain.
                   1576:     #  uname - Username.
                   1577:     #  upass - Current password.
                   1578:     #  npass - New password.
                   1579:    
                   1580:     my ($udom,$uname,$upass,$npass)=split(/:/,$tail);
                   1581: 
                   1582:     $upass=&unescape($upass);
                   1583:     $npass=&unescape($npass);
                   1584:     &Debug("Trying to change password for $uname");
                   1585: 
                   1586:     # First require that the user can be authenticated with their
                   1587:     # old password:
                   1588: 
                   1589:     my $validated = &validate_user($udom, $uname, $upass);
                   1590:     if($validated) {
                   1591: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   1592: 	
                   1593: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   1594: 	if ($howpwd eq 'internal') {
                   1595: 	    &Debug("internal auth");
                   1596: 	    my $salt=time;
                   1597: 	    $salt=substr($salt,6,2);
                   1598: 	    my $ncpass=crypt($npass,$salt);
                   1599: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
                   1600: 		&logthis("Result of password change for "
                   1601: 			 ."$uname: pwchange_success");
                   1602: 		&Reply($client, "ok\n", $userinput);
                   1603: 	    } else {
                   1604: 		&logthis("Unable to open $uname passwd "               
                   1605: 			 ."to change password");
                   1606: 		&Failure( $client, "non_authorized\n",$userinput);
                   1607: 	    }
                   1608: 	} elsif ($howpwd eq 'unix') {
1.287     foxr     1609: 	    my $result = &change_unix_password($uname, $npass);
1.222     foxr     1610: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     1611: 		     $result);
1.222     foxr     1612: 	    &Reply($client, "$result\n", $userinput);
                   1613: 	} else {
                   1614: 	    # this just means that the current password mode is not
                   1615: 	    # one we know how to change (e.g the kerberos auth modes or
                   1616: 	    # locally written auth handler).
                   1617: 	    #
                   1618: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   1619: 	}  
                   1620: 	
1.224     foxr     1621:     } else {
1.222     foxr     1622: 	&Failure( $client, "non_authorized\n", $userinput);
                   1623:     }
                   1624: 
                   1625:     return 1;
                   1626: }
1.263     albertel 1627: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     1628: 
1.225     foxr     1629: #
                   1630: #   Create a new user.  User in this case means a lon-capa user.
                   1631: #   The user must either already exist in some authentication realm
                   1632: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   1633: #   this loncapa system is created.
                   1634: #
                   1635: # Parameters:
                   1636: #    $cmd      - The command that got us here.
                   1637: #    $tail     - Tail of the command (remaining parameters).
                   1638: #    $client   - File descriptor connected to client.
                   1639: # Returns
                   1640: #     0        - Requested to exit, caller should shut down.
                   1641: #     1        - Continue processing.
                   1642: # Implicit inputs:
                   1643: #    The authentication systems describe above have their own forms of implicit
                   1644: #    input into the authentication process that are described above.
                   1645: sub add_user_handler {
                   1646: 
                   1647:     my ($cmd, $tail, $client) = @_;
                   1648: 
                   1649: 
                   1650:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   1651:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   1652: 
                   1653:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   1654: 
                   1655: 
                   1656:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   1657: 	
                   1658: 	my $oldumask=umask(0077);
                   1659: 	chomp($npass);
                   1660: 	$npass=&unescape($npass);
                   1661: 	my $passfilename  = &password_path($udom, $uname);
                   1662: 	&Debug("Password file created will be:".$passfilename);
                   1663: 	if (-e $passfilename) {
                   1664: 	    &Failure( $client, "already_exists\n", $userinput);
                   1665: 	} else {
                   1666: 	    my $fperror='';
1.264     albertel 1667: 	    if (!&mkpath($passfilename)) {
                   1668: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   1669: 		    ."makeuser";
1.225     foxr     1670: 	    }
                   1671: 	    unless ($fperror) {
                   1672: 		my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
                   1673: 		&Reply($client, $result, $userinput);     #BUGBUG - could be fail
                   1674: 	    } else {
                   1675: 		&Failure($client, "$fperror\n", $userinput);
                   1676: 	    }
                   1677: 	}
                   1678: 	umask($oldumask);
                   1679:     }  else {
                   1680: 	&Failure($client, "not_right_domain\n",
                   1681: 		$userinput);	# Even if we are multihomed.
                   1682:     
                   1683:     }
                   1684:     return 1;
                   1685: 
                   1686: }
                   1687: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   1688: 
                   1689: #
                   1690: #   Change the authentication method of a user.  Note that this may
                   1691: #   also implicitly change the user's password if, for example, the user is
                   1692: #   joining an existing authentication realm.  Known authentication realms at
                   1693: #   this time are:
                   1694: #    internal   - Purely internal password file (only loncapa knows this user)
                   1695: #    local      - Institutionally written authentication module.
                   1696: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   1697: #    kerb4      - kerberos version 4
                   1698: #    kerb5      - kerberos version 5
                   1699: #
                   1700: # Parameters:
                   1701: #    $cmd      - The command that got us here.
                   1702: #    $tail     - Tail of the command (remaining parameters).
                   1703: #    $client   - File descriptor connected to client.
                   1704: # Returns
                   1705: #     0        - Requested to exit, caller should shut down.
                   1706: #     1        - Continue processing.
                   1707: # Implicit inputs:
                   1708: #    The authentication systems describe above have their own forms of implicit
                   1709: #    input into the authentication process that are described above.
1.287     foxr     1710: # NOTE:
                   1711: #   This is also used to change the authentication credential values (e.g. passwd).
                   1712: #   
1.225     foxr     1713: #
                   1714: sub change_authentication_handler {
                   1715: 
                   1716:     my ($cmd, $tail, $client) = @_;
                   1717:    
                   1718:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   1719: 
                   1720:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   1721:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   1722:     if ($udom ne $currentdomainid) {
                   1723: 	&Failure( $client, "not_right_domain\n", $client);
                   1724:     } else {
                   1725: 	
                   1726: 	chomp($npass);
                   1727: 	
                   1728: 	$npass=&unescape($npass);
1.261     foxr     1729: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     1730: 	my $passfilename = &password_path($udom, $uname);
                   1731: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     1732: 	    # If just changing the unix passwd. need to arrange to run
                   1733: 	    # passwd since otherwise make_passwd_file will run
                   1734: 	    # lcuseradd which fails if an account already exists
                   1735: 	    # (to prevent an unscrupulous LONCAPA admin from stealing
                   1736: 	    # an existing account by overwriting it as a LonCAPA account).
                   1737: 
                   1738: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   1739: 		my $result = &change_unix_password($uname, $npass);
                   1740: 		&logthis("Result of password change for $uname: ".$result);
                   1741: 		if ($result eq "ok") {
                   1742: 		    &Reply($client, "$result\n")
1.288     albertel 1743: 		} else {
1.287     foxr     1744: 		    &Failure($client, "$result\n");
                   1745: 		}
1.288     albertel 1746: 	    } else {
1.287     foxr     1747: 		my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
                   1748: 		#
                   1749: 		#  If the current auth mode is internal, and the old auth mode was
                   1750: 		#  unix, or krb*,  and the user is an author for this domain,
                   1751: 		#  re-run manage_permissions for that role in order to be able
                   1752: 		#  to take ownership of the construction space back to www:www
                   1753: 		#
                   1754: 		
                   1755: 		
                   1756: 		if( (($oldauth =~ /^unix/) && ($umode eq "internal")) ||
                   1757: 		    (($oldauth =~ /^internal/) && ($umode eq "unix")) ) { 
                   1758: 		    if(&is_author($udom, $uname)) {
                   1759: 			&Debug(" Need to manage author permissions...");
                   1760: 			&manage_permissions("/$udom/_au", $udom, $uname, "$umode:");
                   1761: 		    }
1.261     foxr     1762: 		}
1.287     foxr     1763: 		&Reply($client, $result, $userinput);
1.261     foxr     1764: 	    }
                   1765: 	       
                   1766: 
1.225     foxr     1767: 	} else {	       
1.251     foxr     1768: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     1769: 	}
                   1770:     }
                   1771:     return 1;
                   1772: }
                   1773: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   1774: 
                   1775: #
                   1776: #   Determines if this is the home server for a user.  The home server
                   1777: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   1778: #   to do is determine if this file exists.
                   1779: #
                   1780: # Parameters:
                   1781: #    $cmd      - The command that got us here.
                   1782: #    $tail     - Tail of the command (remaining parameters).
                   1783: #    $client   - File descriptor connected to client.
                   1784: # Returns
                   1785: #     0        - Requested to exit, caller should shut down.
                   1786: #     1        - Continue processing.
                   1787: # Implicit inputs:
                   1788: #    The authentication systems describe above have their own forms of implicit
                   1789: #    input into the authentication process that are described above.
                   1790: #
                   1791: sub is_home_handler {
                   1792:     my ($cmd, $tail, $client) = @_;
                   1793:    
                   1794:     my $userinput  = "$cmd:$tail";
                   1795:    
                   1796:     my ($udom,$uname)=split(/:/,$tail);
                   1797:     chomp($uname);
                   1798:     my $passfile = &password_filename($udom, $uname);
                   1799:     if($passfile) {
                   1800: 	&Reply( $client, "found\n", $userinput);
                   1801:     } else {
                   1802: 	&Failure($client, "not_found\n", $userinput);
                   1803:     }
                   1804:     return 1;
                   1805: }
                   1806: &register_handler("home", \&is_home_handler, 0,1,0);
                   1807: 
                   1808: #
                   1809: #   Process an update request for a resource?? I think what's going on here is
                   1810: #   that a resource has been modified that we hold a subscription to.
                   1811: #   If the resource is not local, then we must update, or at least invalidate our
                   1812: #   cached copy of the resource. 
                   1813: #   FUTURE WORK:
                   1814: #      I need to look at this logic carefully.  My druthers would be to follow
                   1815: #      typical caching logic, and simple invalidate the cache, drop any subscription
                   1816: #      an let the next fetch start the ball rolling again... however that may
                   1817: #      actually be more difficult than it looks given the complex web of
                   1818: #      proxy servers.
                   1819: # Parameters:
                   1820: #    $cmd      - The command that got us here.
                   1821: #    $tail     - Tail of the command (remaining parameters).
                   1822: #    $client   - File descriptor connected to client.
                   1823: # Returns
                   1824: #     0        - Requested to exit, caller should shut down.
                   1825: #     1        - Continue processing.
                   1826: # Implicit inputs:
                   1827: #    The authentication systems describe above have their own forms of implicit
                   1828: #    input into the authentication process that are described above.
                   1829: #
                   1830: sub update_resource_handler {
                   1831: 
                   1832:     my ($cmd, $tail, $client) = @_;
                   1833:    
                   1834:     my $userinput = "$cmd:$tail";
                   1835:    
                   1836:     my $fname= $tail;		# This allows interactive testing
                   1837: 
                   1838: 
                   1839:     my $ownership=ishome($fname);
                   1840:     if ($ownership eq 'not_owner') {
                   1841: 	if (-e $fname) {
                   1842: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   1843: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   1844: 	    my $now=time;
                   1845: 	    my $since=$now-$atime;
                   1846: 	    if ($since>$perlvar{'lonExpire'}) {
                   1847: 		my $reply=&reply("unsub:$fname","$clientname");
1.308     albertel 1848: 		&devalidate_meta_cache($fname);
1.225     foxr     1849: 		unlink("$fname");
                   1850: 	    } else {
                   1851: 		my $transname="$fname.in.transfer";
                   1852: 		my $remoteurl=&reply("sub:$fname","$clientname");
                   1853: 		my $response;
                   1854: 		alarm(120);
                   1855: 		{
                   1856: 		    my $ua=new LWP::UserAgent;
                   1857: 		    my $request=new HTTP::Request('GET',"$remoteurl");
                   1858: 		    $response=$ua->request($request,$transname);
                   1859: 		}
                   1860: 		alarm(0);
                   1861: 		if ($response->is_error()) {
                   1862: 		    unlink($transname);
                   1863: 		    my $message=$response->status_line;
                   1864: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   1865: 		} else {
                   1866: 		    if ($remoteurl!~/\.meta$/) {
                   1867: 			alarm(120);
                   1868: 			{
                   1869: 			    my $ua=new LWP::UserAgent;
                   1870: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1871: 			    my $mresponse=$ua->request($mrequest,$fname.'.meta');
                   1872: 			    if ($mresponse->is_error()) {
                   1873: 				unlink($fname.'.meta');
                   1874: 			    }
                   1875: 			}
                   1876: 			alarm(0);
                   1877: 		    }
                   1878: 		    rename($transname,$fname);
1.308     albertel 1879: 		    &devalidate_meta_cache($fname);
1.225     foxr     1880: 		}
                   1881: 	    }
                   1882: 	    &Reply( $client, "ok\n", $userinput);
                   1883: 	} else {
                   1884: 	    &Failure($client, "not_found\n", $userinput);
                   1885: 	}
                   1886:     } else {
                   1887: 	&Failure($client, "rejected\n", $userinput);
                   1888:     }
                   1889:     return 1;
                   1890: }
                   1891: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   1892: 
1.308     albertel 1893: sub devalidate_meta_cache {
                   1894:     my ($url) = @_;
                   1895:     use Cache::Memcached;
                   1896:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
                   1897:     $url = &declutter($url);
                   1898:     $url =~ s-\.meta$--;
                   1899:     my $id = &escape('meta:'.$url);
                   1900:     $memcache->delete($id);
                   1901: }
                   1902: 
                   1903: sub declutter {
                   1904:     my $thisfn=shift;
                   1905:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   1906:     $thisfn=~s/^\///;
                   1907:     $thisfn=~s|^adm/wrapper/||;
                   1908:     $thisfn=~s|^adm/coursedocs/showdoc/||;
                   1909:     $thisfn=~s/^res\///;
                   1910:     $thisfn=~s/\?.+$//;
                   1911:     return $thisfn;
                   1912: }
1.225     foxr     1913: #
1.226     foxr     1914: #   Fetch a user file from a remote server to the user's home directory
                   1915: #   userfiles subdir.
1.225     foxr     1916: # Parameters:
                   1917: #    $cmd      - The command that got us here.
                   1918: #    $tail     - Tail of the command (remaining parameters).
                   1919: #    $client   - File descriptor connected to client.
                   1920: # Returns
                   1921: #     0        - Requested to exit, caller should shut down.
                   1922: #     1        - Continue processing.
                   1923: #
                   1924: sub fetch_user_file_handler {
                   1925: 
                   1926:     my ($cmd, $tail, $client) = @_;
                   1927: 
                   1928:     my $userinput = "$cmd:$tail";
                   1929:     my $fname           = $tail;
1.232     foxr     1930:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     1931:     my $udir=&propath($udom,$uname).'/userfiles';
                   1932:     unless (-e $udir) {
                   1933: 	mkdir($udir,0770); 
                   1934:     }
1.232     foxr     1935:     Debug("fetch user file for $fname");
1.225     foxr     1936:     if (-e $udir) {
                   1937: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     1938: 
                   1939: 	# IF necessary, create the path right down to the file.
                   1940: 	# Note that any regular files in the way of this path are
                   1941: 	# wiped out to deal with some earlier folly of mine.
                   1942: 
1.267     raeburn  1943: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 1944: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     1945: 	}
                   1946: 
1.225     foxr     1947: 	my $destname=$udir.'/'.$ufile;
                   1948: 	my $transname=$udir.'/'.$ufile.'.in.transit';
                   1949: 	my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
                   1950: 	my $response;
1.232     foxr     1951: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.225     foxr     1952: 	alarm(120);
                   1953: 	{
                   1954: 	    my $ua=new LWP::UserAgent;
                   1955: 	    my $request=new HTTP::Request('GET',"$remoteurl");
                   1956: 	    $response=$ua->request($request,$transname);
                   1957: 	}
                   1958: 	alarm(0);
                   1959: 	if ($response->is_error()) {
                   1960: 	    unlink($transname);
                   1961: 	    my $message=$response->status_line;
                   1962: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   1963: 	    &Failure($client, "failed\n", $userinput);
                   1964: 	} else {
1.232     foxr     1965: 	    Debug("Renaming $transname to $destname");
1.225     foxr     1966: 	    if (!rename($transname,$destname)) {
                   1967: 		&logthis("Unable to move $transname to $destname");
                   1968: 		unlink($transname);
                   1969: 		&Failure($client, "failed\n", $userinput);
                   1970: 	    } else {
                   1971: 		&Reply($client, "ok\n", $userinput);
                   1972: 	    }
                   1973: 	}   
                   1974:     } else {
                   1975: 	&Failure($client, "not_home\n", $userinput);
                   1976:     }
                   1977:     return 1;
                   1978: }
                   1979: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   1980: 
1.226     foxr     1981: #
                   1982: #   Remove a file from a user's home directory userfiles subdirectory.
                   1983: # Parameters:
                   1984: #    cmd   - the Lond request keyword that got us here.
                   1985: #    tail  - the part of the command past the keyword.
                   1986: #    client- File descriptor connected with the client.
                   1987: #
                   1988: # Returns:
                   1989: #    1    - Continue processing.
                   1990: sub remove_user_file_handler {
                   1991:     my ($cmd, $tail, $client) = @_;
                   1992: 
                   1993:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   1994: 
                   1995:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   1996:     if ($ufile =~m|/\.\./|) {
                   1997: 	# any files paths with /../ in them refuse 
                   1998: 	# to deal with
                   1999: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2000:     } else {
                   2001: 	my $udir = &propath($udom,$uname);
                   2002: 	if (-e $udir) {
                   2003: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2004: 	    if (-e $file) {
1.253     foxr     2005: 		#
                   2006: 		#   If the file is a regular file unlink is fine...
                   2007: 		#   However it's possible the client wants a dir.
                   2008: 		#   removed, in which case rmdir is more approprate:
                   2009: 		#
1.240     banghart 2010: 	        if (-f $file){
1.241     albertel 2011: 		    unlink($file);
                   2012: 		} elsif(-d $file) {
                   2013: 		    rmdir($file);
1.240     banghart 2014: 		}
1.226     foxr     2015: 		if (-e $file) {
1.253     foxr     2016: 		    #  File is still there after we deleted it ?!?
                   2017: 
1.226     foxr     2018: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2019: 		} else {
                   2020: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2021: 		}
                   2022: 	    } else {
                   2023: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2024: 	    }
                   2025: 	} else {
                   2026: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2027: 	}
                   2028:     }
                   2029:     return 1;
                   2030: }
                   2031: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2032: 
1.236     albertel 2033: #
                   2034: #   make a directory in a user's home directory userfiles subdirectory.
                   2035: # Parameters:
                   2036: #    cmd   - the Lond request keyword that got us here.
                   2037: #    tail  - the part of the command past the keyword.
                   2038: #    client- File descriptor connected with the client.
                   2039: #
                   2040: # Returns:
                   2041: #    1    - Continue processing.
                   2042: sub mkdir_user_file_handler {
                   2043:     my ($cmd, $tail, $client) = @_;
                   2044: 
                   2045:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2046:     $dir=&unescape($dir);
                   2047:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2048:     if ($ufile =~m|/\.\./|) {
                   2049: 	# any files paths with /../ in them refuse 
                   2050: 	# to deal with
                   2051: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2052:     } else {
                   2053: 	my $udir = &propath($udom,$uname);
                   2054: 	if (-e $udir) {
1.264     albertel 2055: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2056: 	    if (!&mkpath($newdir)) {
                   2057: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2058: 	    }
1.264     albertel 2059: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2060: 	} else {
                   2061: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2062: 	}
                   2063:     }
                   2064:     return 1;
                   2065: }
                   2066: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2067: 
1.237     albertel 2068: #
                   2069: #   rename a file in a user's home directory userfiles subdirectory.
                   2070: # Parameters:
                   2071: #    cmd   - the Lond request keyword that got us here.
                   2072: #    tail  - the part of the command past the keyword.
                   2073: #    client- File descriptor connected with the client.
                   2074: #
                   2075: # Returns:
                   2076: #    1    - Continue processing.
                   2077: sub rename_user_file_handler {
                   2078:     my ($cmd, $tail, $client) = @_;
                   2079: 
                   2080:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2081:     $old=&unescape($old);
                   2082:     $new=&unescape($new);
                   2083:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2084: 	# any files paths with /../ in them refuse to deal with
                   2085: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2086:     } else {
                   2087: 	my $udir = &propath($udom,$uname);
                   2088: 	if (-e $udir) {
                   2089: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2090: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2091: 	    if (-e $newfile) {
                   2092: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2093: 	    } elsif (! -e $oldfile) {
                   2094: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2095: 	    } else {
                   2096: 		if (!rename($oldfile,$newfile)) {
                   2097: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2098: 		} else {
                   2099: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2100: 		}
                   2101: 	    }
                   2102: 	} else {
                   2103: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2104: 	}
                   2105:     }
                   2106:     return 1;
                   2107: }
                   2108: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2109: 
1.227     foxr     2110: #
1.263     albertel 2111: #  Authenticate access to a user file by checking that the token the user's 
                   2112: #  passed also exists in their session file
1.227     foxr     2113: #
                   2114: # Parameters:
                   2115: #   cmd      - The request keyword that dispatched to tus.
                   2116: #   tail     - The tail of the request (colon separated parameters).
                   2117: #   client   - Filehandle open on the client.
                   2118: # Return:
                   2119: #    1.
                   2120: sub token_auth_user_file_handler {
                   2121:     my ($cmd, $tail, $client) = @_;
                   2122: 
                   2123:     my ($fname, $session) = split(/:/, $tail);
                   2124:     
                   2125:     chomp($session);
1.251     foxr     2126:     my $reply="non_auth\n";
1.227     foxr     2127:     if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
                   2128: 	     $session.'.id')) {
                   2129: 	while (my $line=<ENVIN>) {
1.330     albertel 2130: 	    my ($envname)=split(/=/,$line,2);
                   2131: 	    $envname=&unescape($envname);
                   2132: 	    if ($envname=~ m|^userfile\.\Q$fname\E|) { $reply="ok\n"; }
1.227     foxr     2133: 	}
                   2134: 	close(ENVIN);
1.251     foxr     2135: 	&Reply($client, $reply, "$cmd:$tail");
1.227     foxr     2136:     } else {
                   2137: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2138:     }
                   2139:     return 1;
                   2140: 
                   2141: }
                   2142: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2143: 
                   2144: #
                   2145: #   Unsubscribe from a resource.
                   2146: #
                   2147: # Parameters:
                   2148: #    $cmd      - The command that got us here.
                   2149: #    $tail     - Tail of the command (remaining parameters).
                   2150: #    $client   - File descriptor connected to client.
                   2151: # Returns
                   2152: #     0        - Requested to exit, caller should shut down.
                   2153: #     1        - Continue processing.
                   2154: #
                   2155: sub unsubscribe_handler {
                   2156:     my ($cmd, $tail, $client) = @_;
                   2157: 
                   2158:     my $userinput= "$cmd:$tail";
                   2159:     
                   2160:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   2161: 
                   2162:     &Debug("Unsubscribing $fname");
                   2163:     if (-e $fname) {
                   2164: 	&Debug("Exists");
                   2165: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   2166:     } else {
                   2167: 	&Failure($client, "not_found\n", $userinput);
                   2168:     }
                   2169:     return 1;
                   2170: }
                   2171: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 2172: 
1.230     foxr     2173: #   Subscribe to a resource
                   2174: #
                   2175: # Parameters:
                   2176: #    $cmd      - The command that got us here.
                   2177: #    $tail     - Tail of the command (remaining parameters).
                   2178: #    $client   - File descriptor connected to client.
                   2179: # Returns
                   2180: #     0        - Requested to exit, caller should shut down.
                   2181: #     1        - Continue processing.
                   2182: #
                   2183: sub subscribe_handler {
                   2184:     my ($cmd, $tail, $client)= @_;
                   2185: 
                   2186:     my $userinput  = "$cmd:$tail";
                   2187: 
                   2188:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   2189: 
                   2190:     return 1;
                   2191: }
                   2192: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   2193: 
                   2194: #
                   2195: #   Determine the version of a resource (?) Or is it return
                   2196: #   the top version of the resource?  Not yet clear from the
                   2197: #   code in currentversion.
                   2198: #
                   2199: # Parameters:
                   2200: #    $cmd      - The command that got us here.
                   2201: #    $tail     - Tail of the command (remaining parameters).
                   2202: #    $client   - File descriptor connected to client.
                   2203: # Returns
                   2204: #     0        - Requested to exit, caller should shut down.
                   2205: #     1        - Continue processing.
                   2206: #
                   2207: sub current_version_handler {
                   2208:     my ($cmd, $tail, $client) = @_;
                   2209: 
                   2210:     my $userinput= "$cmd:$tail";
                   2211:    
                   2212:     my $fname   = $tail;
                   2213:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   2214:     return 1;
                   2215: 
                   2216: }
                   2217: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   2218: 
                   2219: #  Make an entry in a user's activity log.
                   2220: #
                   2221: # Parameters:
                   2222: #    $cmd      - The command that got us here.
                   2223: #    $tail     - Tail of the command (remaining parameters).
                   2224: #    $client   - File descriptor connected to client.
                   2225: # Returns
                   2226: #     0        - Requested to exit, caller should shut down.
                   2227: #     1        - Continue processing.
                   2228: #
                   2229: sub activity_log_handler {
                   2230:     my ($cmd, $tail, $client) = @_;
                   2231: 
                   2232: 
                   2233:     my $userinput= "$cmd:$tail";
                   2234: 
                   2235:     my ($udom,$uname,$what)=split(/:/,$tail);
                   2236:     chomp($what);
                   2237:     my $proname=&propath($udom,$uname);
                   2238:     my $now=time;
                   2239:     my $hfh;
                   2240:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   2241: 	print $hfh "$now:$clientname:$what\n";
                   2242: 	&Reply( $client, "ok\n", $userinput); 
                   2243:     } else {
                   2244: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   2245: 		 ."while attempting log\n", 
                   2246: 		 $userinput);
                   2247:     }
                   2248: 
                   2249:     return 1;
                   2250: }
1.263     albertel 2251: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     2252: 
                   2253: #
                   2254: #   Put a namespace entry in a user profile hash.
                   2255: #   My druthers would be for this to be an encrypted interaction too.
                   2256: #   anything that might be an inadvertent covert channel about either
                   2257: #   user authentication or user personal information....
                   2258: #
                   2259: # Parameters:
                   2260: #    $cmd      - The command that got us here.
                   2261: #    $tail     - Tail of the command (remaining parameters).
                   2262: #    $client   - File descriptor connected to client.
                   2263: # Returns
                   2264: #     0        - Requested to exit, caller should shut down.
                   2265: #     1        - Continue processing.
                   2266: #
                   2267: sub put_user_profile_entry {
                   2268:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     2269: 
1.230     foxr     2270:     my $userinput = "$cmd:$tail";
                   2271:     
1.242     raeburn  2272:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     2273:     if ($namespace ne 'roles') {
                   2274: 	chomp($what);
                   2275: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2276: 				  &GDBM_WRCREAT(),"P",$what);
                   2277: 	if($hashref) {
                   2278: 	    my @pairs=split(/\&/,$what);
                   2279: 	    foreach my $pair (@pairs) {
                   2280: 		my ($key,$value)=split(/=/,$pair);
                   2281: 		$hashref->{$key}=$value;
                   2282: 	    }
1.311     albertel 2283: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     2284: 		&Reply( $client, "ok\n", $userinput);
                   2285: 	    } else {
                   2286: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2287: 			"while attempting put\n", 
                   2288: 			$userinput);
                   2289: 	    }
                   2290: 	} else {
1.316     albertel 2291: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     2292: 		     "while attempting put\n", $userinput);
                   2293: 	}
                   2294:     } else {
                   2295:         &Failure( $client, "refused\n", $userinput);
                   2296:     }
                   2297:     
                   2298:     return 1;
                   2299: }
                   2300: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   2301: 
1.283     albertel 2302: #   Put a piece of new data in hash, returns error if entry already exists
                   2303: # Parameters:
                   2304: #    $cmd      - The command that got us here.
                   2305: #    $tail     - Tail of the command (remaining parameters).
                   2306: #    $client   - File descriptor connected to client.
                   2307: # Returns
                   2308: #     0        - Requested to exit, caller should shut down.
                   2309: #     1        - Continue processing.
                   2310: #
                   2311: sub newput_user_profile_entry {
                   2312:     my ($cmd, $tail, $client)  = @_;
                   2313: 
                   2314:     my $userinput = "$cmd:$tail";
                   2315: 
                   2316:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   2317:     if ($namespace eq 'roles') {
                   2318:         &Failure( $client, "refused\n", $userinput);
                   2319: 	return 1;
                   2320:     }
                   2321: 
                   2322:     chomp($what);
                   2323: 
                   2324:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2325: 				 &GDBM_WRCREAT(),"N",$what);
                   2326:     if(!$hashref) {
1.316     albertel 2327: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 2328: 		  "while attempting put\n", $userinput);
                   2329: 	return 1;
                   2330:     }
                   2331: 
                   2332:     my @pairs=split(/\&/,$what);
                   2333:     foreach my $pair (@pairs) {
                   2334: 	my ($key,$value)=split(/=/,$pair);
                   2335: 	if (exists($hashref->{$key})) {
                   2336: 	    &Failure($client, "key_exists: ".$key."\n",$userinput);
                   2337: 	    return 1;
                   2338: 	}
                   2339:     }
                   2340: 
                   2341:     foreach my $pair (@pairs) {
                   2342: 	my ($key,$value)=split(/=/,$pair);
                   2343: 	$hashref->{$key}=$value;
                   2344:     }
                   2345: 
1.311     albertel 2346:     if (&untie_user_hash($hashref)) {
1.283     albertel 2347: 	&Reply( $client, "ok\n", $userinput);
                   2348:     } else {
                   2349: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2350: 		 "while attempting put\n", 
                   2351: 		 $userinput);
                   2352:     }
                   2353:     return 1;
                   2354: }
                   2355: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   2356: 
1.230     foxr     2357: # 
                   2358: #   Increment a profile entry in the user history file.
                   2359: #   The history contains keyword value pairs.  In this case,
                   2360: #   The value itself is a pair of numbers.  The first, the current value
                   2361: #   the second an increment that this function applies to the current
                   2362: #   value.
                   2363: #
                   2364: # Parameters:
                   2365: #    $cmd      - The command that got us here.
                   2366: #    $tail     - Tail of the command (remaining parameters).
                   2367: #    $client   - File descriptor connected to client.
                   2368: # Returns
                   2369: #     0        - Requested to exit, caller should shut down.
                   2370: #     1        - Continue processing.
                   2371: #
                   2372: sub increment_user_value_handler {
                   2373:     my ($cmd, $tail, $client) = @_;
                   2374:     
                   2375:     my $userinput   = "$cmd:$tail";
                   2376:     
                   2377:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   2378:     if ($namespace ne 'roles') {
                   2379:         chomp($what);
                   2380: 	my $hashref = &tie_user_hash($udom, $uname,
                   2381: 				     $namespace, &GDBM_WRCREAT(),
                   2382: 				     "P",$what);
                   2383: 	if ($hashref) {
                   2384: 	    my @pairs=split(/\&/,$what);
                   2385: 	    foreach my $pair (@pairs) {
                   2386: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  2387:                 $value = &unescape($value);
1.230     foxr     2388: 		# We could check that we have a number...
                   2389: 		if (! defined($value) || $value eq '') {
                   2390: 		    $value = 1;
                   2391: 		}
                   2392: 		$hashref->{$key}+=$value;
1.284     raeburn  2393:                 if ($namespace eq 'nohist_resourcetracker') {
                   2394:                     if ($hashref->{$key} < 0) {
                   2395:                         $hashref->{$key} = 0;
                   2396:                     }
                   2397:                 }
1.230     foxr     2398: 	    }
1.311     albertel 2399: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     2400: 		&Reply( $client, "ok\n", $userinput);
                   2401: 	    } else {
                   2402: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2403: 			 "while attempting inc\n", $userinput);
                   2404: 	    }
                   2405: 	} else {
                   2406: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2407: 		     "while attempting inc\n", $userinput);
                   2408: 	}
                   2409:     } else {
                   2410: 	&Failure($client, "refused\n", $userinput);
                   2411:     }
                   2412:     
                   2413:     return 1;
                   2414: }
                   2415: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   2416: 
                   2417: #
                   2418: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   2419: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   2420: #   for a person grants the permissions packaged with that role
                   2421: #   to that user when the role is selected.
                   2422: #
                   2423: # Parameters:
                   2424: #    $cmd       - The command string (rolesput).
                   2425: #    $tail      - The remainder of the request line.  For rolesput this
                   2426: #                 consists of a colon separated list that contains:
                   2427: #                 The domain and user that is granting the role (logged).
                   2428: #                 The domain and user that is getting the role.
                   2429: #                 The roles being granted as a set of & separated pairs.
                   2430: #                 each pair a key value pair.
                   2431: #    $client    - File descriptor connected to the client.
                   2432: # Returns:
                   2433: #     0         - If the daemon should exit
                   2434: #     1         - To continue processing.
                   2435: #
                   2436: #
                   2437: sub roles_put_handler {
                   2438:     my ($cmd, $tail, $client) = @_;
                   2439: 
                   2440:     my $userinput  = "$cmd:$tail";
                   2441: 
                   2442:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   2443:     
                   2444: 
                   2445:     my $namespace='roles';
                   2446:     chomp($what);
                   2447:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2448: 				 &GDBM_WRCREAT(), "P",
                   2449: 				 "$exedom:$exeuser:$what");
                   2450:     #
                   2451:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   2452:     #  handle is open for the minimal amount of time.  Since the flush
                   2453:     #  is done on close this improves the chances the log will be an un-
                   2454:     #  corrupted ordered thing.
                   2455:     if ($hashref) {
1.261     foxr     2456: 	my $pass_entry = &get_auth_type($udom, $uname);
                   2457: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   2458: 	$auth_type = $auth_type.":";
1.230     foxr     2459: 	my @pairs=split(/\&/,$what);
                   2460: 	foreach my $pair (@pairs) {
                   2461: 	    my ($key,$value)=split(/=/,$pair);
                   2462: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     2463: 			       $auth_type);
1.230     foxr     2464: 	    $hashref->{$key}=$value;
                   2465: 	}
1.311     albertel 2466: 	if (&untie_user_hash($hashref)) {
1.230     foxr     2467: 	    &Reply($client, "ok\n", $userinput);
                   2468: 	} else {
                   2469: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2470: 		     "while attempting rolesput\n", $userinput);
                   2471: 	}
                   2472:     } else {
                   2473: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2474: 		 "while attempting rolesput\n", $userinput);
                   2475:     }
                   2476:     return 1;
                   2477: }
                   2478: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   2479: 
                   2480: #
1.231     foxr     2481: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   2482: #  a permissions package associated with the role from the user's profile.
                   2483: #
                   2484: # Parameters:
                   2485: #     $cmd                 - The command (rolesdel)
                   2486: #     $tail                - The remainder of the request line. This consists
                   2487: #                             of:
                   2488: #                             The domain and user requesting the change (logged)
                   2489: #                             The domain and user being changed.
                   2490: #                             The roles being revoked.  These are shipped to us
                   2491: #                             as a bunch of & separated role name keywords.
                   2492: #     $client              - The file handle open on the client.
                   2493: # Returns:
                   2494: #     1                    - Continue processing
                   2495: #     0                    - Exit.
                   2496: #
                   2497: sub roles_delete_handler {
                   2498:     my ($cmd, $tail, $client)  = @_;
                   2499: 
                   2500:     my $userinput    = "$cmd:$tail";
                   2501:    
                   2502:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   2503:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   2504: 	   "what = ".$what);
                   2505:     my $namespace='roles';
                   2506:     chomp($what);
                   2507:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2508: 				 &GDBM_WRCREAT(), "D",
                   2509: 				 "$exedom:$exeuser:$what");
                   2510:     
                   2511:     if ($hashref) {
                   2512: 	my @rolekeys=split(/\&/,$what);
                   2513: 	
                   2514: 	foreach my $key (@rolekeys) {
                   2515: 	    delete $hashref->{$key};
                   2516: 	}
1.315     albertel 2517: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2518: 	    &Reply($client, "ok\n", $userinput);
                   2519: 	} else {
                   2520: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2521: 		     "while attempting rolesdel\n", $userinput);
                   2522: 	}
                   2523:     } else {
                   2524:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2525: 		 "while attempting rolesdel\n", $userinput);
                   2526:     }
                   2527:     
                   2528:     return 1;
                   2529: }
                   2530: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   2531: 
                   2532: # Unencrypted get from a user's profile database.  See 
                   2533: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   2534: # This function retrieves a keyed item from a specific named database in the
                   2535: # user's directory.
                   2536: #
                   2537: # Parameters:
                   2538: #   $cmd             - Command request keyword (get).
                   2539: #   $tail            - Tail of the command.  This is a colon separated list
                   2540: #                      consisting of the domain and username that uniquely
                   2541: #                      identifies the profile,
                   2542: #                      The 'namespace' which selects the gdbm file to 
                   2543: #                      do the lookup in, 
                   2544: #                      & separated list of keys to lookup.  Note that
                   2545: #                      the values are returned as an & separated list too.
                   2546: #   $client          - File descriptor open on the client.
                   2547: # Returns:
                   2548: #   1       - Continue processing.
                   2549: #   0       - Exit.
                   2550: #
                   2551: sub get_profile_entry {
                   2552:     my ($cmd, $tail, $client) = @_;
                   2553: 
                   2554:     my $userinput= "$cmd:$tail";
                   2555:    
                   2556:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2557:     chomp($what);
1.255     foxr     2558: 
                   2559:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   2560:     my ($first) = split(/:/,$replystring);
                   2561:     if($first ne "error") {
                   2562: 	&Reply($client, "$replystring\n", $userinput);
1.231     foxr     2563:     } else {
1.255     foxr     2564: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     2565:     }
                   2566:     return 1;
1.255     foxr     2567: 
                   2568: 
1.231     foxr     2569: }
                   2570: &register_handler("get", \&get_profile_entry, 0,1,0);
                   2571: 
                   2572: #
                   2573: #  Process the encrypted get request.  Note that the request is sent
                   2574: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   2575: #  information about the sensitive keys is given to the snooper.  Just not
                   2576: #  information about the values of the sensitive key.  Hmm if I wanted to
                   2577: #  know these I'd snoop for the egets. Get the profile item names from them
                   2578: #  and then issue a get for them since there's no enforcement of the
                   2579: #  requirement of an encrypted get for particular profile items.  If I
                   2580: #  were re-doing this, I'd force the request to be encrypted as well as the
                   2581: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   2582: #  that would prevent any covert channel snooping.
                   2583: #
                   2584: #  Parameters:
                   2585: #     $cmd               - Command keyword of request (eget).
                   2586: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
                   2587: #     $client            - File open on the client.
                   2588: #  Returns:
                   2589: #     1      - Continue processing
                   2590: #     0      - server should exit.
                   2591: sub get_profile_entry_encrypted {
                   2592:     my ($cmd, $tail, $client) = @_;
                   2593: 
                   2594:     my $userinput = "$cmd:$tail";
                   2595:    
                   2596:     my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
                   2597:     chomp($what);
1.255     foxr     2598:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   2599:     my ($first) = split(/:/, $qresult);
                   2600:     if($first ne "error") {
                   2601: 	
                   2602: 	if ($cipher) {
                   2603: 	    my $cmdlength=length($qresult);
                   2604: 	    $qresult.="         ";
                   2605: 	    my $encqresult='';
                   2606: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   2607: 		$encqresult.= unpack("H16", 
                   2608: 				     $cipher->encrypt(substr($qresult,
                   2609: 							     $encidx,
                   2610: 							     8)));
                   2611: 	    }
                   2612: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   2613: 	} else {
1.231     foxr     2614: 		&Failure( $client, "error:no_key\n", $userinput);
                   2615: 	    }
                   2616:     } else {
1.255     foxr     2617: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   2618: 
1.231     foxr     2619:     }
                   2620:     
                   2621:     return 1;
                   2622: }
1.255     foxr     2623: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 2624: 
1.231     foxr     2625: #
                   2626: #   Deletes a key in a user profile database.
                   2627: #   
                   2628: #   Parameters:
                   2629: #       $cmd                  - Command keyword (del).
                   2630: #       $tail                 - Command tail.  IN this case a colon
                   2631: #                               separated list containing:
                   2632: #                               The domain and user that identifies uniquely
                   2633: #                               the identity of the user.
                   2634: #                               The profile namespace (name of the profile
                   2635: #                               database file).
                   2636: #                               & separated list of keywords to delete.
                   2637: #       $client              - File open on client socket.
                   2638: # Returns:
                   2639: #     1   - Continue processing
                   2640: #     0   - Exit server.
                   2641: #
                   2642: #
                   2643: sub delete_profile_entry {
                   2644:     my ($cmd, $tail, $client) = @_;
                   2645: 
                   2646:     my $userinput = "cmd:$tail";
                   2647: 
                   2648:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2649:     chomp($what);
                   2650:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2651: 				 &GDBM_WRCREAT(),
                   2652: 				 "D",$what);
                   2653:     if ($hashref) {
                   2654:         my @keys=split(/\&/,$what);
                   2655: 	foreach my $key (@keys) {
                   2656: 	    delete($hashref->{$key});
                   2657: 	}
1.315     albertel 2658: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2659: 	    &Reply($client, "ok\n", $userinput);
                   2660: 	} else {
                   2661: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2662: 		    "while attempting del\n", $userinput);
                   2663: 	}
                   2664:     } else {
                   2665: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2666: 		 "while attempting del\n", $userinput);
                   2667:     }
                   2668:     return 1;
                   2669: }
                   2670: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 2671: 
1.231     foxr     2672: #
                   2673: #  List the set of keys that are defined in a profile database file.
                   2674: #  A successful reply from this will contain an & separated list of
                   2675: #  the keys. 
                   2676: # Parameters:
                   2677: #     $cmd              - Command request (keys).
                   2678: #     $tail             - Remainder of the request, a colon separated
                   2679: #                         list containing domain/user that identifies the
                   2680: #                         user being queried, and the database namespace
                   2681: #                         (database filename essentially).
                   2682: #     $client           - File open on the client.
                   2683: #  Returns:
                   2684: #    1    - Continue processing.
                   2685: #    0    - Exit the server.
                   2686: #
                   2687: sub get_profile_keys {
                   2688:     my ($cmd, $tail, $client) = @_;
                   2689: 
                   2690:     my $userinput = "$cmd:$tail";
                   2691: 
                   2692:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   2693:     my $qresult='';
                   2694:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2695: 				  &GDBM_READER());
                   2696:     if ($hashref) {
                   2697: 	foreach my $key (keys %$hashref) {
                   2698: 	    $qresult.="$key&";
                   2699: 	}
1.315     albertel 2700: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2701: 	    $qresult=~s/\&$//;
                   2702: 	    &Reply($client, "$qresult\n", $userinput);
                   2703: 	} else {
                   2704: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2705: 		    "while attempting keys\n", $userinput);
                   2706: 	}
                   2707:     } else {
                   2708: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2709: 		 "while attempting keys\n", $userinput);
                   2710:     }
                   2711:    
                   2712:     return 1;
                   2713: }
                   2714: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   2715: 
                   2716: #
                   2717: #   Dump the contents of a user profile database.
                   2718: #   Note that this constitutes a very large covert channel too since
                   2719: #   the dump will return sensitive information that is not encrypted.
                   2720: #   The naive security assumption is that the session negotiation ensures
                   2721: #   our client is trusted and I don't believe that's assured at present.
                   2722: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   2723: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   2724: # 
                   2725: #  Parameters:
                   2726: #     $cmd           - The command request keyword (currentdump).
                   2727: #     $tail          - Remainder of the request, consisting of a colon
                   2728: #                      separated list that has the domain/username and
                   2729: #                      the namespace to dump (database file).
                   2730: #     $client        - file open on the remote client.
                   2731: # Returns:
                   2732: #     1    - Continue processing.
                   2733: #     0    - Exit the server.
                   2734: #
                   2735: sub dump_profile_database {
                   2736:     my ($cmd, $tail, $client) = @_;
                   2737: 
                   2738:     my $userinput = "$cmd:$tail";
                   2739:    
                   2740:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   2741:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2742: 				 &GDBM_READER());
                   2743:     if ($hashref) {
                   2744: 	# Structure of %data:
                   2745: 	# $data{$symb}->{$parameter}=$value;
                   2746: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   2747: 	# since $parameter will be unescaped, we do not
                   2748:  	# have to worry about silly parameter names...
                   2749: 	
                   2750:         my $qresult='';
                   2751: 	my %data = ();                     # A hash of anonymous hashes..
                   2752: 	while (my ($key,$value) = each(%$hashref)) {
                   2753: 	    my ($v,$symb,$param) = split(/:/,$key);
                   2754: 	    next if ($v eq 'version' || $symb eq 'keys');
                   2755: 	    next if (exists($data{$symb}) && 
                   2756: 		     exists($data{$symb}->{$param}) &&
                   2757: 		     $data{$symb}->{'v.'.$param} > $v);
                   2758: 	    $data{$symb}->{$param}=$value;
                   2759: 	    $data{$symb}->{'v.'.$param}=$v;
                   2760: 	}
1.311     albertel 2761: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2762: 	    while (my ($symb,$param_hash) = each(%data)) {
                   2763: 		while(my ($param,$value) = each (%$param_hash)){
                   2764: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   2765: 		    #
                   2766: 		    #   Just dump the symb=value pairs separated by &
                   2767: 		    #
                   2768: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   2769: 		}
                   2770: 	    }
                   2771: 	    chop($qresult);
                   2772: 	    &Reply($client , "$qresult\n", $userinput);
                   2773: 	} else {
                   2774: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2775: 		     "while attempting currentdump\n", $userinput);
                   2776: 	}
                   2777:     } else {
                   2778: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2779: 		"while attempting currentdump\n", $userinput);
                   2780:     }
                   2781: 
                   2782:     return 1;
                   2783: }
                   2784: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   2785: 
                   2786: #
                   2787: #   Dump a profile database with an optional regular expression
                   2788: #   to match against the keys.  In this dump, no effort is made
                   2789: #   to separate symb from version information. Presumably the
                   2790: #   databases that are dumped by this command are of a different
                   2791: #   structure.  Need to look at this and improve the documentation of
                   2792: #   both this and the currentdump handler.
                   2793: # Parameters:
                   2794: #    $cmd                     - The command keyword.
                   2795: #    $tail                    - All of the characters after the $cmd:
                   2796: #                               These are expected to be a colon
                   2797: #                               separated list containing:
                   2798: #                               domain/user - identifying the user.
                   2799: #                               namespace   - identifying the database.
                   2800: #                               regexp      - optional regular expression
                   2801: #                                             that is matched against
                   2802: #                                             database keywords to do
                   2803: #                                             selective dumps.
                   2804: #   $client                   - Channel open on the client.
                   2805: # Returns:
                   2806: #    1    - Continue processing.
                   2807: # Side effects:
                   2808: #    response is written to $client.
                   2809: #
                   2810: sub dump_with_regexp {
                   2811:     my ($cmd, $tail, $client) = @_;
                   2812: 
                   2813: 
                   2814:     my $userinput = "$cmd:$tail";
                   2815: 
1.306     albertel 2816:     my ($udom,$uname,$namespace,$regexp,$range)=split(/:/,$tail);
1.231     foxr     2817:     if (defined($regexp)) {
                   2818: 	$regexp=&unescape($regexp);
                   2819:     } else {
                   2820: 	$regexp='.';
                   2821:     }
1.306     albertel 2822:     my ($start,$end);
                   2823:     if (defined($range)) {
                   2824: 	if ($range =~/^(\d+)\-(\d+)$/) {
                   2825: 	    ($start,$end) = ($1,$2);
                   2826: 	} elsif ($range =~/^(\d+)$/) {
                   2827: 	    ($start,$end) = (0,$1);
                   2828: 	} else {
                   2829: 	    undef($range);
                   2830: 	}
                   2831:     }
1.231     foxr     2832:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2833: 				 &GDBM_READER());
                   2834:     if ($hashref) {
                   2835:         my $qresult='';
1.306     albertel 2836: 	my $count=0;
1.231     foxr     2837: 	while (my ($key,$value) = each(%$hashref)) {
                   2838: 	    if ($regexp eq '.') {
1.306     albertel 2839: 		$count++;
                   2840: 		if (defined($range) && $count >= $end)   { last; }
                   2841: 		if (defined($range) && $count <  $start) { next; }
1.231     foxr     2842: 		$qresult.=$key.'='.$value.'&';
                   2843: 	    } else {
                   2844: 		my $unescapeKey = &unescape($key);
                   2845: 		if (eval('$unescapeKey=~/$regexp/')) {
1.306     albertel 2846: 		    $count++;
                   2847: 		    if (defined($range) && $count >= $end)   { last; }
                   2848: 		    if (defined($range) && $count <  $start) { next; }
1.231     foxr     2849: 		    $qresult.="$key=$value&";
                   2850: 		}
                   2851: 	    }
                   2852: 	}
1.311     albertel 2853: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2854: 	    chop($qresult);
                   2855: 	    &Reply($client, "$qresult\n", $userinput);
                   2856: 	} else {
                   2857: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2858: 		     "while attempting dump\n", $userinput);
                   2859: 	}
                   2860:     } else {
                   2861: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2862: 		"while attempting dump\n", $userinput);
                   2863:     }
                   2864: 
                   2865:     return 1;
                   2866: }
                   2867: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   2868: 
                   2869: #  Store a set of key=value pairs associated with a versioned name.
                   2870: #
                   2871: #  Parameters:
                   2872: #    $cmd                - Request command keyword.
                   2873: #    $tail               - Tail of the request.  This is a colon
                   2874: #                          separated list containing:
                   2875: #                          domain/user - User and authentication domain.
                   2876: #                          namespace   - Name of the database being modified
                   2877: #                          rid         - Resource keyword to modify.
                   2878: #                          what        - new value associated with rid.
                   2879: #
                   2880: #    $client             - Socket open on the client.
                   2881: #
                   2882: #
                   2883: #  Returns:
                   2884: #      1 (keep on processing).
                   2885: #  Side-Effects:
                   2886: #    Writes to the client
                   2887: sub store_handler {
                   2888:     my ($cmd, $tail, $client) = @_;
                   2889:  
                   2890:     my $userinput = "$cmd:$tail";
                   2891: 
                   2892:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
                   2893:     if ($namespace ne 'roles') {
                   2894: 
                   2895: 	chomp($what);
                   2896: 	my @pairs=split(/\&/,$what);
                   2897: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 2898: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     2899: 				       "$rid:$what");
                   2900: 	if ($hashref) {
                   2901: 	    my $now = time;
                   2902: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
                   2903: 	    my $key;
                   2904: 	    $hashref->{"version:$rid"}++;
                   2905: 	    my $version=$hashref->{"version:$rid"};
                   2906: 	    my $allkeys=''; 
                   2907: 	    foreach my $pair (@pairs) {
                   2908: 		my ($key,$value)=split(/=/,$pair);
                   2909: 		$allkeys.=$key.':';
                   2910: 		$hashref->{"$version:$rid:$key"}=$value;
                   2911: 	    }
                   2912: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   2913: 	    $allkeys.='timestamp';
                   2914: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 2915: 	    if (&untie_user_hash($hashref)) {
1.231     foxr     2916: 		&Reply($client, "ok\n", $userinput);
                   2917: 	    } else {
                   2918: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2919: 			"while attempting store\n", $userinput);
                   2920: 	    }
                   2921: 	} else {
                   2922: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2923: 		     "while attempting store\n", $userinput);
                   2924: 	}
                   2925:     } else {
                   2926: 	&Failure($client, "refused\n", $userinput);
                   2927:     }
                   2928: 
                   2929:     return 1;
                   2930: }
                   2931: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 2932: 
1.323     albertel 2933: #  Modify a set of key=value pairs associated with a versioned name.
                   2934: #
                   2935: #  Parameters:
                   2936: #    $cmd                - Request command keyword.
                   2937: #    $tail               - Tail of the request.  This is a colon
                   2938: #                          separated list containing:
                   2939: #                          domain/user - User and authentication domain.
                   2940: #                          namespace   - Name of the database being modified
                   2941: #                          rid         - Resource keyword to modify.
                   2942: #                          v           - Version item to modify
                   2943: #                          what        - new value associated with rid.
                   2944: #
                   2945: #    $client             - Socket open on the client.
                   2946: #
                   2947: #
                   2948: #  Returns:
                   2949: #      1 (keep on processing).
                   2950: #  Side-Effects:
                   2951: #    Writes to the client
                   2952: sub putstore_handler {
                   2953:     my ($cmd, $tail, $client) = @_;
                   2954:  
                   2955:     my $userinput = "$cmd:$tail";
                   2956: 
                   2957:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   2958:     if ($namespace ne 'roles') {
                   2959: 
                   2960: 	chomp($what);
                   2961: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   2962: 				       &GDBM_WRCREAT(), "M",
                   2963: 				       "$rid:$v:$what");
                   2964: 	if ($hashref) {
                   2965: 	    my $now = time;
                   2966: 	    my %data = &hash_extract($what);
                   2967: 	    my @allkeys;
                   2968: 	    while (my($key,$value) = each(%data)) {
                   2969: 		push(@allkeys,$key);
                   2970: 		$hashref->{"$v:$rid:$key"} = $value;
                   2971: 	    }
                   2972: 	    my $allkeys = join(':',@allkeys);
                   2973: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   2974: 
                   2975: 	    if (&untie_user_hash($hashref)) {
                   2976: 		&Reply($client, "ok\n", $userinput);
                   2977: 	    } else {
                   2978: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2979: 			"while attempting store\n", $userinput);
                   2980: 	    }
                   2981: 	} else {
                   2982: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2983: 		     "while attempting store\n", $userinput);
                   2984: 	}
                   2985:     } else {
                   2986: 	&Failure($client, "refused\n", $userinput);
                   2987:     }
                   2988: 
                   2989:     return 1;
                   2990: }
                   2991: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   2992: 
                   2993: sub hash_extract {
                   2994:     my ($str)=@_;
                   2995:     my %hash;
                   2996:     foreach my $pair (split(/\&/,$str)) {
                   2997: 	my ($key,$value)=split(/=/,$pair);
                   2998: 	$hash{$key}=$value;
                   2999:     }
                   3000:     return (%hash);
                   3001: }
                   3002: sub hash_to_str {
                   3003:     my ($hash_ref)=@_;
                   3004:     my $str;
                   3005:     foreach my $key (keys(%$hash_ref)) {
                   3006: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3007:     }
                   3008:     $str=~s/\&$//;
                   3009:     return $str;
                   3010: }
                   3011: 
1.231     foxr     3012: #
                   3013: #  Dump out all versions of a resource that has key=value pairs associated
                   3014: # with it for each version.  These resources are built up via the store
                   3015: # command.
                   3016: #
                   3017: #  Parameters:
                   3018: #     $cmd               - Command keyword.
                   3019: #     $tail              - Remainder of the request which consists of:
                   3020: #                          domain/user   - User and auth. domain.
                   3021: #                          namespace     - name of resource database.
                   3022: #                          rid           - Resource id.
                   3023: #    $client             - socket open on the client.
                   3024: #
                   3025: # Returns:
                   3026: #      1  indicating the caller should not yet exit.
                   3027: # Side-effects:
                   3028: #   Writes a reply to the client.
                   3029: #   The reply is a string of the following shape:
                   3030: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3031: #    Where the 1 above represents version 1.
                   3032: #    this continues for all pairs of keys in all versions.
                   3033: #
                   3034: #
                   3035: #    
                   3036: #
                   3037: sub restore_handler {
                   3038:     my ($cmd, $tail, $client) = @_;
                   3039: 
                   3040:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
                   3041: 
                   3042:     my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
                   3043:     $namespace=~s/\//\_/g;
                   3044:     $namespace=~s/\W//g;
                   3045:     chomp($rid);
                   3046:     my $qresult='';
1.309     albertel 3047:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3048:     if ($hashref) {
                   3049: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3050: 	$qresult.="version=$version&";
                   3051: 	my $scope;
                   3052: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3053: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3054: 	    my @keys=split(/:/,$vkeys);
                   3055: 	    my $key;
                   3056: 	    $qresult.="$scope:keys=$vkeys&";
                   3057: 	    foreach $key (@keys) {
1.309     albertel 3058: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3059: 	    }                                  
                   3060: 	}
1.311     albertel 3061: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3062: 	    $qresult=~s/\&$//;
                   3063: 	    &Reply( $client, "$qresult\n", $userinput);
                   3064: 	} else {
                   3065: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3066: 		    "while attempting restore\n", $userinput);
                   3067: 	}
                   3068:     } else {
                   3069: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3070: 		"while attempting restore\n", $userinput);
                   3071:     }
                   3072:   
                   3073:     return 1;
                   3074: 
                   3075: 
                   3076: }
                   3077: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3078: 
                   3079: #
1.324     raeburn  3080: #   Add a chat message to a synchronous discussion board.
1.234     foxr     3081: #
                   3082: # Parameters:
                   3083: #    $cmd                - Request keyword.
                   3084: #    $tail               - Tail of the command. A colon separated list
                   3085: #                          containing:
                   3086: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  3087: #                          cnum    - Course containing the chat board.
                   3088: #                          newpost - Body of the posting.
                   3089: #                          group   - Optional group, if chat board is only 
                   3090: #                                    accessible in a group within the course 
1.234     foxr     3091: #   $client              - Socket open on the client.
                   3092: # Returns:
                   3093: #   1    - Indicating caller should keep on processing.
                   3094: #
                   3095: # Side-effects:
                   3096: #   writes a reply to the client.
                   3097: #
                   3098: #
                   3099: sub send_chat_handler {
                   3100:     my ($cmd, $tail, $client) = @_;
                   3101: 
                   3102:     
                   3103:     my $userinput = "$cmd:$tail";
                   3104: 
1.324     raeburn  3105:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   3106:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     3107:     &Reply($client, "ok\n", $userinput);
                   3108: 
                   3109:     return 1;
                   3110: }
                   3111: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3112: 
1.234     foxr     3113: #
1.324     raeburn  3114: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     3115: #
                   3116: #  Parameters:
                   3117: #    $cmd             - Command keyword that initiated the request.
                   3118: #    $tail            - Remainder of the request after the command
                   3119: #                       keyword.  In this case a colon separated list of
                   3120: #                       chat domain    - Which discussion board.
                   3121: #                       chat id        - Discussion thread(?)
                   3122: #                       domain/user    - Authentication domain and username
                   3123: #                                        of the requesting person.
1.324     raeburn  3124: #                       group          - Optional course group containing
                   3125: #                                        the board.      
1.234     foxr     3126: #   $client           - Socket open on the client program.
                   3127: # Returns:
                   3128: #    1     - continue processing
                   3129: # Side effects:
                   3130: #    Response is written to the client.
                   3131: #
                   3132: sub retrieve_chat_handler {
                   3133:     my ($cmd, $tail, $client) = @_;
                   3134: 
                   3135: 
                   3136:     my $userinput = "$cmd:$tail";
                   3137: 
1.324     raeburn  3138:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     3139:     my $reply='';
1.324     raeburn  3140:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     3141: 	$reply.=&escape($_).':';
                   3142:     }
                   3143:     $reply=~s/\:$//;
                   3144:     &Reply($client, $reply."\n", $userinput);
                   3145: 
                   3146: 
                   3147:     return 1;
                   3148: }
                   3149: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3150: 
                   3151: #
                   3152: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3153: #  a file for later retrieval.  This prevents sql query results from
                   3154: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3155: #  less of an issue since multiple outstanding requests can be concurrently
                   3156: #  serviced.
                   3157: #
                   3158: #  Parameters:
                   3159: #     $cmd       - COmmand keyword that initiated the request.
                   3160: #     $tail      - Remainder of the command after the keyword.
                   3161: #                  For this function, this consists of a query and
                   3162: #                  3 arguments that are self-documentingly labelled
                   3163: #                  in the original arg1, arg2, arg3.
                   3164: #     $client    - Socket open on the client.
                   3165: # Return:
                   3166: #    1   - Indicating processing should continue.
                   3167: # Side-effects:
                   3168: #    a reply is written to $client.
                   3169: #
                   3170: sub send_query_handler {
                   3171:     my ($cmd, $tail, $client) = @_;
                   3172: 
                   3173: 
                   3174:     my $userinput = "$cmd:$tail";
                   3175: 
                   3176:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3177:     $query=~s/\n*$//g;
                   3178:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   3179: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   3180: 	  $userinput);
                   3181:     
                   3182:     return 1;
                   3183: }
                   3184: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   3185: 
                   3186: #
                   3187: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   3188: #   The query is submitted via a "querysend" transaction.
                   3189: #   There it is passed on to the lonsql daemon, queued and issued to
                   3190: #   mysql.
                   3191: #     This transaction is invoked when the sql transaction is complete
                   3192: #   it stores the query results in flie and indicates query completion.
                   3193: #   presumably local software then fetches this response... I'm guessing
                   3194: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   3195: #   lonsql on completion of the query interacts with the lond of our
                   3196: #   client to do a query reply storing two files:
                   3197: #    - id     - The results of the query.
                   3198: #    - id.end - Indicating the transaction completed. 
                   3199: #    NOTE: id is a unique id assigned to the query and querysend time.
                   3200: # Parameters:
                   3201: #    $cmd        - Command keyword that initiated this request.
                   3202: #    $tail       - Remainder of the tail.  In this case that's a colon
                   3203: #                  separated list containing the query Id and the 
                   3204: #                  results of the query.
                   3205: #    $client     - Socket open on the client.
                   3206: # Return:
                   3207: #    1           - Indicating that we should continue processing.
                   3208: # Side effects:
                   3209: #    ok written to the client.
                   3210: #
                   3211: sub reply_query_handler {
                   3212:     my ($cmd, $tail, $client) = @_;
                   3213: 
                   3214: 
                   3215:     my $userinput = "$cmd:$tail";
                   3216: 
                   3217:     my ($cmd,$id,$reply)=split(/:/,$userinput); 
                   3218:     my $store;
                   3219:     my $execdir=$perlvar{'lonDaemons'};
                   3220:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   3221: 	$reply=~s/\&/\n/g;
                   3222: 	print $store $reply;
                   3223: 	close $store;
                   3224: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   3225: 	print $store2 "done\n";
                   3226: 	close $store2;
                   3227: 	&Reply($client, "ok\n", $userinput);
                   3228:     } else {
                   3229: 	&Failure($client, "error: ".($!+0)
                   3230: 		." IO::File->new Failed ".
                   3231: 		"while attempting queryreply\n", $userinput);
                   3232:     }
                   3233:  
                   3234: 
                   3235:     return 1;
                   3236: }
                   3237: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   3238: 
                   3239: #
                   3240: #  Process the courseidput request.  Not quite sure what this means
                   3241: #  at the system level sense.  It appears a gdbm file in the 
                   3242: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   3243: #  a set of entries made in that database.
                   3244: #
                   3245: # Parameters:
                   3246: #   $cmd      - The command keyword that initiated this request.
                   3247: #   $tail     - Tail of the command.  In this case consists of a colon
                   3248: #               separated list contaning the domain to apply this to and
                   3249: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  3250: #               Each value is a colon separated list that includes:  
                   3251: #               description, institutional code and course owner.
                   3252: #               For backward compatibility with versions included
                   3253: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   3254: #               code and/or course owner are preserved from the existing 
                   3255: #               record when writing a new record in response to 1.1 or 
                   3256: #               1.2 implementations of lonnet::flushcourselogs().   
                   3257: #                      
1.234     foxr     3258: #   $client   - Socket open on the client.
                   3259: # Returns:
                   3260: #   1    - indicating that processing should continue
                   3261: #
                   3262: # Side effects:
                   3263: #   reply is written to the client.
                   3264: #
                   3265: sub put_course_id_handler {
                   3266:     my ($cmd, $tail, $client) = @_;
                   3267: 
                   3268: 
                   3269:     my $userinput = "$cmd:$tail";
                   3270: 
1.266     raeburn  3271:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     3272:     chomp($what);
                   3273:     my $now=time;
                   3274:     my @pairs=split(/\&/,$what);
                   3275: 
                   3276:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3277:     if ($hashref) {
                   3278: 	foreach my $pair (@pairs) {
1.271     raeburn  3279:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   3280:             $courseinfo =~ s/=/:/g;
1.272     raeburn  3281: 
1.273     albertel 3282:             my @current_items = split(/:/,$hashref->{$key});
                   3283:             shift(@current_items); # remove description
                   3284:             pop(@current_items);   # remove last access
1.272     raeburn  3285:             my $numcurrent = scalar(@current_items);
                   3286: 
1.273     albertel 3287:             my @new_items = split(/:/,$courseinfo);
1.272     raeburn  3288:             my $numnew = scalar(@new_items);
                   3289:             if ($numcurrent > 0) {
                   3290:                 if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
                   3291:                     $courseinfo .= ':'.join(':',@current_items);
                   3292:                 } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
                   3293:                     $courseinfo .= ':'.$current_items[$numcurrent-1];
                   3294:                 }
                   3295:             }
1.266     raeburn  3296: 	    $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     3297: 	}
1.311     albertel 3298: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     3299: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     3300: 	} else {
1.253     foxr     3301: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     3302: 		     ." untie(GDBM) Failed ".
                   3303: 		     "while attempting courseidput\n", $userinput);
                   3304: 	}
                   3305:     } else {
1.253     foxr     3306: 	&Failure($client, "error: ".($!+0)
1.234     foxr     3307: 		 ." tie(GDBM) Failed ".
                   3308: 		 "while attempting courseidput\n", $userinput);
                   3309:     }
1.253     foxr     3310:     
1.234     foxr     3311: 
                   3312:     return 1;
                   3313: }
                   3314: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   3315: 
                   3316: #  Retrieves the value of a course id resource keyword pattern
                   3317: #  defined since a starting date.  Both the starting date and the
                   3318: #  keyword pattern are optional.  If the starting date is not supplied it
                   3319: #  is treated as the beginning of time.  If the pattern is not found,
                   3320: #  it is treatred as "." matching everything.
                   3321: #
                   3322: #  Parameters:
                   3323: #     $cmd     - Command keyword that resulted in us being dispatched.
                   3324: #     $tail    - The remainder of the command that, in this case, consists
                   3325: #                of a colon separated list of:
                   3326: #                 domain   - The domain in which the course database is 
                   3327: #                            defined.
                   3328: #                 since    - Optional parameter describing the minimum
                   3329: #                            time of definition(?) of the resources that
                   3330: #                            will match the dump.
                   3331: #                 description - regular expression that is used to filter
                   3332: #                            the dump.  Only keywords matching this regexp
                   3333: #                            will be used.
1.272     raeburn  3334: #                 institutional code - optional supplied code to filter 
                   3335: #                            the dump. Only courses with an institutional code 
                   3336: #                            that match the supplied code will be returned.
                   3337: #                 owner    - optional supplied username of owner to filter
                   3338: #                            the dump.  Only courses for which the course 
                   3339: #                            owner matches the supplied username will be
1.274     albertel 3340: #                            returned. Implicit assumption that owner
                   3341: #                            is a user in the domain in which the
                   3342: #                            course database is defined.
1.234     foxr     3343: #     $client  - The socket open on the client.
                   3344: # Returns:
                   3345: #    1     - Continue processing.
                   3346: # Side Effects:
                   3347: #   a reply is written to $client.
                   3348: sub dump_course_id_handler {
                   3349:     my ($cmd, $tail, $client) = @_;
                   3350: 
                   3351:     my $userinput = "$cmd:$tail";
                   3352: 
1.282     raeburn  3353:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter) =split(/:/,$tail);
1.234     foxr     3354:     if (defined($description)) {
                   3355: 	$description=&unescape($description);
                   3356:     } else {
                   3357: 	$description='.';
                   3358:     }
1.266     raeburn  3359:     if (defined($instcodefilter)) {
                   3360:         $instcodefilter=&unescape($instcodefilter);
                   3361:     } else {
                   3362:         $instcodefilter='.';
                   3363:     }
                   3364:     if (defined($ownerfilter)) {
                   3365:         $ownerfilter=&unescape($ownerfilter);
                   3366:     } else {
                   3367:         $ownerfilter='.';
                   3368:     }
1.282     raeburn  3369:     if (defined($coursefilter)) {
                   3370:         $coursefilter=&unescape($coursefilter);
                   3371:     } else {
                   3372:         $coursefilter='.';
                   3373:     }
1.266     raeburn  3374: 
1.234     foxr     3375:     unless (defined($since)) { $since=0; }
                   3376:     my $qresult='';
                   3377:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3378:     if ($hashref) {
                   3379: 	while (my ($key,$value) = each(%$hashref)) {
1.266     raeburn  3380: 	    my ($descr,$lasttime,$inst_code,$owner);
1.274     albertel 3381:             my @courseitems = split(/:/,$value);
                   3382:             $lasttime = pop(@courseitems);
                   3383: 	    ($descr,$inst_code,$owner)=@courseitems;
1.234     foxr     3384: 	    if ($lasttime<$since) { next; }
1.266     raeburn  3385:             my $match = 1;
                   3386: 	    unless ($description eq '.') {
                   3387: 		my $unescapeDescr = &unescape($descr);
                   3388: 		unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
                   3389:                     $match = 0;
1.234     foxr     3390: 		}
1.266     raeburn  3391:             }
                   3392:             unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
                   3393:                 my $unescapeInstcode = &unescape($inst_code);
                   3394:                 unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
                   3395:                     $match = 0;
                   3396:                 }
1.234     foxr     3397: 	    }
1.266     raeburn  3398:             unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
                   3399:                 my $unescapeOwner = &unescape($owner);
                   3400:                 unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
                   3401:                     $match = 0;
                   3402:                 }
                   3403:             }
1.282     raeburn  3404:             unless ($coursefilter eq '.' || !defined($coursefilter)) {
                   3405:                 my $unescapeCourse = &unescape($key);
                   3406:                 unless (eval('$unescapeCourse=~/^$udom(_)\Q$coursefilter\E$/')) {
                   3407:                     $match = 0;
                   3408:                 }
                   3409:             }
1.266     raeburn  3410:             if ($match == 1) {
                   3411:                 $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
                   3412:             }
1.234     foxr     3413: 	}
1.311     albertel 3414: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     3415: 	    chop($qresult);
                   3416: 	    &Reply($client, "$qresult\n", $userinput);
                   3417: 	} else {
                   3418: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3419: 		    "while attempting courseiddump\n", $userinput);
                   3420: 	}
                   3421:     } else {
                   3422: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3423: 		"while attempting courseiddump\n", $userinput);
                   3424:     }
                   3425: 
                   3426: 
                   3427:     return 1;
                   3428: }
                   3429: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     3430: 
                   3431: #
                   3432: #  Puts an id to a domains id database. 
                   3433: #
                   3434: #  Parameters:
                   3435: #   $cmd     - The command that triggered us.
                   3436: #   $tail    - Remainder of the request other than the command. This is a 
                   3437: #              colon separated list containing:
                   3438: #              $domain  - The domain for which we are writing the id.
                   3439: #              $pairs  - The id info to write... this is and & separated list
                   3440: #                        of keyword=value.
                   3441: #   $client  - Socket open on the client.
                   3442: #  Returns:
                   3443: #    1   - Continue processing.
                   3444: #  Side effects:
                   3445: #     reply is written to $client.
                   3446: #
                   3447: sub put_id_handler {
                   3448:     my ($cmd,$tail,$client) = @_;
                   3449: 
                   3450: 
                   3451:     my $userinput = "$cmd:$tail";
                   3452: 
                   3453:     my ($udom,$what)=split(/:/,$tail);
                   3454:     chomp($what);
                   3455:     my @pairs=split(/\&/,$what);
                   3456:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   3457: 				   "P", $what);
                   3458:     if ($hashref) {
                   3459: 	foreach my $pair (@pairs) {
                   3460: 	    my ($key,$value)=split(/=/,$pair);
                   3461: 	    $hashref->{$key}=$value;
                   3462: 	}
1.311     albertel 3463: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     3464: 	    &Reply($client, "ok\n", $userinput);
                   3465: 	} else {
                   3466: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3467: 		     "while attempting idput\n", $userinput);
                   3468: 	}
                   3469:     } else {
                   3470: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3471: 		  "while attempting idput\n", $userinput);
                   3472:     }
                   3473: 
                   3474:     return 1;
                   3475: }
1.263     albertel 3476: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     3477: 
                   3478: #
                   3479: #  Retrieves a set of id values from the id database.
                   3480: #  Returns an & separated list of results, one for each requested id to the
                   3481: #  client.
                   3482: #
                   3483: # Parameters:
                   3484: #   $cmd       - Command keyword that caused us to be dispatched.
                   3485: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3486: #               domain - the domain whose id table we dump
                   3487: #               ids      Consists of an & separated list of
                   3488: #                        id keywords whose values will be fetched.
                   3489: #                        nonexisting keywords will have an empty value.
                   3490: #   $client    - Socket open on the client.
                   3491: #
                   3492: # Returns:
                   3493: #    1 - indicating processing should continue.
                   3494: # Side effects:
                   3495: #   An & separated list of results is written to $client.
                   3496: #
                   3497: sub get_id_handler {
                   3498:     my ($cmd, $tail, $client) = @_;
                   3499: 
                   3500:     
                   3501:     my $userinput = "$client:$tail";
                   3502:     
                   3503:     my ($udom,$what)=split(/:/,$tail);
                   3504:     chomp($what);
                   3505:     my @queries=split(/\&/,$what);
                   3506:     my $qresult='';
                   3507:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   3508:     if ($hashref) {
                   3509: 	for (my $i=0;$i<=$#queries;$i++) {
                   3510: 	    $qresult.="$hashref->{$queries[$i]}&";
                   3511: 	}
1.311     albertel 3512: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     3513: 	    $qresult=~s/\&$//;
                   3514: 	    &Reply($client, "$qresult\n", $userinput);
                   3515: 	} else {
                   3516: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3517: 		      "while attempting idget\n",$userinput);
                   3518: 	}
                   3519:     } else {
                   3520: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3521: 		 "while attempting idget\n",$userinput);
                   3522:     }
                   3523:     
                   3524:     return 1;
                   3525: }
1.263     albertel 3526: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     3527: 
                   3528: #
1.299     raeburn  3529: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   3530: #
                   3531: # Parameters
                   3532: #   $cmd       - Command keyword that caused us to be dispatched.
                   3533: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3534: #               domain - the domain whose dcmail we are recording
                   3535: #               email    Consists of key=value pair 
                   3536: #                        where key is unique msgid
                   3537: #                        and value is message (in XML)
                   3538: #   $client    - Socket open on the client.
                   3539: #
                   3540: # Returns:
                   3541: #    1 - indicating processing should continue.
                   3542: # Side effects
                   3543: #     reply is written to $client.
                   3544: #
                   3545: sub put_dcmail_handler {
                   3546:     my ($cmd,$tail,$client) = @_;
                   3547:     my $userinput = "$cmd:$tail";
                   3548:                                                                                 
                   3549:     my ($udom,$what)=split(/:/,$tail);
                   3550:     chomp($what);
                   3551:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   3552:     if ($hashref) {
                   3553:         my ($key,$value)=split(/=/,$what);
                   3554:         $hashref->{$key}=$value;
                   3555:     }
1.311     albertel 3556:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  3557:         &Reply($client, "ok\n", $userinput);
                   3558:     } else {
                   3559:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3560:                  "while attempting dcmailput\n", $userinput);
                   3561:     }
                   3562:     return 1;
                   3563: }
                   3564: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   3565: 
                   3566: #
                   3567: # Retrieves broadcast e-mail from nohist_dcmail database
                   3568: # Returns to client an & separated list of key=value pairs,
                   3569: # where key is msgid and value is message information.
                   3570: #
                   3571: # Parameters
                   3572: #   $cmd       - Command keyword that caused us to be dispatched.
                   3573: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3574: #               domain - the domain whose dcmail table we dump
                   3575: #               startfilter - beginning of time window 
                   3576: #               endfilter - end of time window
                   3577: #               sendersfilter - & separated list of username:domain 
                   3578: #                 for senders to search for.
                   3579: #   $client    - Socket open on the client.
                   3580: #
                   3581: # Returns:
                   3582: #    1 - indicating processing should continue.
                   3583: # Side effects
                   3584: #     reply (& separated list of msgid=messageinfo pairs) is 
                   3585: #     written to $client.
                   3586: #
                   3587: sub dump_dcmail_handler {
                   3588:     my ($cmd, $tail, $client) = @_;
                   3589:                                                                                 
                   3590:     my $userinput = "$cmd:$tail";
                   3591:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   3592:     chomp($sendersfilter);
                   3593:     my @senders = ();
                   3594:     if (defined($startfilter)) {
                   3595:         $startfilter=&unescape($startfilter);
                   3596:     } else {
                   3597:         $startfilter='.';
                   3598:     }
                   3599:     if (defined($endfilter)) {
                   3600:         $endfilter=&unescape($endfilter);
                   3601:     } else {
                   3602:         $endfilter='.';
                   3603:     }
                   3604:     if (defined($sendersfilter)) {
                   3605:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 3606: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  3607:     }
                   3608: 
                   3609:     my $qresult='';
                   3610:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   3611:     if ($hashref) {
                   3612:         while (my ($key,$value) = each(%$hashref)) {
                   3613:             my $match = 1;
1.303     albertel 3614:             my ($timestamp,$subj,$uname,$udom) = 
                   3615: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  3616:             $subj = &unescape($subj);
                   3617:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   3618:                 if ($timestamp < $startfilter) {
                   3619:                     $match = 0;
                   3620:                 }
                   3621:             }
                   3622:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   3623:                 if ($timestamp > $endfilter) {
                   3624:                     $match = 0;
                   3625:                 }
                   3626:             }
                   3627:             unless (@senders < 1) {
                   3628:                 unless (grep/^$uname:$udom$/,@senders) {
                   3629:                     $match = 0;
                   3630:                 }
                   3631:             }
                   3632:             if ($match == 1) {
                   3633:                 $qresult.=$key.'='.$value.'&';
                   3634:             }
                   3635:         }
1.311     albertel 3636:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  3637:             chop($qresult);
                   3638:             &Reply($client, "$qresult\n", $userinput);
                   3639:         } else {
                   3640:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3641:                     "while attempting dcmaildump\n", $userinput);
                   3642:         }
                   3643:     } else {
                   3644:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3645:                 "while attempting dcmaildump\n", $userinput);
                   3646:     }
                   3647:     return 1;
                   3648: }
                   3649: 
                   3650: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   3651: 
                   3652: #
                   3653: # Puts domain roles in nohist_domainroles database
                   3654: #
                   3655: # Parameters
                   3656: #   $cmd       - Command keyword that caused us to be dispatched.
                   3657: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3658: #               domain - the domain whose roles we are recording  
                   3659: #               role -   Consists of key=value pair
                   3660: #                        where key is unique role
                   3661: #                        and value is start/end date information
                   3662: #   $client    - Socket open on the client.
                   3663: #
                   3664: # Returns:
                   3665: #    1 - indicating processing should continue.
                   3666: # Side effects
                   3667: #     reply is written to $client.
                   3668: #
                   3669: 
                   3670: sub put_domainroles_handler {
                   3671:     my ($cmd,$tail,$client) = @_;
                   3672: 
                   3673:     my $userinput = "$cmd:$tail";
                   3674:     my ($udom,$what)=split(/:/,$tail);
                   3675:     chomp($what);
                   3676:     my @pairs=split(/\&/,$what);
                   3677:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   3678:     if ($hashref) {
                   3679:         foreach my $pair (@pairs) {
                   3680:             my ($key,$value)=split(/=/,$pair);
                   3681:             $hashref->{$key}=$value;
                   3682:         }
1.311     albertel 3683:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  3684:             &Reply($client, "ok\n", $userinput);
                   3685:         } else {
                   3686:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3687:                      "while attempting domroleput\n", $userinput);
                   3688:         }
                   3689:     } else {
                   3690:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3691:                   "while attempting domroleput\n", $userinput);
                   3692:     }
                   3693:                                                                                   
                   3694:     return 1;
                   3695: }
                   3696: 
                   3697: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   3698: 
                   3699: #
                   3700: # Retrieves domain roles from nohist_domainroles database
                   3701: # Returns to client an & separated list of key=value pairs,
                   3702: # where key is role and value is start and end date information.
                   3703: #
                   3704: # Parameters
                   3705: #   $cmd       - Command keyword that caused us to be dispatched.
                   3706: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3707: #               domain - the domain whose domain roles table we dump
                   3708: #   $client    - Socket open on the client.
                   3709: #
                   3710: # Returns:
                   3711: #    1 - indicating processing should continue.
                   3712: # Side effects
                   3713: #     reply (& separated list of role=start/end info pairs) is
                   3714: #     written to $client.
                   3715: #
                   3716: sub dump_domainroles_handler {
                   3717:     my ($cmd, $tail, $client) = @_;
                   3718:                                                                                            
                   3719:     my $userinput = "$cmd:$tail";
                   3720:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   3721:     chomp($rolesfilter);
                   3722:     my @roles = ();
                   3723:     if (defined($startfilter)) {
                   3724:         $startfilter=&unescape($startfilter);
                   3725:     } else {
                   3726:         $startfilter='.';
                   3727:     }
                   3728:     if (defined($endfilter)) {
                   3729:         $endfilter=&unescape($endfilter);
                   3730:     } else {
                   3731:         $endfilter='.';
                   3732:     }
                   3733:     if (defined($rolesfilter)) {
                   3734:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 3735: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  3736:     }
                   3737:                                                                                            
                   3738:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   3739:     if ($hashref) {
                   3740:         my $qresult = '';
                   3741:         while (my ($key,$value) = each(%$hashref)) {
                   3742:             my $match = 1;
                   3743:             my ($start,$end) = split(/:/,&unescape($value));
                   3744:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
                   3745:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   3746:                 if ($start >= $startfilter) {
                   3747:                     $match = 0;
                   3748:                 }
                   3749:             }
                   3750:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   3751:                 if ($end <= $endfilter) {
                   3752:                     $match = 0;
                   3753:                 }
                   3754:             }
                   3755:             unless (@roles < 1) {
                   3756:                 unless (grep/^$trole$/,@roles) {
                   3757:                     $match = 0;
                   3758:                 }
                   3759:             }
                   3760:             if ($match == 1) {
                   3761:                 $qresult.=$key.'='.$value.'&';
                   3762:             }
                   3763:         }
1.311     albertel 3764:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  3765:             chop($qresult);
                   3766:             &Reply($client, "$qresult\n", $userinput);
                   3767:         } else {
                   3768:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3769:                     "while attempting domrolesdump\n", $userinput);
                   3770:         }
                   3771:     } else {
                   3772:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3773:                 "while attempting domrolesdump\n", $userinput);
                   3774:     }
                   3775:     return 1;
                   3776: }
                   3777: 
                   3778: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   3779: 
                   3780: 
1.238     foxr     3781: #  Process the tmpput command I'm not sure what this does.. Seems to
                   3782: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   3783: # where Id is the client's ip concatenated with a sequence number.
                   3784: # The file will contain some value that is passed in.  Is this e.g.
                   3785: # a login token?
                   3786: #
                   3787: # Parameters:
                   3788: #    $cmd     - The command that got us dispatched.
                   3789: #    $tail    - The remainder of the request following $cmd:
                   3790: #               In this case this will be the contents of the file.
                   3791: #    $client  - Socket connected to the client.
                   3792: # Returns:
                   3793: #    1 indicating processing can continue.
                   3794: # Side effects:
                   3795: #   A file is created in the local filesystem.
                   3796: #   A reply is sent to the client.
                   3797: sub tmp_put_handler {
                   3798:     my ($cmd, $what, $client) = @_;
                   3799: 
                   3800:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   3801: 
                   3802: 
                   3803:     my $store;
                   3804:     $tmpsnum++;
                   3805:     my $id=$$.'_'.$clientip.'_'.$tmpsnum;
                   3806:     $id=~s/\W/\_/g;
                   3807:     $what=~s/\n//g;
                   3808:     my $execdir=$perlvar{'lonDaemons'};
                   3809:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
                   3810: 	print $store $what;
                   3811: 	close $store;
                   3812: 	&Reply($client, "$id\n", $userinput);
                   3813:     } else {
                   3814: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   3815: 		  "while attempting tmpput\n", $userinput);
                   3816:     }
                   3817:     return 1;
                   3818:   
                   3819: }
                   3820: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 3821: 
1.238     foxr     3822: #   Processes the tmpget command.  This command returns the contents
                   3823: #  of a temporary resource file(?) created via tmpput.
                   3824: #
                   3825: # Paramters:
                   3826: #    $cmd      - Command that got us dispatched.
                   3827: #    $id       - Tail of the command, contain the id of the resource
                   3828: #                we want to fetch.
                   3829: #    $client   - socket open on the client.
                   3830: # Return:
                   3831: #    1         - Inidcating processing can continue.
                   3832: # Side effects:
                   3833: #   A reply is sent to the client.
                   3834: #
                   3835: sub tmp_get_handler {
                   3836:     my ($cmd, $id, $client) = @_;
                   3837: 
                   3838:     my $userinput = "$cmd:$id"; 
                   3839:     
                   3840: 
                   3841:     $id=~s/\W/\_/g;
                   3842:     my $store;
                   3843:     my $execdir=$perlvar{'lonDaemons'};
                   3844:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   3845: 	my $reply=<$store>;
                   3846: 	&Reply( $client, "$reply\n", $userinput);
                   3847: 	close $store;
                   3848:     } else {
                   3849: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   3850: 		  "while attempting tmpget\n", $userinput);
                   3851:     }
                   3852: 
                   3853:     return 1;
                   3854: }
                   3855: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 3856: 
1.238     foxr     3857: #
                   3858: #  Process the tmpdel command.  This command deletes a temp resource
                   3859: #  created by the tmpput command.
                   3860: #
                   3861: # Parameters:
                   3862: #   $cmd      - Command that got us here.
                   3863: #   $id       - Id of the temporary resource created.
                   3864: #   $client   - socket open on the client process.
                   3865: #
                   3866: # Returns:
                   3867: #   1     - Indicating processing should continue.
                   3868: # Side Effects:
                   3869: #   A file is deleted
                   3870: #   A reply is sent to the client.
                   3871: sub tmp_del_handler {
                   3872:     my ($cmd, $id, $client) = @_;
                   3873:     
                   3874:     my $userinput= "$cmd:$id";
                   3875:     
                   3876:     chomp($id);
                   3877:     $id=~s/\W/\_/g;
                   3878:     my $execdir=$perlvar{'lonDaemons'};
                   3879:     if (unlink("$execdir/tmp/$id.tmp")) {
                   3880: 	&Reply($client, "ok\n", $userinput);
                   3881:     } else {
                   3882: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   3883: 		  "while attempting tmpdel\n", $userinput);
                   3884:     }
                   3885:     
                   3886:     return 1;
                   3887: 
                   3888: }
                   3889: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 3890: 
1.238     foxr     3891: #
1.246     foxr     3892: #   Processes the setannounce command.  This command
                   3893: #   creates a file named announce.txt in the top directory of
                   3894: #   the documentn root and sets its contents.  The announce.txt file is
                   3895: #   printed in its entirety at the LonCAPA login page.  Note:
                   3896: #   once the announcement.txt fileis created it cannot be deleted.
                   3897: #   However, setting the contents of the file to empty removes the
                   3898: #   announcement from the login page of loncapa so who cares.
                   3899: #
                   3900: # Parameters:
                   3901: #    $cmd          - The command that got us dispatched.
                   3902: #    $announcement - The text of the announcement.
                   3903: #    $client       - Socket open on the client process.
                   3904: # Retunrns:
                   3905: #   1             - Indicating request processing should continue
                   3906: # Side Effects:
                   3907: #   The file {DocRoot}/announcement.txt is created.
                   3908: #   A reply is sent to $client.
                   3909: #
                   3910: sub set_announce_handler {
                   3911:     my ($cmd, $announcement, $client) = @_;
                   3912:   
                   3913:     my $userinput    = "$cmd:$announcement";
                   3914: 
                   3915:     chomp($announcement);
                   3916:     $announcement=&unescape($announcement);
                   3917:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   3918: 				'/announcement.txt')) {
                   3919: 	print $store $announcement;
                   3920: 	close $store;
                   3921: 	&Reply($client, "ok\n", $userinput);
                   3922:     } else {
                   3923: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   3924:     }
                   3925: 
                   3926:     return 1;
                   3927: }
                   3928: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 3929: 
1.246     foxr     3930: #
                   3931: #  Return the version of the daemon.  This can be used to determine
                   3932: #  the compatibility of cross version installations or, alternatively to
                   3933: #  simply know who's out of date and who isn't.  Note that the version
                   3934: #  is returned concatenated with the tail.
                   3935: # Parameters:
                   3936: #   $cmd        - the request that dispatched to us.
                   3937: #   $tail       - Tail of the request (client's version?).
                   3938: #   $client     - Socket open on the client.
                   3939: #Returns:
                   3940: #   1 - continue processing requests.
                   3941: # Side Effects:
                   3942: #   Replies with version to $client.
                   3943: sub get_version_handler {
                   3944:     my ($cmd, $tail, $client) = @_;
                   3945: 
                   3946:     my $userinput  = $cmd.$tail;
                   3947:     
                   3948:     &Reply($client, &version($userinput)."\n", $userinput);
                   3949: 
                   3950: 
                   3951:     return 1;
                   3952: }
                   3953: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 3954: 
1.246     foxr     3955: #  Set the current host and domain.  This is used to support
                   3956: #  multihomed systems.  Each IP of the system, or even separate daemons
                   3957: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   3958: #  machine.  This command selects the virtual lonCAPA.  The client always
                   3959: #  knows the right one since it is lonc and it is selecting the domain/system
                   3960: #  from the hosts.tab file.
                   3961: # Parameters:
                   3962: #    $cmd      - Command that dispatched us.
                   3963: #    $tail     - Tail of the command (domain/host requested).
                   3964: #    $socket   - Socket open on the client.
                   3965: #
                   3966: # Returns:
                   3967: #     1   - Indicates the program should continue to process requests.
                   3968: # Side-effects:
                   3969: #     The default domain/system context is modified for this daemon.
                   3970: #     a reply is sent to the client.
                   3971: #
                   3972: sub set_virtual_host_handler {
                   3973:     my ($cmd, $tail, $socket) = @_;
                   3974:   
                   3975:     my $userinput  ="$cmd:$tail";
                   3976: 
                   3977:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   3978: 
                   3979: 
                   3980:     return 1;
                   3981: }
1.247     albertel 3982: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     3983: 
                   3984: #  Process a request to exit:
                   3985: #   - "bye" is sent to the client.
                   3986: #   - The client socket is shutdown and closed.
                   3987: #   - We indicate to the caller that we should exit.
                   3988: # Formal Parameters:
                   3989: #   $cmd                - The command that got us here.
                   3990: #   $tail               - Tail of the command (empty).
                   3991: #   $client             - Socket open on the tail.
                   3992: # Returns:
                   3993: #   0      - Indicating the program should exit!!
                   3994: #
                   3995: sub exit_handler {
                   3996:     my ($cmd, $tail, $client) = @_;
                   3997: 
                   3998:     my $userinput = "$cmd:$tail";
                   3999: 
                   4000:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   4001:     &Reply($client, "bye\n", $userinput);
                   4002:     $client->shutdown(2);        # shutdown the socket forcibly.
                   4003:     $client->close();
                   4004: 
                   4005:     return 0;
                   4006: }
1.248     foxr     4007: &register_handler("exit", \&exit_handler, 0,1,1);
                   4008: &register_handler("init", \&exit_handler, 0,1,1);
                   4009: &register_handler("quit", \&exit_handler, 0,1,1);
                   4010: 
                   4011: #  Determine if auto-enrollment is enabled.
                   4012: #  Note that the original had what I believe to be a defect.
                   4013: #  The original returned 0 if the requestor was not a registerd client.
                   4014: #  It should return "refused".
                   4015: # Formal Parameters:
                   4016: #   $cmd       - The command that invoked us.
                   4017: #   $tail      - The tail of the command (Extra command parameters.
                   4018: #   $client    - The socket open on the client that issued the request.
                   4019: # Returns:
                   4020: #    1         - Indicating processing should continue.
                   4021: #
                   4022: sub enrollment_enabled_handler {
                   4023:     my ($cmd, $tail, $client) = @_;
                   4024:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   4025: 
                   4026:     
                   4027:     my $cdom = split(/:/, $tail);   # Domain we're asking about.
                   4028:     my $outcome  = &localenroll::run($cdom);
                   4029:     &Reply($client, "$outcome\n", $userinput);
                   4030: 
                   4031:     return 1;
                   4032: }
                   4033: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   4034: 
                   4035: #   Get the official sections for which auto-enrollment is possible.
                   4036: #   Since the admin people won't know about 'unofficial sections' 
                   4037: #   we cannot auto-enroll on them.
                   4038: # Formal Parameters:
                   4039: #    $cmd     - The command request that got us dispatched here.
                   4040: #    $tail    - The remainder of the request.  In our case this
                   4041: #               will be split into:
                   4042: #               $coursecode   - The course name from the admin point of view.
                   4043: #               $cdom         - The course's domain(?).
                   4044: #    $client  - Socket open on the client.
                   4045: # Returns:
                   4046: #    1    - Indiciting processing should continue.
                   4047: #
                   4048: sub get_sections_handler {
                   4049:     my ($cmd, $tail, $client) = @_;
                   4050:     my $userinput = "$cmd:$tail";
                   4051: 
                   4052:     my ($coursecode, $cdom) = split(/:/, $tail);
                   4053:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   4054:     my $seclist = &escape(join(':',@secs));
                   4055: 
                   4056:     &Reply($client, "$seclist\n", $userinput);
                   4057:     
                   4058: 
                   4059:     return 1;
                   4060: }
                   4061: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   4062: 
                   4063: #   Validate the owner of a new course section.  
                   4064: #
                   4065: # Formal Parameters:
                   4066: #   $cmd      - Command that got us dispatched.
                   4067: #   $tail     - the remainder of the command.  For us this consists of a
                   4068: #               colon separated string containing:
                   4069: #                  $inst    - Course Id from the institutions point of view.
                   4070: #                  $owner   - Proposed owner of the course.
                   4071: #                  $cdom    - Domain of the course (from the institutions
                   4072: #                             point of view?)..
                   4073: #   $client   - Socket open on the client.
                   4074: #
                   4075: # Returns:
                   4076: #   1        - Processing should continue.
                   4077: #
                   4078: sub validate_course_owner_handler {
                   4079:     my ($cmd, $tail, $client)  = @_;
                   4080:     my $userinput = "$cmd:$tail";
                   4081:     my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
                   4082: 
                   4083:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
                   4084:     &Reply($client, "$outcome\n", $userinput);
                   4085: 
                   4086: 
                   4087: 
                   4088:     return 1;
                   4089: }
                   4090: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 4091: 
1.248     foxr     4092: #
                   4093: #   Validate a course section in the official schedule of classes
                   4094: #   from the institutions point of view (part of autoenrollment).
                   4095: #
                   4096: # Formal Parameters:
                   4097: #   $cmd          - The command request that got us dispatched.
                   4098: #   $tail         - The tail of the command.  In this case,
                   4099: #                   this is a colon separated set of words that will be split
                   4100: #                   into:
                   4101: #                        $inst_course_id - The course/section id from the
                   4102: #                                          institutions point of view.
                   4103: #                        $cdom           - The domain from the institutions
                   4104: #                                          point of view.
                   4105: #   $client       - Socket open on the client.
                   4106: # Returns:
                   4107: #    1           - Indicating processing should continue.
                   4108: #
                   4109: sub validate_course_section_handler {
                   4110:     my ($cmd, $tail, $client) = @_;
                   4111:     my $userinput = "$cmd:$tail";
                   4112:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   4113: 
                   4114:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
                   4115:     &Reply($client, "$outcome\n", $userinput);
                   4116: 
                   4117: 
                   4118:     return 1;
                   4119: }
                   4120: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   4121: 
                   4122: #
                   4123: #   Create a password for a new auto-enrollment user.
                   4124: #   I think/guess, this password allows access to the institutions 
                   4125: #   AIS class list server/services.  Stuart can correct this comment
                   4126: #   when he finds out how wrong I am.
                   4127: #
                   4128: # Formal Parameters:
                   4129: #    $cmd     - The command request that got us dispatched.
                   4130: #    $tail    - The tail of the command.   In this case this is a colon separated
                   4131: #               set of words that will be split into:
                   4132: #               $authparam - An authentication parameter (username??).
                   4133: #               $cdom      - The domain of the course from the institution's
                   4134: #                            point of view.
                   4135: #    $client  - The socket open on the client.
                   4136: # Returns:
                   4137: #    1 - continue processing.
                   4138: #
                   4139: sub create_auto_enroll_password_handler {
                   4140:     my ($cmd, $tail, $client) = @_;
                   4141:     my $userinput = "$cmd:$tail";
                   4142: 
                   4143:     my ($authparam, $cdom) = split(/:/, $userinput);
                   4144: 
                   4145:     my ($create_passwd,$authchk);
                   4146:     ($authparam,
                   4147:      $create_passwd,
                   4148:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   4149: 
                   4150:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   4151: 	   $userinput);
                   4152: 
                   4153: 
                   4154:     return 1;
                   4155: }
                   4156: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   4157: 		  0, 1, 0);
                   4158: 
                   4159: #   Retrieve and remove temporary files created by/during autoenrollment.
                   4160: #
                   4161: # Formal Parameters:
                   4162: #    $cmd      - The command that got us dispatched.
                   4163: #    $tail     - The tail of the command.  In our case this is a colon 
                   4164: #                separated list that will be split into:
                   4165: #                $filename - The name of the file to remove.
                   4166: #                            The filename is given as a path relative to
                   4167: #                            the LonCAPA temp file directory.
                   4168: #    $client   - Socket open on the client.
                   4169: #
                   4170: # Returns:
                   4171: #   1     - Continue processing.
                   4172: sub retrieve_auto_file_handler {
                   4173:     my ($cmd, $tail, $client)    = @_;
                   4174:     my $userinput                = "cmd:$tail";
                   4175: 
                   4176:     my ($filename)   = split(/:/, $tail);
                   4177: 
                   4178:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
                   4179:     if ( (-e $source) && ($filename ne '') ) {
                   4180: 	my $reply = '';
                   4181: 	if (open(my $fh,$source)) {
                   4182: 	    while (<$fh>) {
                   4183: 		chomp($_);
                   4184: 		$_ =~ s/^\s+//g;
                   4185: 		$_ =~ s/\s+$//g;
                   4186: 		$reply .= $_;
                   4187: 	    }
                   4188: 	    close($fh);
                   4189: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   4190: 
                   4191: #   Does this have to be uncommented??!?  (RF).
                   4192: #
                   4193: #                                unlink($source);
                   4194: 	} else {
                   4195: 	    &Failure($client, "error\n", $userinput);
                   4196: 	}
                   4197:     } else {
                   4198: 	&Failure($client, "error\n", $userinput);
                   4199:     }
                   4200:     
                   4201: 
                   4202:     return 1;
                   4203: }
                   4204: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   4205: 
                   4206: #
                   4207: #   Read and retrieve institutional code format (for support form).
                   4208: # Formal Parameters:
                   4209: #    $cmd        - Command that dispatched us.
                   4210: #    $tail       - Tail of the command.  In this case it conatins 
                   4211: #                  the course domain and the coursename.
                   4212: #    $client     - Socket open on the client.
                   4213: # Returns:
                   4214: #    1     - Continue processing.
                   4215: #
                   4216: sub get_institutional_code_format_handler {
                   4217:     my ($cmd, $tail, $client)   = @_;
                   4218:     my $userinput               = "$cmd:$tail";
                   4219: 
                   4220:     my $reply;
                   4221:     my($cdom,$course) = split(/:/,$tail);
                   4222:     my @pairs = split/\&/,$course;
                   4223:     my %instcodes = ();
                   4224:     my %codes = ();
                   4225:     my @codetitles = ();
                   4226:     my %cat_titles = ();
                   4227:     my %cat_order = ();
                   4228:     foreach (@pairs) {
                   4229: 	my ($key,$value) = split/=/,$_;
                   4230: 	$instcodes{&unescape($key)} = &unescape($value);
                   4231:     }
                   4232:     my $formatreply = &localenroll::instcode_format($cdom,
                   4233: 						    \%instcodes,
                   4234: 						    \%codes,
                   4235: 						    \@codetitles,
                   4236: 						    \%cat_titles,
                   4237: 						    \%cat_order);
                   4238:     if ($formatreply eq 'ok') {
                   4239: 	my $codes_str = &hash2str(%codes);
                   4240: 	my $codetitles_str = &array2str(@codetitles);
                   4241: 	my $cat_titles_str = &hash2str(%cat_titles);
                   4242: 	my $cat_order_str = &hash2str(%cat_order);
                   4243: 	&Reply($client,
                   4244: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   4245: 	       .$cat_order_str."\n",
                   4246: 	       $userinput);
                   4247:     } else {
                   4248: 	# this else branch added by RF since if not ok, lonc will
                   4249: 	# hang waiting on reply until timeout.
                   4250: 	#
                   4251: 	&Reply($client, "format_error\n", $userinput);
                   4252:     }
                   4253:     
                   4254:     return 1;
                   4255: }
1.265     albertel 4256: &register_handler("autoinstcodeformat",
                   4257: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     4258: 
1.317     raeburn  4259: # Get domain specific conditions for import of student photographs to a course
                   4260: #
                   4261: # Retrieves information from photo_permission subroutine in localenroll.
                   4262: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   4263: # required to accept conditions of use (yes/no).
                   4264: #
                   4265: #    
                   4266: sub photo_permission_handler {
                   4267:     my ($cmd, $tail, $client)   = @_;
                   4268:     my $userinput               = "$cmd:$tail";
                   4269:     my $cdom = $tail;
                   4270:     my ($perm_reqd,$conditions);
1.320     albertel 4271:     my $outcome;
                   4272:     eval {
                   4273: 	local($SIG{__DIE__})='DEFAULT';
                   4274: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   4275: 						  \$conditions);
                   4276:     };
                   4277:     if (!$@) {
                   4278: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   4279: 	       $userinput);
                   4280:     } else {
                   4281: 	&Failure($client,"unknown_cmd\n",$userinput);
                   4282:     }
                   4283:     return 1;
1.317     raeburn  4284: }
                   4285: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   4286: 
                   4287: #
                   4288: # Checks if student photo is available for a user in the domain, in the user's
                   4289: # directory (in /userfiles/internal/studentphoto.jpg).
                   4290: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   4291: # the student's photo.   
                   4292: 
                   4293: sub photo_check_handler {
                   4294:     my ($cmd, $tail, $client)   = @_;
                   4295:     my $userinput               = "$cmd:$tail";
                   4296:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   4297:     $udom = &unescape($udom);
                   4298:     $uname = &unescape($uname);
                   4299:     $pid = &unescape($pid);
                   4300:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   4301:     if (!-e $path) {
                   4302:         &mkpath($path);
                   4303:     }
                   4304:     my $response;
                   4305:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   4306:     $result .= ':'.$response;
                   4307:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 4308:     return 1;
1.317     raeburn  4309: }
                   4310: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   4311: 
                   4312: #
                   4313: # Retrieve information from localenroll about whether to provide a button     
                   4314: # for users who have enbled import of student photos to initiate an 
                   4315: # update of photo files for registered students. Also include 
                   4316: # comment to display alongside button.  
                   4317: 
                   4318: sub photo_choice_handler {
                   4319:     my ($cmd, $tail, $client) = @_;
                   4320:     my $userinput             = "$cmd:$tail";
                   4321:     my $cdom                  = &unescape($tail);
1.320     albertel 4322:     my ($update,$comment);
                   4323:     eval {
                   4324: 	local($SIG{__DIE__})='DEFAULT';
                   4325: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   4326:     };
                   4327:     if (!$@) {
                   4328: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   4329:     } else {
                   4330: 	&Failure($client,"unknown_cmd\n",$userinput);
                   4331:     }
                   4332:     return 1;
1.317     raeburn  4333: }
                   4334: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   4335: 
1.265     albertel 4336: #
                   4337: # Gets a student's photo to exist (in the correct image type) in the user's 
                   4338: # directory.
                   4339: # Formal Parameters:
                   4340: #    $cmd     - The command request that got us dispatched.
                   4341: #    $tail    - A colon separated set of words that will be split into:
                   4342: #               $domain - student's domain
                   4343: #               $uname  - student username
                   4344: #               $type   - image type desired
                   4345: #    $client  - The socket open on the client.
                   4346: # Returns:
                   4347: #    1 - continue processing.
1.317     raeburn  4348: 
1.265     albertel 4349: sub student_photo_handler {
                   4350:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  4351:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 4352: 
1.317     raeburn  4353:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   4354:     my $filename = 'studentphoto.'.$ext;
                   4355:     if ($type eq 'thumbnail') {
                   4356:         $filename = 'studentphoto_tn.'.$ext;
                   4357:     }
                   4358:     if (-e $path.$filename) {
1.265     albertel 4359: 	&Reply($client,"ok\n","$cmd:$tail");
                   4360: 	return 1;
                   4361:     }
                   4362:     &mkpath($path);
1.317     raeburn  4363:     my $file;
                   4364:     if ($type eq 'thumbnail') {
1.320     albertel 4365: 	eval {
                   4366: 	    local($SIG{__DIE__})='DEFAULT';
                   4367: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   4368: 	};
1.317     raeburn  4369:     } else {
                   4370:         $file=&localstudentphoto::fetch($domain,$uname);
                   4371:     }
1.265     albertel 4372:     if (!$file) {
                   4373: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   4374: 	return 1;
                   4375:     }
1.317     raeburn  4376:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   4377:     if (-e $path.$filename) {
1.265     albertel 4378: 	&Reply($client,"ok\n","$cmd:$tail");
                   4379: 	return 1;
                   4380:     }
                   4381:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   4382:     return 1;
                   4383: }
                   4384: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     4385: 
1.264     albertel 4386: # mkpath makes all directories for a file, expects an absolute path with a
                   4387: # file or a trailing / if just a dir is passed
                   4388: # returns 1 on success 0 on failure
                   4389: sub mkpath {
                   4390:     my ($file)=@_;
                   4391:     my @parts=split(/\//,$file,-1);
                   4392:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   4393:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 4394: 	$now.='/'.$parts[$i]; 
1.264     albertel 4395: 	if (!-e $now) {
                   4396: 	    if  (!mkdir($now,0770)) { return 0; }
                   4397: 	}
                   4398:     }
                   4399:     return 1;
                   4400: }
                   4401: 
1.207     foxr     4402: #---------------------------------------------------------------
                   4403: #
                   4404: #   Getting, decoding and dispatching requests:
                   4405: #
                   4406: #
                   4407: #   Get a Request:
                   4408: #   Gets a Request message from the client.  The transaction
                   4409: #   is defined as a 'line' of text.  We remove the new line
                   4410: #   from the text line.  
1.226     foxr     4411: #
1.211     albertel 4412: sub get_request {
1.207     foxr     4413:     my $input = <$client>;
                   4414:     chomp($input);
1.226     foxr     4415: 
1.234     foxr     4416:     &Debug("get_request: Request = $input\n");
1.207     foxr     4417: 
                   4418:     &status('Processing '.$clientname.':'.$input);
                   4419: 
                   4420:     return $input;
                   4421: }
1.212     foxr     4422: #---------------------------------------------------------------
                   4423: #
                   4424: #  Process a request.  This sub should shrink as each action
                   4425: #  gets farmed out into a separat sub that is registered 
                   4426: #  with the dispatch hash.  
                   4427: #
                   4428: # Parameters:
                   4429: #    user_input   - The request received from the client (lonc).
                   4430: # Returns:
                   4431: #    true to keep processing, false if caller should exit.
                   4432: #
                   4433: sub process_request {
                   4434:     my ($userinput) = @_;      # Easier for now to break style than to
                   4435:                                 # fix all the userinput -> user_input.
                   4436:     my $wasenc    = 0;		# True if request was encrypted.
                   4437: # ------------------------------------------------------------ See if encrypted
1.322     albertel 4438:     # for command
                   4439:     # sethost:<server>
                   4440:     # <command>:<args>
                   4441:     #   we just send it to the processor
                   4442:     # for
                   4443:     # sethost:<server>:<command>:<args>
                   4444:     #  we do the implict set host and then do the command
                   4445:     if ($userinput =~ /^sethost:/) {
                   4446: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   4447: 	if (defined($userinput)) {
                   4448: 	    &sethost("$cmd:$newid");
                   4449: 	} else {
                   4450: 	    $userinput = "$cmd:$newid";
                   4451: 	}
                   4452:     }
                   4453: 
1.212     foxr     4454:     if ($userinput =~ /^enc/) {
                   4455: 	$userinput = decipher($userinput);
                   4456: 	$wasenc=1;
                   4457: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     4458: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     4459: 	    return 0;
                   4460: 	}
                   4461:     }
                   4462:     Debug("process_request: $userinput\n");
                   4463:     
1.213     foxr     4464:     #  
                   4465:     #   The 'correct way' to add a command to lond is now to
                   4466:     #   write a sub to execute it and Add it to the command dispatch
                   4467:     #   hash via a call to register_handler..  The comments to that
                   4468:     #   sub should give you enough to go on to show how to do this
                   4469:     #   along with the examples that are building up as this code
                   4470:     #   is getting refactored.   Until all branches of the
                   4471:     #   if/elseif monster below have been factored out into
                   4472:     #   separate procesor subs, if the dispatch hash is missing
                   4473:     #   the command keyword, we will fall through to the remainder
                   4474:     #   of the if/else chain below in order to keep this thing in 
                   4475:     #   working order throughout the transmogrification.
                   4476: 
                   4477:     my ($command, $tail) = split(/:/, $userinput, 2);
                   4478:     chomp($command);
                   4479:     chomp($tail);
                   4480:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     4481:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   4482:     if(!$tail) {
                   4483: 	$tail ="";		# defined but blank.
                   4484:     }
1.213     foxr     4485: 
                   4486:     &Debug("Command received: $command, encoded = $wasenc");
                   4487: 
                   4488:     if(defined $Dispatcher{$command}) {
                   4489: 
                   4490: 	my $dispatch_info = $Dispatcher{$command};
                   4491: 	my $handler       = $$dispatch_info[0];
                   4492: 	my $need_encode   = $$dispatch_info[1];
                   4493: 	my $client_types  = $$dispatch_info[2];
                   4494: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   4495: 	      ."ClientType $client_types");
                   4496:       
                   4497: 	#  Validate the request:
                   4498:       
                   4499: 	my $ok = 1;
                   4500: 	my $requesterprivs = 0;
                   4501: 	if(&isClient()) {
                   4502: 	    $requesterprivs |= $CLIENT_OK;
                   4503: 	}
                   4504: 	if(&isManager()) {
                   4505: 	    $requesterprivs |= $MANAGER_OK;
                   4506: 	}
                   4507: 	if($need_encode && (!$wasenc)) {
                   4508: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   4509: 	    $ok = 0;
                   4510: 	}
                   4511: 	if(($client_types & $requesterprivs) == 0) {
                   4512: 	    Debug("Client not privileged to do this operation");
                   4513: 	    $ok = 0;
                   4514: 	}
                   4515: 
                   4516: 	if($ok) {
                   4517: 	    Debug("Dispatching to handler $command $tail");
                   4518: 	    my $keep_going = &$handler($command, $tail, $client);
                   4519: 	    return $keep_going;
                   4520: 	} else {
                   4521: 	    Debug("Refusing to dispatch because client did not match requirements");
                   4522: 	    Failure($client, "refused\n", $userinput);
                   4523: 	    return 1;
                   4524: 	}
                   4525: 
                   4526:     }    
                   4527: 
1.262     foxr     4528:     print $client "unknown_cmd\n";
1.212     foxr     4529: # -------------------------------------------------------------------- complete
                   4530:     Debug("process_request - returning 1");
                   4531:     return 1;
                   4532: }
1.207     foxr     4533: #
                   4534: #   Decipher encoded traffic
                   4535: #  Parameters:
                   4536: #     input      - Encoded data.
                   4537: #  Returns:
                   4538: #     Decoded data or undef if encryption key was not yet negotiated.
                   4539: #  Implicit input:
                   4540: #     cipher  - This global holds the negotiated encryption key.
                   4541: #
1.211     albertel 4542: sub decipher {
1.207     foxr     4543:     my ($input)  = @_;
                   4544:     my $output = '';
1.212     foxr     4545:     
                   4546:     
1.207     foxr     4547:     if($cipher) {
                   4548: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   4549: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   4550: 	    $output .= 
                   4551: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   4552: 	}
                   4553: 	return substr($output, 0, $enclength);
                   4554:     } else {
                   4555: 	return undef;
                   4556:     }
                   4557: }
                   4558: 
                   4559: #
                   4560: #   Register a command processor.  This function is invoked to register a sub
                   4561: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   4562: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   4563: #   as well:
                   4564: #    - Is the keyword recognized.
                   4565: #    - Is the proper client type attempting the request.
                   4566: #    - Is the request encrypted if it has to be.
                   4567: #   Parameters:
                   4568: #    $request_name         - Name of the request being registered.
                   4569: #                           This is the command request that will match
                   4570: #                           against the hash keywords to lookup the information
                   4571: #                           associated with the dispatch information.
                   4572: #    $procedure           - Reference to a sub to call to process the request.
                   4573: #                           All subs get called as follows:
                   4574: #                             Procedure($cmd, $tail, $replyfd, $key)
                   4575: #                             $cmd    - the actual keyword that invoked us.
                   4576: #                             $tail   - the tail of the request that invoked us.
                   4577: #                             $replyfd- File descriptor connected to the client
                   4578: #    $must_encode          - True if the request must be encoded to be good.
                   4579: #    $client_ok            - True if it's ok for a client to request this.
                   4580: #    $manager_ok           - True if it's ok for a manager to request this.
                   4581: # Side effects:
                   4582: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   4583: #      - On failure, the program will die as it's a bad internal bug to try to 
                   4584: #        register a duplicate command handler.
                   4585: #
1.211     albertel 4586: sub register_handler {
1.212     foxr     4587:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     4588: 
                   4589:     #  Don't allow duplication#
                   4590:    
                   4591:     if (defined $Dispatcher{$request_name}) {
                   4592: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   4593:     }
                   4594:     #   Build the client type mask:
                   4595:     
                   4596:     my $client_type_mask = 0;
                   4597:     if($client_ok) {
                   4598: 	$client_type_mask  |= $CLIENT_OK;
                   4599:     }
                   4600:     if($manager_ok) {
                   4601: 	$client_type_mask  |= $MANAGER_OK;
                   4602:     }
                   4603:    
                   4604:     #  Enter the hash:
                   4605:       
                   4606:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   4607:    
                   4608:     $Dispatcher{$request_name} = \@entry;
                   4609:    
                   4610: }
                   4611: 
                   4612: 
                   4613: #------------------------------------------------------------------
                   4614: 
                   4615: 
                   4616: 
                   4617: 
1.141     foxr     4618: #
1.96      foxr     4619: #  Convert an error return code from lcpasswd to a string value.
                   4620: #
                   4621: sub lcpasswdstrerror {
                   4622:     my $ErrorCode = shift;
1.97      foxr     4623:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     4624: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   4625:     } else {
1.98      foxr     4626: 	return $passwderrors[$ErrorCode];
1.96      foxr     4627:     }
                   4628: }
                   4629: 
1.97      foxr     4630: #
                   4631: # Convert an error return code from lcuseradd to a string value:
                   4632: #
                   4633: sub lcuseraddstrerror {
                   4634:     my $ErrorCode = shift;
                   4635:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
                   4636: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
                   4637:     } else {
1.98      foxr     4638: 	return $adderrors[$ErrorCode];
1.97      foxr     4639:     }
                   4640: }
                   4641: 
1.23      harris41 4642: # grabs exception and records it to log before exiting
                   4643: sub catchexception {
1.27      albertel 4644:     my ($error)=@_;
1.25      www      4645:     $SIG{'QUIT'}='DEFAULT';
                   4646:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 4647:     &status("Catching exception");
1.190     albertel 4648:     &logthis("<font color='red'>CRITICAL: "
1.134     albertel 4649:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27      albertel 4650:      ."a crash with this error msg->[$error]</font>");
1.57      www      4651:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 4652:     if ($client) { print $client "error: $error\n"; }
1.59      www      4653:     $server->close();
1.27      albertel 4654:     die($error);
1.23      harris41 4655: }
1.63      www      4656: sub timeout {
1.165     albertel 4657:     &status("Handling Timeout");
1.190     albertel 4658:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      4659:     &catchexception('Timeout');
                   4660: }
1.22      harris41 4661: # -------------------------------- Set signal handlers to record abnormal exits
                   4662: 
1.226     foxr     4663: 
1.22      harris41 4664: $SIG{'QUIT'}=\&catchexception;
                   4665: $SIG{__DIE__}=\&catchexception;
                   4666: 
1.81      matthew  4667: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 4668: &status("Read loncapa.conf and loncapa_apache.conf");
                   4669: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     4670: %perlvar=%{$perlvarref};
1.80      harris41 4671: undef $perlvarref;
1.19      www      4672: 
1.35      harris41 4673: # ----------------------------- Make sure this process is running from user=www
                   4674: my $wwwid=getpwnam('www');
                   4675: if ($wwwid!=$<) {
1.134     albertel 4676:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4677:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 4678:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 4679:  mailto $emailto -s '$subj' > /dev/null");
                   4680:    exit 1;
                   4681: }
                   4682: 
1.19      www      4683: # --------------------------------------------- Check if other instance running
                   4684: 
                   4685: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   4686: 
                   4687: if (-e $pidfile) {
                   4688:    my $lfh=IO::File->new("$pidfile");
                   4689:    my $pide=<$lfh>;
                   4690:    chomp($pide);
1.29      harris41 4691:    if (kill 0 => $pide) { die "already running"; }
1.19      www      4692: }
1.1       albertel 4693: 
                   4694: # ------------------------------------------------------------- Read hosts file
                   4695: 
                   4696: 
                   4697: 
                   4698: # establish SERVER socket, bind and listen.
                   4699: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   4700:                                 Type      => SOCK_STREAM,
                   4701:                                 Proto     => 'tcp',
                   4702:                                 Reuse     => 1,
                   4703:                                 Listen    => 10 )
1.29      harris41 4704:   or die "making socket: $@\n";
1.1       albertel 4705: 
                   4706: # --------------------------------------------------------- Do global variables
                   4707: 
                   4708: # global variables
                   4709: 
1.134     albertel 4710: my %children               = ();       # keys are current child process IDs
1.1       albertel 4711: 
                   4712: sub REAPER {                        # takes care of dead children
                   4713:     $SIG{CHLD} = \&REAPER;
1.165     albertel 4714:     &status("Handling child death");
1.178     foxr     4715:     my $pid;
                   4716:     do {
                   4717: 	$pid = waitpid(-1,&WNOHANG());
                   4718: 	if (defined($children{$pid})) {
                   4719: 	    &logthis("Child $pid died");
                   4720: 	    delete($children{$pid});
1.183     albertel 4721: 	} elsif ($pid > 0) {
1.178     foxr     4722: 	    &logthis("Unknown Child $pid died");
                   4723: 	}
                   4724:     } while ( $pid > 0 );
                   4725:     foreach my $child (keys(%children)) {
                   4726: 	$pid = waitpid($child,&WNOHANG());
                   4727: 	if ($pid > 0) {
                   4728: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   4729: 	    delete($children{$pid});
                   4730: 	}
1.176     albertel 4731:     }
1.165     albertel 4732:     &status("Finished Handling child death");
1.1       albertel 4733: }
                   4734: 
                   4735: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 4736:     &status("Killing children (INT)");
1.1       albertel 4737:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   4738:     kill 'INT' => keys %children;
1.59      www      4739:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 4740:     my $execdir=$perlvar{'lonDaemons'};
                   4741:     unlink("$execdir/logs/lond.pid");
1.190     albertel 4742:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 4743:     &status("Done killing children");
1.1       albertel 4744:     exit;                           # clean up with dignity
                   4745: }
                   4746: 
                   4747: sub HUPSMAN {                      # signal handler for SIGHUP
                   4748:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 4749:     &status("Killing children for restart (HUP)");
1.1       albertel 4750:     kill 'INT' => keys %children;
1.59      www      4751:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 4752:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 4753:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 4754:     unlink("$execdir/logs/lond.pid");
1.165     albertel 4755:     &status("Restarting self (HUP)");
1.1       albertel 4756:     exec("$execdir/lond");         # here we go again
                   4757: }
                   4758: 
1.144     foxr     4759: #
1.148     foxr     4760: #    Kill off hashes that describe the host table prior to re-reading it.
                   4761: #    Hashes affected are:
1.200     matthew  4762: #       %hostid, %hostdom %hostip %hostdns.
1.148     foxr     4763: #
                   4764: sub KillHostHashes {
                   4765:     foreach my $key (keys %hostid) {
                   4766: 	delete $hostid{$key};
                   4767:     }
                   4768:     foreach my $key (keys %hostdom) {
                   4769: 	delete $hostdom{$key};
                   4770:     }
                   4771:     foreach my $key (keys %hostip) {
                   4772: 	delete $hostip{$key};
                   4773:     }
1.200     matthew  4774:     foreach my $key (keys %hostdns) {
                   4775: 	delete $hostdns{$key};
                   4776:     }
1.148     foxr     4777: }
                   4778: #
                   4779: #   Read in the host table from file and distribute it into the various hashes:
                   4780: #
                   4781: #    - %hostid  -  Indexed by IP, the loncapa hostname.
                   4782: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
                   4783: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
                   4784: sub ReadHostTable {
                   4785: 
                   4786:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200     matthew  4787:     my $myloncapaname = $perlvar{'lonHostID'};
                   4788:     Debug("My loncapa name is : $myloncapaname");
1.296     albertel 4789:     my %name_to_ip;
1.148     foxr     4790:     while (my $configline=<CONFIG>) {
1.277     albertel 4791: 	if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
                   4792: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   4793: 	    $name=~s/\s//g;
1.296     albertel 4794: 	    my $ip;
                   4795: 	    if (!exists($name_to_ip{$name})) {
                   4796: 		$ip = gethostbyname($name);
                   4797: 		if (!$ip || length($ip) ne 4) {
                   4798: 		    &logthis("Skipping host $id name $name no IP found\n");
                   4799: 		    next;
                   4800: 		}
                   4801: 		$ip=inet_ntoa($ip);
                   4802: 		$name_to_ip{$name} = $ip;
                   4803: 	    } else {
                   4804: 		$ip = $name_to_ip{$name};
1.277     albertel 4805: 	    }
1.200     matthew  4806: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
                   4807: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
1.307     albertel 4808: 	    $hostname{$id}=$name;     # LonCAPA name -> DNS name
1.277     albertel 4809: 	    $hostip{$id}=$ip;         # IP address of host.
1.200     matthew  4810: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
                   4811: 
                   4812: 	    if ($id eq $perlvar{'lonHostID'}) { 
                   4813: 		Debug("Found me in the host table: $name");
                   4814: 		$thisserver=$name; 
                   4815: 	    }
1.178     foxr     4816: 	}
1.148     foxr     4817:     }
                   4818:     close(CONFIG);
                   4819: }
                   4820: #
                   4821: #  Reload the Apache daemon's state.
1.150     foxr     4822: #  This is done by invoking /home/httpd/perl/apachereload
                   4823: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     4824: #
                   4825: sub ReloadApache {
1.150     foxr     4826:     my $execdir = $perlvar{'lonDaemons'};
                   4827:     my $script  = $execdir."/apachereload";
                   4828:     system($script);
1.148     foxr     4829: }
                   4830: 
                   4831: #
1.144     foxr     4832: #   Called in response to a USR2 signal.
                   4833: #   - Reread hosts.tab
                   4834: #   - All children connected to hosts that were removed from hosts.tab
                   4835: #     are killed via SIGINT
                   4836: #   - All children connected to previously existing hosts are sent SIGUSR1
                   4837: #   - Our internal hosts hash is updated to reflect the new contents of
                   4838: #     hosts.tab causing connections from hosts added to hosts.tab to
                   4839: #     now be honored.
                   4840: #
                   4841: sub UpdateHosts {
1.165     albertel 4842:     &status("Reload hosts.tab");
1.147     foxr     4843:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     4844:     #
                   4845:     #  The %children hash has the set of IP's we currently have children
                   4846:     #  on.  These need to be matched against records in the hosts.tab
                   4847:     #  Any ip's no longer in the table get killed off they correspond to
                   4848:     #  either dropped or changed hosts.  Note that the re-read of the table
                   4849:     #  will take care of new and changed hosts as connections come into being.
                   4850: 
                   4851: 
                   4852:     KillHostHashes;
                   4853:     ReadHostTable;
                   4854: 
                   4855:     foreach my $child (keys %children) {
                   4856: 	my $childip = $children{$child};
                   4857: 	if(!$hostid{$childip}) {
1.149     foxr     4858: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   4859: 		    ." $child for ip $childip </font>");
1.148     foxr     4860: 	    kill('INT', $child);
1.149     foxr     4861: 	} else {
                   4862: 	    logthis('<font color="green"> keeping child for ip '
                   4863: 		    ." $childip (pid=$child) </font>");
1.148     foxr     4864: 	}
                   4865:     }
                   4866:     ReloadApache;
1.165     albertel 4867:     &status("Finished reloading hosts.tab");
1.144     foxr     4868: }
                   4869: 
1.148     foxr     4870: 
1.57      www      4871: sub checkchildren {
1.165     albertel 4872:     &status("Checking on the children (sending signals)");
1.57      www      4873:     &initnewstatus();
                   4874:     &logstatus();
                   4875:     &logthis('Going to check on the children');
1.134     albertel 4876:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 4877:     foreach (sort keys %children) {
1.221     albertel 4878: 	#sleep 1;
1.57      www      4879:         unless (kill 'USR1' => $_) {
                   4880: 	    &logthis ('Child '.$_.' is dead');
                   4881:             &logstatus($$.' is dead');
1.221     albertel 4882: 	    delete($children{$_});
1.57      www      4883:         } 
1.61      harris41 4884:     }
1.63      www      4885:     sleep 5;
1.212     foxr     4886:     $SIG{ALRM} = sub { Debug("timeout"); 
                   4887: 		       die "timeout";  };
1.113     albertel 4888:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 4889:     &status("Checking on the children (waiting for reports)");
1.63      www      4890:     foreach (sort keys %children) {
                   4891:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 4892:           eval {
                   4893:             alarm(300);
1.63      www      4894: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 4895: 	    kill 9 => $_;
1.131     albertel 4896: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4897: 	    #$subj="LON: $currenthostid killed lond process $_";
                   4898: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   4899: 	    #$execdir=$perlvar{'lonDaemons'};
                   4900: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 4901: 	    delete($children{$_});
1.113     albertel 4902: 	    alarm(0);
                   4903: 	  }
1.63      www      4904:         }
                   4905:     }
1.113     albertel 4906:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 4907:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 4908:     &status("Finished checking children");
1.221     albertel 4909:     &logthis('Finished Checking children');
1.57      www      4910: }
                   4911: 
1.1       albertel 4912: # --------------------------------------------------------------------- Logging
                   4913: 
                   4914: sub logthis {
                   4915:     my $message=shift;
                   4916:     my $execdir=$perlvar{'lonDaemons'};
                   4917:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   4918:     my $now=time;
                   4919:     my $local=localtime($now);
1.58      www      4920:     $lastlog=$local.': '.$message;
1.1       albertel 4921:     print $fh "$local ($$): $message\n";
                   4922: }
                   4923: 
1.77      foxr     4924: # ------------------------- Conditional log if $DEBUG true.
                   4925: sub Debug {
                   4926:     my $message = shift;
                   4927:     if($DEBUG) {
                   4928: 	&logthis($message);
                   4929:     }
                   4930: }
1.161     foxr     4931: 
                   4932: #
                   4933: #   Sub to do replies to client.. this gives a hook for some
                   4934: #   debug tracing too:
                   4935: #  Parameters:
                   4936: #     fd      - File open on client.
                   4937: #     reply   - Text to send to client.
                   4938: #     request - Original request from client.
                   4939: #
                   4940: sub Reply {
1.192     foxr     4941:     my ($fd, $reply, $request) = @_;
1.161     foxr     4942:     print $fd $reply;
                   4943:     Debug("Request was $request  Reply was $reply");
                   4944: 
1.212     foxr     4945:     $Transactions++;
                   4946: }
                   4947: 
                   4948: 
                   4949: #
                   4950: #    Sub to report a failure.
                   4951: #    This function:
                   4952: #     -   Increments the failure statistic counters.
                   4953: #     -   Invokes Reply to send the error message to the client.
                   4954: # Parameters:
                   4955: #    fd       - File descriptor open on the client
                   4956: #    reply    - Reply text to emit.
                   4957: #    request  - The original request message (used by Reply
                   4958: #               to debug if that's enabled.
                   4959: # Implicit outputs:
                   4960: #    $Failures- The number of failures is incremented.
                   4961: #    Reply (invoked here) sends a message to the 
                   4962: #    client:
                   4963: #
                   4964: sub Failure {
                   4965:     my $fd      = shift;
                   4966:     my $reply   = shift;
                   4967:     my $request = shift;
                   4968:    
                   4969:     $Failures++;
                   4970:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     4971: }
1.57      www      4972: # ------------------------------------------------------------------ Log status
                   4973: 
                   4974: sub logstatus {
1.178     foxr     4975:     &status("Doing logging");
                   4976:     my $docdir=$perlvar{'lonDocRoot'};
                   4977:     {
                   4978: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  4979:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     4980:         $fh->close();
                   4981:     }
1.221     albertel 4982:     &status("Finished $$.txt");
                   4983:     {
                   4984: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   4985: 	flock(LOG,LOCK_EX);
                   4986: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   4987: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 4988: 	flock(LOG,LOCK_UN);
1.221     albertel 4989: 	close(LOG);
                   4990:     }
1.178     foxr     4991:     &status("Finished logging");
1.57      www      4992: }
                   4993: 
                   4994: sub initnewstatus {
                   4995:     my $docdir=$perlvar{'lonDocRoot'};
                   4996:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
                   4997:     my $now=time;
                   4998:     my $local=localtime($now);
                   4999:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      5000:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 5001:     while (my $filename=readdir(DIR)) {
1.64      www      5002:         unlink("$docdir/lon-status/londchld/$filename");
                   5003:     }
                   5004:     closedir(DIR);
1.57      www      5005: }
                   5006: 
                   5007: # -------------------------------------------------------------- Status setting
                   5008: 
                   5009: sub status {
                   5010:     my $what=shift;
                   5011:     my $now=time;
                   5012:     my $local=localtime($now);
1.178     foxr     5013:     $status=$local.': '.$what;
                   5014:     $0='lond: '.$what.' '.$local;
1.57      www      5015: }
1.11      www      5016: 
1.1       albertel 5017: # ----------------------------------------------------------- Send USR1 to lonc
                   5018: 
                   5019: sub reconlonc {
                   5020:     my $peerfile=shift;
                   5021:     &logthis("Trying to reconnect for $peerfile");
                   5022:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                   5023:     if (my $fh=IO::File->new("$loncfile")) {
                   5024: 	my $loncpid=<$fh>;
                   5025:         chomp($loncpid);
                   5026:         if (kill 0 => $loncpid) {
                   5027: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                   5028:             kill USR1 => $loncpid;
                   5029:         } else {
1.9       www      5030: 	    &logthis(
1.190     albertel 5031:               "<font color='red'>CRITICAL: "
1.9       www      5032:              ."lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel 5033:         }
                   5034:     } else {
1.190     albertel 5035:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1       albertel 5036:     }
                   5037: }
                   5038: 
                   5039: # -------------------------------------------------- Non-critical communication
1.11      www      5040: 
1.1       albertel 5041: sub subreply {
                   5042:     my ($cmd,$server)=@_;
1.307     albertel 5043:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.1       albertel 5044:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   5045:                                       Type    => SOCK_STREAM,
                   5046:                                       Timeout => 10)
                   5047:        or return "con_lost";
1.307     albertel 5048:     print $sclient "sethost:$server:$cmd\n";
1.1       albertel 5049:     my $answer=<$sclient>;
                   5050:     chomp($answer);
                   5051:     if (!$answer) { $answer="con_lost"; }
                   5052:     return $answer;
                   5053: }
                   5054: 
                   5055: sub reply {
                   5056:   my ($cmd,$server)=@_;
                   5057:   my $answer;
1.115     albertel 5058:   if ($server ne $currenthostid) { 
1.1       albertel 5059:     $answer=subreply($cmd,$server);
                   5060:     if ($answer eq 'con_lost') {
                   5061: 	$answer=subreply("ping",$server);
                   5062:         if ($answer ne $server) {
1.115     albertel 5063: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
1.307     albertel 5064:            &reconlonc("$perlvar{'lonSockDir'}/".$hostname{$server});
1.1       albertel 5065:         }
                   5066:         $answer=subreply($cmd,$server);
                   5067:     }
                   5068:   } else {
                   5069:     $answer='self_reply';
                   5070:   } 
                   5071:   return $answer;
                   5072: }
                   5073: 
1.13      www      5074: # -------------------------------------------------------------- Talk to lonsql
                   5075: 
1.234     foxr     5076: sub sql_reply {
1.12      harris41 5077:     my ($cmd)=@_;
1.234     foxr     5078:     my $answer=&sub_sql_reply($cmd);
                   5079:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 5080:     return $answer;
                   5081: }
                   5082: 
1.234     foxr     5083: sub sub_sql_reply {
1.12      harris41 5084:     my ($cmd)=@_;
                   5085:     my $unixsock="mysqlsock";
                   5086:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   5087:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   5088:                                       Type    => SOCK_STREAM,
                   5089:                                       Timeout => 10)
                   5090:        or return "con_lost";
1.319     www      5091:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 5092:     my $answer=<$sclient>;
                   5093:     chomp($answer);
                   5094:     if (!$answer) { $answer="con_lost"; }
                   5095:     return $answer;
                   5096: }
                   5097: 
1.1       albertel 5098: # --------------------------------------- Is this the home server of an author?
1.11      www      5099: 
1.1       albertel 5100: sub ishome {
                   5101:     my $author=shift;
                   5102:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   5103:     my ($udom,$uname)=split(/\//,$author);
                   5104:     my $proname=propath($udom,$uname);
                   5105:     if (-e $proname) {
                   5106: 	return 'owner';
                   5107:     } else {
                   5108:         return 'not_owner';
                   5109:     }
                   5110: }
                   5111: 
                   5112: # ======================================================= Continue main program
                   5113: # ---------------------------------------------------- Fork once and dissociate
                   5114: 
1.134     albertel 5115: my $fpid=fork;
1.1       albertel 5116: exit if $fpid;
1.29      harris41 5117: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 5118: 
1.29      harris41 5119: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 5120: 
                   5121: # ------------------------------------------------------- Write our PID on disk
                   5122: 
1.134     albertel 5123: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 5124: open (PIDSAVE,">$execdir/logs/lond.pid");
                   5125: print PIDSAVE "$$\n";
                   5126: close(PIDSAVE);
1.190     albertel 5127: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      5128: &status('Starting');
1.1       albertel 5129: 
1.106     foxr     5130: 
1.1       albertel 5131: 
                   5132: # ----------------------------------------------------- Install signal handlers
                   5133: 
1.57      www      5134: 
1.1       albertel 5135: $SIG{CHLD} = \&REAPER;
                   5136: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   5137: $SIG{HUP}  = \&HUPSMAN;
1.57      www      5138: $SIG{USR1} = \&checkchildren;
1.144     foxr     5139: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     5140: 
1.148     foxr     5141: #  Read the host hashes:
                   5142: 
                   5143: ReadHostTable;
1.106     foxr     5144: 
1.286     albertel 5145: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
                   5146: 
1.106     foxr     5147: # --------------------------------------------------------------
                   5148: #   Accept connections.  When a connection comes in, it is validated
                   5149: #   and if good, a child process is created to process transactions
                   5150: #   along the connection.
                   5151: 
1.1       albertel 5152: while (1) {
1.165     albertel 5153:     &status('Starting accept');
1.106     foxr     5154:     $client = $server->accept() or next;
1.165     albertel 5155:     &status('Accepted '.$client.' off to spawn');
1.106     foxr     5156:     make_new_child($client);
1.165     albertel 5157:     &status('Finished spawning');
1.1       albertel 5158: }
                   5159: 
1.212     foxr     5160: sub make_new_child {
                   5161:     my $pid;
                   5162: #    my $cipher;     # Now global
                   5163:     my $sigset;
1.178     foxr     5164: 
1.212     foxr     5165:     $client = shift;
                   5166:     &status('Starting new child '.$client);
                   5167:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   5168: 	     ")</font>");    
                   5169:     # block signal for fork
                   5170:     $sigset = POSIX::SigSet->new(SIGINT);
                   5171:     sigprocmask(SIG_BLOCK, $sigset)
                   5172:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     5173: 
1.212     foxr     5174:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     5175: 
1.212     foxr     5176:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   5177: 	                               # connection liveness.
1.178     foxr     5178: 
1.212     foxr     5179:     #
                   5180:     #  Figure out who we're talking to so we can record the peer in 
                   5181:     #  the pid hash.
                   5182:     #
                   5183:     my $caller = getpeername($client);
                   5184:     my ($port,$iaddr);
                   5185:     if (defined($caller) && length($caller) > 0) {
                   5186: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   5187:     } else {
                   5188: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   5189:     }
                   5190:     if (defined($iaddr)) {
                   5191: 	$clientip  = inet_ntoa($iaddr);
                   5192: 	Debug("Connected with $clientip");
                   5193:     } else {
                   5194: 	&logthis("Unable to determine clientip");
                   5195: 	$clientip='Unavailable';
                   5196:     }
                   5197:     
                   5198:     if ($pid) {
                   5199:         # Parent records the child's birth and returns.
                   5200:         sigprocmask(SIG_UNBLOCK, $sigset)
                   5201:             or die "Can't unblock SIGINT for fork: $!\n";
                   5202:         $children{$pid} = $clientip;
                   5203:         &status('Started child '.$pid);
                   5204:         return;
                   5205:     } else {
                   5206:         # Child can *not* return from this subroutine.
                   5207:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   5208:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   5209:                                 #don't get intercepted
                   5210:         $SIG{USR1}= \&logstatus;
                   5211:         $SIG{ALRM}= \&timeout;
                   5212:         $lastlog='Forked ';
                   5213:         $status='Forked';
1.178     foxr     5214: 
1.212     foxr     5215:         # unblock signals
                   5216:         sigprocmask(SIG_UNBLOCK, $sigset)
                   5217:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     5218: 
1.212     foxr     5219: #        my $tmpsnum=0;            # Now global
                   5220: #---------------------------------------------------- kerberos 5 initialization
                   5221:         &Authen::Krb5::init_context();
1.297     raeburn  5222: 	unless (($dist eq 'fedora4') || ($dist eq 'suse9.3')) {
1.286     albertel 5223: 	    &Authen::Krb5::init_ets();
                   5224: 	}
1.209     albertel 5225: 
1.212     foxr     5226: 	&status('Accepted connection');
                   5227: # =============================================================================
                   5228:             # do something with the connection
                   5229: # -----------------------------------------------------------------------------
                   5230: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     5231: 
1.212     foxr     5232: 	ReadManagerTable;	# May also be a manager!!
                   5233: 	
1.278     albertel 5234: 	my $outsideip=$clientip;
                   5235: 	if ($clientip eq '127.0.0.1') {
                   5236: 	    $outsideip=$hostip{$perlvar{'lonHostID'}};
                   5237: 	}
                   5238: 
                   5239: 	my $clientrec=($hostid{$outsideip}     ne undef);
                   5240: 	my $ismanager=($managers{$outsideip}    ne undef);
1.212     foxr     5241: 	$clientname  = "[unknonwn]";
                   5242: 	if($clientrec) {	# Establish client type.
                   5243: 	    $ConnectionType = "client";
1.278     albertel 5244: 	    $clientname = $hostid{$outsideip};
1.212     foxr     5245: 	    if($ismanager) {
                   5246: 		$ConnectionType = "both";
                   5247: 	    }
                   5248: 	} else {
                   5249: 	    $ConnectionType = "manager";
1.278     albertel 5250: 	    $clientname = $managers{$outsideip};
1.212     foxr     5251: 	}
                   5252: 	my $clientok;
1.178     foxr     5253: 
1.212     foxr     5254: 	if ($clientrec || $ismanager) {
                   5255: 	    &status("Waiting for init from $clientip $clientname");
                   5256: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   5257: 		     $clientip.
                   5258: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   5259: 	    &status("Connecting $clientip  ($clientname))"); 
                   5260: 	    my $remotereq=<$client>;
                   5261: 	    chomp($remotereq);
                   5262: 	    Debug("Got init: $remotereq");
                   5263: 	    my $inikeyword = split(/:/, $remotereq);
                   5264: 	    if ($remotereq =~ /^init/) {
                   5265: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   5266: 		#
                   5267: 		#  If the remote is attempting a local init... give that a try:
                   5268: 		#
                   5269: 		my ($i, $inittype) = split(/:/, $remotereq);
1.209     albertel 5270: 
1.212     foxr     5271: 		# If the connection type is ssl, but I didn't get my
                   5272: 		# certificate files yet, then I'll drop  back to 
                   5273: 		# insecure (if allowed).
                   5274: 		
                   5275: 		if($inittype eq "ssl") {
                   5276: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   5277: 		    my $kfile       = lonssl::KeyFile;
                   5278: 		    if((!$ca)   || 
                   5279: 		       (!$cert) || 
                   5280: 		       (!$kfile)) {
                   5281: 			$inittype = ""; # This forces insecure attempt.
                   5282: 			&logthis("<font color=\"blue\"> Certificates not "
                   5283: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     5284: 		    } else {	# SSL certificates are in place so
1.212     foxr     5285: 		    }		# Leave the inittype alone.
                   5286: 		}
                   5287: 
                   5288: 		if($inittype eq "local") {
                   5289: 		    my $key = LocalConnection($client, $remotereq);
                   5290: 		    if($key) {
                   5291: 			Debug("Got local key $key");
                   5292: 			$clientok     = 1;
                   5293: 			my $cipherkey = pack("H32", $key);
                   5294: 			$cipher       = new IDEA($cipherkey);
                   5295: 			print $client "ok:local\n";
                   5296: 			&logthis('<font color="green"'
                   5297: 				 . "Successful local authentication </font>");
                   5298: 			$keymode = "local"
1.178     foxr     5299: 		    } else {
1.212     foxr     5300: 			Debug("Failed to get local key");
                   5301: 			$clientok = 0;
                   5302: 			shutdown($client, 3);
                   5303: 			close $client;
1.178     foxr     5304: 		    }
1.212     foxr     5305: 		} elsif ($inittype eq "ssl") {
                   5306: 		    my $key = SSLConnection($client);
                   5307: 		    if ($key) {
                   5308: 			$clientok = 1;
                   5309: 			my $cipherkey = pack("H32", $key);
                   5310: 			$cipher       = new IDEA($cipherkey);
                   5311: 			&logthis('<font color="green">'
                   5312: 				 ."Successfull ssl authentication with $clientname </font>");
                   5313: 			$keymode = "ssl";
                   5314: 	     
1.178     foxr     5315: 		    } else {
1.212     foxr     5316: 			$clientok = 0;
                   5317: 			close $client;
1.178     foxr     5318: 		    }
1.212     foxr     5319: 	   
                   5320: 		} else {
                   5321: 		    my $ok = InsecureConnection($client);
                   5322: 		    if($ok) {
                   5323: 			$clientok = 1;
                   5324: 			&logthis('<font color="green">'
                   5325: 				 ."Successful insecure authentication with $clientname </font>");
                   5326: 			print $client "ok\n";
                   5327: 			$keymode = "insecure";
1.178     foxr     5328: 		    } else {
1.212     foxr     5329: 			&logthis('<font color="yellow">'
                   5330: 				  ."Attempted insecure connection disallowed </font>");
                   5331: 			close $client;
                   5332: 			$clientok = 0;
1.178     foxr     5333: 			
                   5334: 		    }
                   5335: 		}
1.212     foxr     5336: 	    } else {
                   5337: 		&logthis(
                   5338: 			 "<font color='blue'>WARNING: "
                   5339: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   5340: 		&status('No init '.$clientip);
                   5341: 	    }
                   5342: 	    
                   5343: 	} else {
                   5344: 	    &logthis(
                   5345: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   5346: 	    &status('Hung up on '.$clientip);
                   5347: 	}
                   5348:  
                   5349: 	if ($clientok) {
                   5350: # ---------------- New known client connecting, could mean machine online again
                   5351: 	    
                   5352: 	    foreach my $id (keys(%hostip)) {
                   5353: 		if ($hostip{$id} ne $clientip ||
                   5354: 		    $hostip{$currenthostid} eq $clientip) {
                   5355: 		    # no need to try to do recon's to myself
                   5356: 		    next;
                   5357: 		}
1.307     albertel 5358: 		&reconlonc("$perlvar{'lonSockDir'}/".$hostname{$id});
1.212     foxr     5359: 	    }
                   5360: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   5361: 	    &status('Will listen to '.$clientname);
                   5362: # ------------------------------------------------------------ Process requests
                   5363: 	    my $keep_going = 1;
                   5364: 	    my $user_input;
                   5365: 	    while(($user_input = get_request) && $keep_going) {
                   5366: 		alarm(120);
                   5367: 		Debug("Main: Got $user_input\n");
                   5368: 		$keep_going = &process_request($user_input);
1.178     foxr     5369: 		alarm(0);
1.212     foxr     5370: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     5371: 	    }
1.212     foxr     5372: 
1.59      www      5373: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     5374: 	}  else {
1.161     foxr     5375: 	    print $client "refused\n";
                   5376: 	    $client->close();
1.190     albertel 5377: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     5378: 		     ."Rejected client $clientip, closing connection</font>");
                   5379: 	}
1.212     foxr     5380:     }            
1.161     foxr     5381:     
1.1       albertel 5382: # =============================================================================
1.161     foxr     5383:     
1.190     albertel 5384:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     5385: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   5386:     
                   5387:     
                   5388:     # this exit is VERY important, otherwise the child will become
                   5389:     # a producer of more and more children, forking yourself into
                   5390:     # process death.
                   5391:     exit;
1.106     foxr     5392:     
1.78      foxr     5393: }
1.261     foxr     5394: #
                   5395: #   Determine if a user is an author for the indicated domain.
                   5396: #
                   5397: # Parameters:
                   5398: #    domain          - domain to check in .
                   5399: #    user            - Name of user to check.
                   5400: #
                   5401: # Return:
                   5402: #     1             - User is an author for domain.
                   5403: #     0             - User is not an author for domain.
                   5404: sub is_author {
                   5405:     my ($domain, $user) = @_;
                   5406: 
                   5407:     &Debug("is_author: $user @ $domain");
                   5408: 
                   5409:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   5410: 				 &GDBM_READER());
                   5411: 
                   5412:     #  Author role should show up as a key /domain/_au
1.78      foxr     5413: 
1.321     albertel 5414:     my $key    = "/$domain/_au";
                   5415:     my $value;
                   5416:     if (defined($hashref)) {
                   5417: 	$value = $hashref->{$key};
                   5418:     }
1.78      foxr     5419: 
1.261     foxr     5420:     if(defined($value)) {
                   5421: 	&Debug("$user @ $domain is an author");
                   5422:     }
                   5423: 
                   5424:     return defined($value);
                   5425: }
1.78      foxr     5426: #
                   5427: #   Checks to see if the input roleput request was to set
                   5428: # an author role.  If so, invokes the lchtmldir script to set
                   5429: # up a correct public_html 
                   5430: # Parameters:
                   5431: #    request   - The request sent to the rolesput subchunk.
                   5432: #                We're looking for  /domain/_au
                   5433: #    domain    - The domain in which the user is having roles doctored.
                   5434: #    user      - Name of the user for which the role is being put.
                   5435: #    authtype  - The authentication type associated with the user.
                   5436: #
1.289     albertel 5437: sub manage_permissions {
1.192     foxr     5438:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     5439: 
1.261     foxr     5440:     &Debug("manage_permissions: $request $domain $user $authtype");
                   5441: 
1.78      foxr     5442:     # See if the request is of the form /$domain/_au
1.289     albertel 5443:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.78      foxr     5444: 	my $execdir = $perlvar{'lonDaemons'};
                   5445: 	my $userhome= "/home/$user" ;
1.134     albertel 5446: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261     foxr     5447: 	&Debug("Setting homedir permissions for $userhome");
1.78      foxr     5448: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   5449:     }
                   5450: }
1.222     foxr     5451: 
                   5452: 
                   5453: #
                   5454: #  Return the full path of a user password file, whether it exists or not.
                   5455: # Parameters:
                   5456: #   domain     - Domain in which the password file lives.
                   5457: #   user       - name of the user.
                   5458: # Returns:
                   5459: #    Full passwd path:
                   5460: #
                   5461: sub password_path {
                   5462:     my ($domain, $user) = @_;
1.264     albertel 5463:     return &propath($domain, $user).'/passwd';
1.222     foxr     5464: }
                   5465: 
                   5466: #   Password Filename
                   5467: #   Returns the path to a passwd file given domain and user... only if
                   5468: #  it exists.
                   5469: # Parameters:
                   5470: #   domain    - Domain in which to search.
                   5471: #   user      - username.
                   5472: # Returns:
                   5473: #   - If the password file exists returns its path.
                   5474: #   - If the password file does not exist, returns undefined.
                   5475: #
                   5476: sub password_filename {
                   5477:     my ($domain, $user) = @_;
                   5478: 
                   5479:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   5480: 
                   5481:     my $path  = &password_path($domain, $user);
                   5482:     Debug("PasswordFilename got path: $path");
                   5483:     if(-e $path) {
                   5484: 	return $path;
                   5485:     } else {
                   5486: 	return undef;
                   5487:     }
                   5488: }
                   5489: 
                   5490: #
                   5491: #   Rewrite the contents of the user's passwd file.
                   5492: #  Parameters:
                   5493: #    domain    - domain of the user.
                   5494: #    name      - User's name.
                   5495: #    contents  - New contents of the file.
                   5496: # Returns:
                   5497: #   0    - Failed.
                   5498: #   1    - Success.
                   5499: #
                   5500: sub rewrite_password_file {
                   5501:     my ($domain, $user, $contents) = @_;
                   5502: 
                   5503:     my $file = &password_filename($domain, $user);
                   5504:     if (defined $file) {
                   5505: 	my $pf = IO::File->new(">$file");
                   5506: 	if($pf) {
                   5507: 	    print $pf "$contents\n";
                   5508: 	    return 1;
                   5509: 	} else {
                   5510: 	    return 0;
                   5511: 	}
                   5512:     } else {
                   5513: 	return 0;
                   5514:     }
                   5515: 
                   5516: }
                   5517: 
1.78      foxr     5518: #
1.222     foxr     5519: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     5520: 
                   5521: #     Returns the authorization type or nouser if there is no such user.
                   5522: #
1.222     foxr     5523: sub get_auth_type 
1.78      foxr     5524: {
1.192     foxr     5525: 
                   5526:     my ($domain, $user)  = @_;
1.78      foxr     5527: 
1.222     foxr     5528:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     5529:     my $proname    = &propath($domain, $user); 
                   5530:     my $passwdfile = "$proname/passwd";
                   5531:     if( -e $passwdfile ) {
                   5532: 	my $pf = IO::File->new($passwdfile);
                   5533: 	my $realpassword = <$pf>;
                   5534: 	chomp($realpassword);
1.79      foxr     5535: 	Debug("Password info = $realpassword\n");
1.78      foxr     5536: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     5537: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  5538: 	return "$authtype:$contentpwd";     
1.224     foxr     5539:     } else {
1.79      foxr     5540: 	Debug("Returning nouser");
1.78      foxr     5541: 	return "nouser";
                   5542:     }
1.1       albertel 5543: }
                   5544: 
1.220     foxr     5545: #
                   5546: #  Validate a user given their domain, name and password.  This utility
                   5547: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   5548: #  to validate the login credentials of a user.
                   5549: # Parameters:
                   5550: #    $domain    - The domain being logged into (this is required due to
                   5551: #                 the capability for multihomed systems.
                   5552: #    $user      - The name of the user being validated.
                   5553: #    $password  - The user's propoposed password.
                   5554: #
                   5555: # Returns:
                   5556: #     1        - The domain,user,pasword triplet corresponds to a valid
                   5557: #                user.
                   5558: #     0        - The domain,user,password triplet is not a valid user.
                   5559: #
                   5560: sub validate_user {
                   5561:     my ($domain, $user, $password) = @_;
                   5562: 
                   5563: 
                   5564:     # Why negative ~pi you may well ask?  Well this function is about
                   5565:     # authentication, and therefore very important to get right.
                   5566:     # I've initialized the flag that determines whether or not I've 
                   5567:     # validated correctly to a value it's not supposed to get.
                   5568:     # At the end of this function. I'll ensure that it's not still that
                   5569:     # value so we don't just wind up returning some accidental value
                   5570:     # as a result of executing an unforseen code path that
1.249     foxr     5571:     # did not set $validated.  At the end of valid execution paths,
                   5572:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     5573: 
                   5574:     my $validated = -3.14159;
                   5575: 
                   5576:     #  How we authenticate is determined by the type of authentication
                   5577:     #  the user has been assigned.  If the authentication type is
                   5578:     #  "nouser", the user does not exist so we will return 0.
                   5579: 
1.222     foxr     5580:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     5581:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   5582: 
                   5583:     my $null = pack("C",0);	# Used by kerberos auth types.
                   5584: 
                   5585:     if ($howpwd ne 'nouser') {
                   5586: 
                   5587: 	if($howpwd eq "internal") { # Encrypted is in local password file.
                   5588: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
                   5589: 	}
                   5590: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   5591: 	    $contentpwd = (getpwnam($user))[1];
                   5592: 	    if($contentpwd) {
                   5593: 		if($contentpwd eq 'x') { # Shadow password file...
                   5594: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   5595: 		    open PWAUTH,  "|$pwauth_path" or
                   5596: 			die "Cannot invoke authentication";
                   5597: 		    print PWAUTH "$user\n$password\n";
                   5598: 		    close PWAUTH;
                   5599: 		    $validated = ! $?;
                   5600: 
                   5601: 		} else { 	         # Passwords in /etc/passwd. 
                   5602: 		    $validated = (crypt($password,
                   5603: 					$contentpwd) eq $contentpwd);
                   5604: 		}
                   5605: 	    } else {
                   5606: 		$validated = 0;
                   5607: 	    }
                   5608: 	}
                   5609: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   5610: 	    if(! ($password =~ /$null/) ) {
                   5611: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   5612: 							   "",
                   5613: 							   $contentpwd,,
                   5614: 							   'krbtgt',
                   5615: 							   $contentpwd,
                   5616: 							   1,
                   5617: 							   $password);
                   5618: 		if(!$k4error) {
                   5619: 		    $validated = 1;
1.224     foxr     5620: 		} else {
1.220     foxr     5621: 		    $validated = 0;
                   5622: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   5623: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   5624: 		}
1.224     foxr     5625: 	    } else {
1.220     foxr     5626: 		$validated = 0; # Password has a match with null.
                   5627: 	    }
1.224     foxr     5628: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220     foxr     5629: 	    if(!($password =~ /$null/)) { # Null password not allowed.
                   5630: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   5631: 							  .$contentpwd);
                   5632: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   5633: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   5634: 		my $credentials= &Authen::Krb5::cc_default();
                   5635: 		$credentials->initialize($krbclient);
1.270     matthew  5636: 		my $krbreturn  = &Authen::Krb5::get_in_tkt_with_password($krbclient,
1.220     foxr     5637: 									 $krbserver,
                   5638: 									 $password,
                   5639: 									 $credentials);
                   5640: 		$validated = ($krbreturn == 1);
1.224     foxr     5641: 	    } else {
1.220     foxr     5642: 		$validated = 0;
                   5643: 	    }
1.224     foxr     5644: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     5645: 	    #  Authenticate via installation specific authentcation method:
                   5646: 	    $validated = &localauth::localauth($user, 
                   5647: 					       $password, 
                   5648: 					       $contentpwd);
1.224     foxr     5649: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     5650: 	    $validated = 0;
                   5651: 	}
                   5652:     } else {
                   5653: 	$validated = 0;
                   5654:     }
                   5655:     #
                   5656:     #  $validated has the correct stat of the authentication:
                   5657:     #
                   5658: 
                   5659:     unless ($validated != -3.14159) {
1.249     foxr     5660: 	#  I >really really< want to know if this happens.
                   5661: 	#  since it indicates that user authentication is badly
                   5662: 	#  broken in some code path.
                   5663:         #
                   5664: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     5665:     }
                   5666:     return $validated;
                   5667: }
                   5668: 
                   5669: 
1.84      albertel 5670: sub addline {
                   5671:     my ($fname,$hostid,$ip,$newline)=@_;
                   5672:     my $contents;
                   5673:     my $found=0;
                   5674:     my $expr='^'.$hostid.':'.$ip.':';
                   5675:     $expr =~ s/\./\\\./g;
1.134     albertel 5676:     my $sh;
1.84      albertel 5677:     if ($sh=IO::File->new("$fname.subscription")) {
                   5678: 	while (my $subline=<$sh>) {
                   5679: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   5680: 	}
                   5681: 	$sh->close();
                   5682:     }
                   5683:     $sh=IO::File->new(">$fname.subscription");
                   5684:     if ($contents) { print $sh $contents; }
                   5685:     if ($newline) { print $sh $newline; }
                   5686:     $sh->close();
                   5687:     return $found;
1.86      www      5688: }
                   5689: 
1.234     foxr     5690: sub get_chat {
1.324     raeburn  5691:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 5692: 
1.87      www      5693:     my @entries=();
1.324     raeburn  5694:     my $namespace = 'nohist_chatroom';
                   5695:     my $namespace_inroom = 'nohist_inchatroom';
                   5696:     if (defined($group)) {
                   5697:         $namespace .= '_'.$group;
                   5698:         $namespace_inroom .= '_'.$group;
                   5699:     }
                   5700:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 5701: 				 &GDBM_READER());
                   5702:     if ($hashref) {
                   5703: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 5704: 	&untie_user_hash($hashref);
1.123     www      5705:     }
1.124     www      5706:     my @participants=();
1.134     albertel 5707:     my $cutoff=time-60;
1.324     raeburn  5708:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 5709: 			      &GDBM_WRCREAT());
                   5710:     if ($hashref) {
                   5711:         $hashref->{$uname.':'.$udom}=time;
                   5712:         foreach my $user (sort(keys(%$hashref))) {
                   5713: 	    if ($hashref->{$user}>$cutoff) {
                   5714: 		push(@participants, 'active_participant:'.$user);
1.123     www      5715:             }
                   5716:         }
1.311     albertel 5717:         &untie_user_hash($hashref);
1.86      www      5718:     }
1.124     www      5719:     return (@participants,@entries);
1.86      www      5720: }
                   5721: 
1.234     foxr     5722: sub chat_add {
1.324     raeburn  5723:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 5724:     my @entries=();
1.142     www      5725:     my $time=time;
1.324     raeburn  5726:     my $namespace = 'nohist_chatroom';
                   5727:     my $logfile = 'chatroom.log';
                   5728:     if (defined($group)) {
                   5729:         $namespace .= '_'.$group;
                   5730:         $logfile = 'chatroom_'.$group.'.log';
                   5731:     }
                   5732:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 5733: 				 &GDBM_WRCREAT());
                   5734:     if ($hashref) {
                   5735: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 5736: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   5737: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   5738: 	my $newid=$time.'_000000';
                   5739: 	if ($thentime==$time) {
                   5740: 	    $idnum=~s/^0+//;
                   5741: 	    $idnum++;
                   5742: 	    $idnum=substr('000000'.$idnum,-6,6);
                   5743: 	    $newid=$time.'_'.$idnum;
                   5744: 	}
1.310     albertel 5745: 	$hashref->{$newid}=$newchat;
1.88      albertel 5746: 	my $expired=$time-3600;
1.310     albertel 5747: 	foreach my $comment (keys(%$hashref)) {
                   5748: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 5749: 	    if ($thistime<$expired) {
1.310     albertel 5750: 		delete $hashref->{$comment};
1.88      albertel 5751: 	    }
                   5752: 	}
1.310     albertel 5753: 	{
                   5754: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  5755: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 5756: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   5757: 	    }
                   5758: 	    close(CHATLOG);
1.142     www      5759: 	}
1.311     albertel 5760: 	&untie_user_hash($hashref);
1.86      www      5761:     }
1.84      albertel 5762: }
                   5763: 
                   5764: sub unsub {
                   5765:     my ($fname,$clientip)=@_;
                   5766:     my $result;
1.188     foxr     5767:     my $unsubs = 0;		# Number of successful unsubscribes:
                   5768: 
                   5769: 
                   5770:     # An old way subscriptions were handled was to have a 
                   5771:     # subscription marker file:
                   5772: 
                   5773:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     5774:     if (unlink("$fname.$clientname")) {
1.188     foxr     5775: 	$unsubs++;		# Successful unsub via marker file.
                   5776:     } 
                   5777: 
                   5778:     # The more modern way to do it is to have a subscription list
                   5779:     # file:
                   5780: 
1.84      albertel 5781:     if (-e "$fname.subscription") {
1.161     foxr     5782: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     5783: 	if ($found) { 
                   5784: 	    $unsubs++;
                   5785: 	}
                   5786:     } 
                   5787: 
                   5788:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   5789:     #  resource we can return ok:
                   5790: 
                   5791:     if($unsubs) {
                   5792: 	$result = "ok\n";
1.84      albertel 5793:     } else {
1.188     foxr     5794: 	$result = "not_subscribed\n";
1.84      albertel 5795:     }
1.188     foxr     5796: 
1.84      albertel 5797:     return $result;
                   5798: }
                   5799: 
1.101     www      5800: sub currentversion {
                   5801:     my $fname=shift;
                   5802:     my $version=-1;
                   5803:     my $ulsdir='';
                   5804:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   5805:        $ulsdir=$1;
                   5806:     }
1.114     albertel 5807:     my ($fnamere1,$fnamere2);
                   5808:     # remove version if already specified
1.101     www      5809:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 5810:     # get the bits that go before and after the version number
                   5811:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   5812: 	$fnamere1=$1;
                   5813: 	$fnamere2='.'.$2;
                   5814:     }
1.101     www      5815:     if (-e $fname) { $version=1; }
                   5816:     if (-e $ulsdir) {
1.134     albertel 5817: 	if(-d $ulsdir) {
                   5818: 	    if (opendir(LSDIR,$ulsdir)) {
                   5819: 		my $ulsfn;
                   5820: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      5821: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 5822: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   5823: 		    unless (-l $thisfile) {
1.160     www      5824: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 5825: 			    if ($1>$version) { $version=$1; }
                   5826: 			}
                   5827: 		    }
                   5828: 		}
                   5829: 		closedir(LSDIR);
                   5830: 		$version++;
                   5831: 	    }
                   5832: 	}
                   5833:     }
                   5834:     return $version;
1.101     www      5835: }
                   5836: 
                   5837: sub thisversion {
                   5838:     my $fname=shift;
                   5839:     my $version=-1;
                   5840:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   5841: 	$version=$1;
                   5842:     }
                   5843:     return $version;
                   5844: }
                   5845: 
1.84      albertel 5846: sub subscribe {
                   5847:     my ($userinput,$clientip)=@_;
                   5848:     my $result;
1.293     albertel 5849:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 5850:     my $ownership=&ishome($fname);
                   5851:     if ($ownership eq 'owner') {
1.101     www      5852: # explitly asking for the current version?
                   5853:         unless (-e $fname) {
                   5854:             my $currentversion=&currentversion($fname);
                   5855: 	    if (&thisversion($fname)==$currentversion) {
                   5856:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   5857: 		    my $root=$1;
                   5858:                     my $extension=$2;
                   5859:                     symlink($root.'.'.$extension,
                   5860:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      5861:                     unless ($extension=~/\.meta$/) {
                   5862:                        symlink($root.'.'.$extension.'.meta',
                   5863:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   5864: 		    }
1.101     www      5865:                 }
                   5866:             }
                   5867:         }
1.84      albertel 5868: 	if (-e $fname) {
                   5869: 	    if (-d $fname) {
                   5870: 		$result="directory\n";
                   5871: 	    } else {
1.161     foxr     5872: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 5873: 		my $now=time;
1.161     foxr     5874: 		my $found=&addline($fname,$clientname,$clientip,
                   5875: 				   "$clientname:$clientip:$now\n");
1.84      albertel 5876: 		if ($found) { $result="$fname\n"; }
                   5877: 		# if they were subscribed to only meta data, delete that
                   5878:                 # subscription, when you subscribe to a file you also get
                   5879:                 # the metadata
                   5880: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   5881: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
                   5882: 		$fname="http://$thisserver/".$fname;
                   5883: 		$result="$fname\n";
                   5884: 	    }
                   5885: 	} else {
                   5886: 	    $result="not_found\n";
                   5887: 	}
                   5888:     } else {
                   5889: 	$result="rejected\n";
                   5890:     }
                   5891:     return $result;
                   5892: }
1.287     foxr     5893: #  Change the passwd of a unix user.  The caller must have
                   5894: #  first verified that the user is a loncapa user.
                   5895: #
                   5896: # Parameters:
                   5897: #    user      - Unix user name to change.
                   5898: #    pass      - New password for the user.
                   5899: # Returns:
                   5900: #    ok    - if success
                   5901: #    other - Some meaningfule error message string.
                   5902: # NOTE:
                   5903: #    invokes a setuid script to change the passwd.
                   5904: sub change_unix_password {
                   5905:     my ($user, $pass) = @_;
                   5906: 
                   5907:     &Debug("change_unix_password");
                   5908:     my $execdir=$perlvar{'lonDaemons'};
                   5909:     &Debug("Opening lcpasswd pipeline");
                   5910:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   5911: 			   ."$perlvar{'lonDaemons'}"
                   5912: 			   ."/logs/lcpasswd.log");
                   5913:     print $pf "$user\n$pass\n$pass\n";
                   5914:     close $pf;
                   5915:     my $err = $?;
                   5916:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   5917: 	"pwchange_falure - unknown error";
                   5918: 
                   5919:     
                   5920: }
                   5921: 
1.91      albertel 5922: 
                   5923: sub make_passwd_file {
1.98      foxr     5924:     my ($uname, $umode,$npass,$passfilename)=@_;
1.91      albertel 5925:     my $result="ok\n";
                   5926:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   5927: 	{
                   5928: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5929: 	    if ($pf) {
                   5930: 		print $pf "$umode:$npass\n";
                   5931: 	    } else {
                   5932: 		$result = "pass_file_failed_error";
                   5933: 	    }
1.91      albertel 5934: 	}
                   5935:     } elsif ($umode eq 'internal') {
                   5936: 	my $salt=time;
                   5937: 	$salt=substr($salt,6,2);
                   5938: 	my $ncpass=crypt($npass,$salt);
                   5939: 	{
                   5940: 	    &Debug("Creating internal auth");
                   5941: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5942: 	    if($pf) {
                   5943: 		print $pf "internal:$ncpass\n"; 
                   5944: 	    } else {
                   5945: 		$result = "pass_file_failed_error";
                   5946: 	    }
1.91      albertel 5947: 	}
                   5948:     } elsif ($umode eq 'localauth') {
                   5949: 	{
                   5950: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5951: 	    if($pf) {
                   5952: 		print $pf "localauth:$npass\n";
                   5953: 	    } else {
                   5954: 		$result = "pass_file_failed_error";
                   5955: 	    }
1.91      albertel 5956: 	}
                   5957:     } elsif ($umode eq 'unix') {
                   5958: 	{
1.186     foxr     5959: 	    #
                   5960: 	    #  Don't allow the creation of privileged accounts!!! that would
                   5961: 	    #  be real bad!!!
                   5962: 	    #
                   5963: 	    my $uid = getpwnam($uname);
                   5964: 	    if((defined $uid) && ($uid == 0)) {
                   5965: 		&logthis(">>>Attempted to create privilged account blocked");
                   5966: 		return "no_priv_account_error\n";
                   5967: 	    }
                   5968: 
1.223     foxr     5969: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224     foxr     5970: 
                   5971: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
1.91      albertel 5972: 	    {
                   5973: 		&Debug("Executing external: ".$execpath);
1.98      foxr     5974: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  5975: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 5976: 		print $se "$uname\n";
                   5977: 		print $se "$npass\n";
                   5978: 		print $se "$npass\n";
1.223     foxr     5979: 		print $se "$lc_error_file\n"; # Status -> unique file.
1.97      foxr     5980: 	    }
1.285     foxr     5981: 	    if (-r $lc_error_file) {
                   5982: 		&Debug("Opening error file: $lc_error_file");
                   5983: 		my $error = IO::File->new("< $lc_error_file");
                   5984: 		my $useraddok = <$error>;
                   5985: 		$error->close;
                   5986: 		unlink($lc_error_file);
                   5987: 		
                   5988: 		chomp $useraddok;
                   5989: 	
                   5990: 		if($useraddok > 0) {
                   5991: 		    my $error_text = &lcuseraddstrerror($useraddok);
                   5992: 		    &logthis("Failed lcuseradd: $error_text");
                   5993: 		    $result = "lcuseradd_failed:$error_text\n";
                   5994: 		}  else {
                   5995: 		    my $pf = IO::File->new(">$passfilename");
                   5996: 		    if($pf) {
                   5997: 			print $pf "unix:\n";
                   5998: 		    } else {
                   5999: 			$result = "pass_file_failed_error";
                   6000: 		    }
                   6001: 		}
1.224     foxr     6002: 	    }  else {
1.285     foxr     6003: 		&Debug("Could not locate lcuseradd error: $lc_error_file");
                   6004: 		$result="bug_lcuseradd_no_output_file";
1.91      albertel 6005: 	    }
                   6006: 	}
                   6007:     } elsif ($umode eq 'none') {
                   6008: 	{
1.223     foxr     6009: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     6010: 	    if($pf) {
                   6011: 		print $pf "none:\n";
                   6012: 	    } else {
                   6013: 		$result = "pass_file_failed_error";
                   6014: 	    }
1.91      albertel 6015: 	}
                   6016:     } else {
                   6017: 	$result="auth_mode_error\n";
                   6018:     }
                   6019:     return $result;
1.121     albertel 6020: }
                   6021: 
1.265     albertel 6022: sub convert_photo {
                   6023:     my ($start,$dest)=@_;
                   6024:     system("convert $start $dest");
                   6025: }
                   6026: 
1.121     albertel 6027: sub sethost {
                   6028:     my ($remotereq) = @_;
                   6029:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 6030:     # ignore sethost if we are already correct
                   6031:     if ($hostid eq $currenthostid) {
                   6032: 	return 'ok';
                   6033:     }
                   6034: 
1.121     albertel 6035:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
                   6036:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200     matthew  6037: 	$currenthostid  =$hostid;
1.121     albertel 6038: 	$currentdomainid=$hostdom{$hostid};
                   6039: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
                   6040:     } else {
                   6041: 	&logthis("Requested host id $hostid not an alias of ".
                   6042: 		 $perlvar{'lonHostID'}." refusing connection");
                   6043: 	return 'unable_to_set';
                   6044:     }
                   6045:     return 'ok';
                   6046: }
                   6047: 
                   6048: sub version {
                   6049:     my ($userinput)=@_;
                   6050:     $remoteVERSION=(split(/:/,$userinput))[1];
                   6051:     return "version:$VERSION";
1.127     albertel 6052: }
1.178     foxr     6053: 
1.128     albertel 6054: #There is a copy of this in lonnet.pm
1.127     albertel 6055: sub userload {
                   6056:     my $numusers=0;
                   6057:     {
                   6058: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   6059: 	my $filename;
                   6060: 	my $curtime=time;
                   6061: 	while ($filename=readdir(LONIDS)) {
                   6062: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.138     albertel 6063: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159     albertel 6064: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.127     albertel 6065: 	}
                   6066: 	closedir(LONIDS);
                   6067:     }
                   6068:     my $userloadpercent=0;
                   6069:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   6070:     if ($maxuserload) {
1.129     albertel 6071: 	$userloadpercent=100*$numusers/$maxuserload;
1.127     albertel 6072:     }
1.130     albertel 6073:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127     albertel 6074:     return $userloadpercent;
1.91      albertel 6075: }
                   6076: 
1.205     raeburn  6077: # Routines for serializing arrays and hashes (copies from lonnet)
                   6078: 
                   6079: sub array2str {
                   6080:   my (@array) = @_;
                   6081:   my $result=&arrayref2str(\@array);
                   6082:   $result=~s/^__ARRAY_REF__//;
                   6083:   $result=~s/__END_ARRAY_REF__$//;
                   6084:   return $result;
                   6085: }
                   6086:                                                                                  
                   6087: sub arrayref2str {
                   6088:   my ($arrayref) = @_;
                   6089:   my $result='__ARRAY_REF__';
                   6090:   foreach my $elem (@$arrayref) {
                   6091:     if(ref($elem) eq 'ARRAY') {
                   6092:       $result.=&arrayref2str($elem).'&';
                   6093:     } elsif(ref($elem) eq 'HASH') {
                   6094:       $result.=&hashref2str($elem).'&';
                   6095:     } elsif(ref($elem)) {
                   6096:       #print("Got a ref of ".(ref($elem))." skipping.");
                   6097:     } else {
                   6098:       $result.=&escape($elem).'&';
                   6099:     }
                   6100:   }
                   6101:   $result=~s/\&$//;
                   6102:   $result .= '__END_ARRAY_REF__';
                   6103:   return $result;
                   6104: }
                   6105:                                                                                  
                   6106: sub hash2str {
                   6107:   my (%hash) = @_;
                   6108:   my $result=&hashref2str(\%hash);
                   6109:   $result=~s/^__HASH_REF__//;
                   6110:   $result=~s/__END_HASH_REF__$//;
                   6111:   return $result;
                   6112: }
                   6113:                                                                                  
                   6114: sub hashref2str {
                   6115:   my ($hashref)=@_;
                   6116:   my $result='__HASH_REF__';
                   6117:   foreach (sort(keys(%$hashref))) {
                   6118:     if (ref($_) eq 'ARRAY') {
                   6119:       $result.=&arrayref2str($_).'=';
                   6120:     } elsif (ref($_) eq 'HASH') {
                   6121:       $result.=&hashref2str($_).'=';
                   6122:     } elsif (ref($_)) {
                   6123:       $result.='=';
                   6124:       #print("Got a ref of ".(ref($_))." skipping.");
                   6125:     } else {
                   6126:         if ($_) {$result.=&escape($_).'=';} else { last; }
                   6127:     }
                   6128: 
                   6129:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   6130:       $result.=&arrayref2str($hashref->{$_}).'&';
                   6131:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   6132:       $result.=&hashref2str($hashref->{$_}).'&';
                   6133:     } elsif(ref($hashref->{$_})) {
                   6134:        $result.='&';
                   6135:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
                   6136:     } else {
                   6137:       $result.=&escape($hashref->{$_}).'&';
                   6138:     }
                   6139:   }
                   6140:   $result=~s/\&$//;
                   6141:   $result .= '__END_HASH_REF__';
                   6142:   return $result;
                   6143: }
1.200     matthew  6144: 
1.61      harris41 6145: # ----------------------------------- POD (plain old documentation, CPAN style)
                   6146: 
                   6147: =head1 NAME
                   6148: 
                   6149: lond - "LON Daemon" Server (port "LOND" 5663)
                   6150: 
                   6151: =head1 SYNOPSIS
                   6152: 
1.74      harris41 6153: Usage: B<lond>
                   6154: 
                   6155: Should only be run as user=www.  This is a command-line script which
                   6156: is invoked by B<loncron>.  There is no expectation that a typical user
                   6157: will manually start B<lond> from the command-line.  (In other words,
                   6158: DO NOT START B<lond> YOURSELF.)
1.61      harris41 6159: 
                   6160: =head1 DESCRIPTION
                   6161: 
1.74      harris41 6162: There are two characteristics associated with the running of B<lond>,
                   6163: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   6164: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   6165: subscriptions, etc).  These are described in two large
                   6166: sections below.
                   6167: 
                   6168: B<PROCESS MANAGEMENT>
                   6169: 
1.61      harris41 6170: Preforker - server who forks first. Runs as a daemon. HUPs.
                   6171: Uses IDEA encryption
                   6172: 
1.74      harris41 6173: B<lond> forks off children processes that correspond to the other servers
                   6174: in the network.  Management of these processes can be done at the
                   6175: parent process level or the child process level.
                   6176: 
                   6177: B<logs/lond.log> is the location of log messages.
                   6178: 
                   6179: The process management is now explained in terms of linux shell commands,
                   6180: subroutines internal to this code, and signal assignments:
                   6181: 
                   6182: =over 4
                   6183: 
                   6184: =item *
                   6185: 
                   6186: PID is stored in B<logs/lond.pid>
                   6187: 
                   6188: This is the process id number of the parent B<lond> process.
                   6189: 
                   6190: =item *
                   6191: 
                   6192: SIGTERM and SIGINT
                   6193: 
                   6194: Parent signal assignment:
                   6195:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   6196: 
                   6197: Child signal assignment:
                   6198:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   6199: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   6200:  to restart a new child.)
                   6201: 
                   6202: Command-line invocations:
                   6203:  B<kill> B<-s> SIGTERM I<PID>
                   6204:  B<kill> B<-s> SIGINT I<PID>
                   6205: 
                   6206: Subroutine B<HUNTSMAN>:
                   6207:  This is only invoked for the B<lond> parent I<PID>.
                   6208: This kills all the children, and then the parent.
                   6209: The B<lonc.pid> file is cleared.
                   6210: 
                   6211: =item *
                   6212: 
                   6213: SIGHUP
                   6214: 
                   6215: Current bug:
                   6216:  This signal can only be processed the first time
                   6217: on the parent process.  Subsequent SIGHUP signals
                   6218: have no effect.
                   6219: 
                   6220: Parent signal assignment:
                   6221:  $SIG{HUP}  = \&HUPSMAN;
                   6222: 
                   6223: Child signal assignment:
                   6224:  none (nothing happens)
                   6225: 
                   6226: Command-line invocations:
                   6227:  B<kill> B<-s> SIGHUP I<PID>
                   6228: 
                   6229: Subroutine B<HUPSMAN>:
                   6230:  This is only invoked for the B<lond> parent I<PID>,
                   6231: This kills all the children, and then the parent.
                   6232: The B<lond.pid> file is cleared.
                   6233: 
                   6234: =item *
                   6235: 
                   6236: SIGUSR1
                   6237: 
                   6238: Parent signal assignment:
                   6239:  $SIG{USR1} = \&USRMAN;
                   6240: 
                   6241: Child signal assignment:
                   6242:  $SIG{USR1}= \&logstatus;
                   6243: 
                   6244: Command-line invocations:
                   6245:  B<kill> B<-s> SIGUSR1 I<PID>
                   6246: 
                   6247: Subroutine B<USRMAN>:
                   6248:  When invoked for the B<lond> parent I<PID>,
                   6249: SIGUSR1 is sent to all the children, and the status of
                   6250: each connection is logged.
1.144     foxr     6251: 
                   6252: =item *
                   6253: 
                   6254: SIGUSR2
                   6255: 
                   6256: Parent Signal assignment:
                   6257:     $SIG{USR2} = \&UpdateHosts
                   6258: 
                   6259: Child signal assignment:
                   6260:     NONE
                   6261: 
1.74      harris41 6262: 
                   6263: =item *
                   6264: 
                   6265: SIGCHLD
                   6266: 
                   6267: Parent signal assignment:
                   6268:  $SIG{CHLD} = \&REAPER;
                   6269: 
                   6270: Child signal assignment:
                   6271:  none
                   6272: 
                   6273: Command-line invocations:
                   6274:  B<kill> B<-s> SIGCHLD I<PID>
                   6275: 
                   6276: Subroutine B<REAPER>:
                   6277:  This is only invoked for the B<lond> parent I<PID>.
                   6278: Information pertaining to the child is removed.
                   6279: The socket port is cleaned up.
                   6280: 
                   6281: =back
                   6282: 
                   6283: B<SERVER-SIDE ACTIVITIES>
                   6284: 
                   6285: Server-side information can be accepted in an encrypted or non-encrypted
                   6286: method.
                   6287: 
                   6288: =over 4
                   6289: 
                   6290: =item ping
                   6291: 
                   6292: Query a client in the hosts.tab table; "Are you there?"
                   6293: 
                   6294: =item pong
                   6295: 
                   6296: Respond to a ping query.
                   6297: 
                   6298: =item ekey
                   6299: 
                   6300: Read in encrypted key, make cipher.  Respond with a buildkey.
                   6301: 
                   6302: =item load
                   6303: 
                   6304: Respond with CPU load based on a computation upon /proc/loadavg.
                   6305: 
                   6306: =item currentauth
                   6307: 
                   6308: Reply with current authentication information (only over an
                   6309: encrypted channel).
                   6310: 
                   6311: =item auth
                   6312: 
                   6313: Only over an encrypted channel, reply as to whether a user's
                   6314: authentication information can be validated.
                   6315: 
                   6316: =item passwd
                   6317: 
                   6318: Allow for a password to be set.
                   6319: 
                   6320: =item makeuser
                   6321: 
                   6322: Make a user.
                   6323: 
                   6324: =item passwd
                   6325: 
                   6326: Allow for authentication mechanism and password to be changed.
                   6327: 
                   6328: =item home
1.61      harris41 6329: 
1.74      harris41 6330: Respond to a question "are you the home for a given user?"
                   6331: 
                   6332: =item update
                   6333: 
                   6334: Update contents of a subscribed resource.
                   6335: 
                   6336: =item unsubscribe
                   6337: 
                   6338: The server is unsubscribing from a resource.
                   6339: 
                   6340: =item subscribe
                   6341: 
                   6342: The server is subscribing to a resource.
                   6343: 
                   6344: =item log
                   6345: 
                   6346: Place in B<logs/lond.log>
                   6347: 
                   6348: =item put
                   6349: 
                   6350: stores hash in namespace
                   6351: 
1.230     foxr     6352: =item rolesputy
1.74      harris41 6353: 
                   6354: put a role into a user's environment
                   6355: 
                   6356: =item get
                   6357: 
                   6358: returns hash with keys from array
                   6359: reference filled in from namespace
                   6360: 
                   6361: =item eget
                   6362: 
                   6363: returns hash with keys from array
                   6364: reference filled in from namesp (encrypts the return communication)
                   6365: 
                   6366: =item rolesget
                   6367: 
                   6368: get a role from a user's environment
                   6369: 
                   6370: =item del
                   6371: 
                   6372: deletes keys out of array from namespace
                   6373: 
                   6374: =item keys
                   6375: 
                   6376: returns namespace keys
                   6377: 
                   6378: =item dump
                   6379: 
                   6380: dumps the complete (or key matching regexp) namespace into a hash
                   6381: 
                   6382: =item store
                   6383: 
                   6384: stores hash permanently
                   6385: for this url; hashref needs to be given and should be a \%hashname; the
                   6386: remaining args aren't required and if they aren't passed or are '' they will
                   6387: be derived from the ENV
                   6388: 
                   6389: =item restore
                   6390: 
                   6391: returns a hash for a given url
                   6392: 
                   6393: =item querysend
                   6394: 
                   6395: Tells client about the lonsql process that has been launched in response
                   6396: to a sent query.
                   6397: 
                   6398: =item queryreply
                   6399: 
                   6400: Accept information from lonsql and make appropriate storage in temporary
                   6401: file space.
                   6402: 
                   6403: =item idput
                   6404: 
                   6405: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   6406: for each student, defined perhaps by the institutional Registrar.)
                   6407: 
                   6408: =item idget
                   6409: 
                   6410: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   6411: for each student, defined perhaps by the institutional Registrar.)
                   6412: 
                   6413: =item tmpput
                   6414: 
                   6415: Accept and store information in temporary space.
                   6416: 
                   6417: =item tmpget
                   6418: 
                   6419: Send along temporarily stored information.
                   6420: 
                   6421: =item ls
                   6422: 
                   6423: List part of a user's directory.
                   6424: 
1.135     foxr     6425: =item pushtable
                   6426: 
                   6427: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   6428: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   6429: must be restored manually in case of a problem with the new table file.
                   6430: pushtable requires that the request be encrypted and validated via
                   6431: ValidateManager.  The form of the command is:
                   6432: enc:pushtable tablename <tablecontents> \n
                   6433: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   6434: cleartext newline.
                   6435: 
1.74      harris41 6436: =item Hanging up (exit or init)
                   6437: 
                   6438: What to do when a client tells the server that they (the client)
                   6439: are leaving the network.
                   6440: 
                   6441: =item unknown command
                   6442: 
                   6443: If B<lond> is sent an unknown command (not in the list above),
                   6444: it replys to the client "unknown_cmd".
1.135     foxr     6445: 
1.74      harris41 6446: 
                   6447: =item UNKNOWN CLIENT
                   6448: 
                   6449: If the anti-spoofing algorithm cannot verify the client,
                   6450: the client is rejected (with a "refused" message sent
                   6451: to the client, and the connection is closed.
                   6452: 
                   6453: =back
1.61      harris41 6454: 
                   6455: =head1 PREREQUISITES
                   6456: 
                   6457: IO::Socket
                   6458: IO::File
                   6459: Apache::File
                   6460: POSIX
                   6461: Crypt::IDEA
                   6462: LWP::UserAgent()
                   6463: GDBM_File
                   6464: Authen::Krb4
1.91      albertel 6465: Authen::Krb5
1.61      harris41 6466: 
                   6467: =head1 COREQUISITES
                   6468: 
                   6469: =head1 OSNAMES
                   6470: 
                   6471: linux
                   6472: 
                   6473: =head1 SCRIPT CATEGORIES
                   6474: 
                   6475: Server/Process
                   6476: 
                   6477: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>
500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.