Annotation of loncom/lond, revision 1.240

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

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