Annotation of loncom/lond, revision 1.257

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

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