Annotation of loncom/lond, revision 1.318.2.5

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

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