Annotation of loncom/lond, revision 1.252

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

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