Annotation of loncom/lond, revision 1.217

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.217   ! foxr        5: # $Id: lond,v 1.216 2004/07/27 11:34:49 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.1       albertel   53: 
1.204     albertel   54: my $DEBUG = 0;		       # Non zero to enable debug log entries.
1.77      foxr       55: 
1.57      www        56: my $status='';
                     57: my $lastlog='';
                     58: 
1.217   ! foxr       59: my $VERSION='$Revision: 1.216 $'; #' stupid emacs
1.121     albertel   60: my $remoteVERSION;
1.214     foxr       61: my $currenthostid="default";
1.115     albertel   62: my $currentdomainid;
1.134     albertel   63: 
                     64: my $client;
1.200     matthew    65: my $clientip;			# IP address of client.
                     66: my $clientdns;			# DNS name of client.
                     67: my $clientname;			# LonCAPA name of client.
1.140     foxr       68: 
1.134     albertel   69: my $server;
1.200     matthew    70: my $thisserver;			# DNS of us.
                     71: 
                     72: my $keymode;
1.198     foxr       73: 
1.207     foxr       74: my $cipher;			# Cipher key negotiated with client
                     75: my $tmpsnum = 0;		# Id of tmpputs.
                     76: 
1.178     foxr       77: # 
                     78: #   Connection type is:
                     79: #      client                   - All client actions are allowed
                     80: #      manager                  - only management functions allowed.
                     81: #      both                     - Both management and client actions are allowed
                     82: #
1.161     foxr       83: 
1.178     foxr       84: my $ConnectionType;
1.161     foxr       85: 
1.200     matthew    86: my %hostid;			# ID's for hosts in cluster by ip.
                     87: my %hostdom;			# LonCAPA domain for hosts in cluster.
                     88: my %hostip;			# IPs for hosts in cluster.
                     89: my %hostdns;			# ID's of hosts looked up by DNS name.
1.161     foxr       90: 
1.178     foxr       91: my %managers;			# Ip -> manager names
1.161     foxr       92: 
1.178     foxr       93: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel   94: 
1.178     foxr       95: #
1.207     foxr       96: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                     97: #    Each element of the hash contains a reference to an array that contains:
                     98: #          A reference to a sub that executes the request corresponding to the keyword.
                     99: #          A flag that is true if the request must be encoded to be acceptable.
                    100: #          A mask with bits as follows:
                    101: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    102: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    103: #
                    104: my $CLIENT_OK  = 1;
                    105: my $MANAGER_OK = 2;
                    106: my %Dispatcher;
                    107: 
                    108: 
                    109: #
1.178     foxr      110: #  The array below are password error strings."
                    111: #
                    112: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    113: my @passwderrors = ("ok",
                    114: 		   "lcpasswd must be run as user 'www'",
                    115: 		   "lcpasswd got incorrect number of arguments",
                    116: 		   "lcpasswd did not get the right nubmer of input text lines",
                    117: 		   "lcpasswd too many simultaneous pwd changes in progress",
                    118: 		   "lcpasswd User does not exist.",
                    119: 		   "lcpasswd Incorrect current passwd",
                    120: 		   "lcpasswd Unable to su to root.",
                    121: 		   "lcpasswd Cannot set new passwd.",
                    122: 		   "lcpasswd Username has invalid characters",
                    123: 		   "lcpasswd Invalid characters in password",
                    124: 		    "11", "12",
                    125: 		    "lcpasswd Password mismatch");
1.97      foxr      126: 
                    127: 
1.178     foxr      128: #  The array below are lcuseradd error strings.:
1.97      foxr      129: 
1.178     foxr      130: my $lastadderror = 13;
                    131: my @adderrors    = ("ok",
                    132: 		    "User ID mismatch, lcuseradd must run as user www",
                    133: 		    "lcuseradd Incorrect number of command line parameters must be 3",
                    134: 		    "lcuseradd Incorrect number of stdinput lines, must be 3",
                    135: 		    "lcuseradd Too many other simultaneous pwd changes in progress",
                    136: 		    "lcuseradd User does not exist",
                    137: 		    "lcuseradd Unable to make www member of users's group",
                    138: 		    "lcuseradd Unable to su to root",
                    139: 		    "lcuseradd Unable to set password",
                    140: 		    "lcuseradd Usrname has invalid characters",
                    141: 		    "lcuseradd Password has an invalid character",
                    142: 		    "lcuseradd User already exists",
                    143: 		    "lcuseradd Could not add user.",
                    144: 		    "lcuseradd Password mismatch");
1.97      foxr      145: 
1.96      foxr      146: 
1.207     foxr      147: 
                    148: #
                    149: #   Statistics that are maintained and dislayed in the status line.
                    150: #
1.212     foxr      151: my $Transactions = 0;		# Number of attempted transactions.
                    152: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      153: 
                    154: #   ResetStatistics: 
                    155: #      Resets the statistics counters:
                    156: #
                    157: sub ResetStatistics {
                    158:     $Transactions = 0;
                    159:     $Failures     = 0;
                    160: }
                    161: 
                    162: 
                    163: 
1.200     matthew   164: #------------------------------------------------------------------------
                    165: #
                    166: #   LocalConnection
                    167: #     Completes the formation of a locally authenticated connection.
                    168: #     This function will ensure that the 'remote' client is really the
                    169: #     local host.  If not, the connection is closed, and the function fails.
                    170: #     If so, initcmd is parsed for the name of a file containing the
                    171: #     IDEA session key.  The fie is opened, read, deleted and the session
                    172: #     key returned to the caller.
                    173: #
                    174: # Parameters:
                    175: #   $Socket      - Socket open on client.
                    176: #   $initcmd     - The full text of the init command.
                    177: #
                    178: # Implicit inputs:
                    179: #    $clientdns  - The DNS name of the remote client.
                    180: #    $thisserver - Our DNS name.
                    181: #
                    182: # Returns:
                    183: #     IDEA session key on success.
                    184: #     undef on failure.
                    185: #
                    186: sub LocalConnection {
                    187:     my ($Socket, $initcmd) = @_;
                    188:     Debug("Attempting local connection: $initcmd client: $clientdns me: $thisserver");
                    189:     if($clientdns ne $thisserver) {
                    190: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
                    191: 		 ."$clientdns ne $thisserver </font>");
                    192: 	close $Socket;
                    193: 	return undef;
                    194:     } 
                    195:     else {
                    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;
                    326:     } 
                    327:     else {
                    328: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    329: 	&status("No challenge reqply");
                    330: 	return 0;
                    331:     }
                    332:     
                    333: 
                    334: }
                    335: 
1.96      foxr      336: #
1.140     foxr      337: #   GetCertificate: Given a transaction that requires a certificate,
                    338: #   this function will extract the certificate from the transaction
                    339: #   request.  Note that at this point, the only concept of a certificate
                    340: #   is the hostname to which we are connected.
                    341: #
                    342: #   Parameter:
                    343: #      request   - The request sent by our client (this parameterization may
                    344: #                  need to change when we really use a certificate granting
                    345: #                  authority.
                    346: #
                    347: sub GetCertificate {
                    348:     my $request = shift;
                    349: 
                    350:     return $clientip;
                    351: }
1.161     foxr      352: 
1.178     foxr      353: #
                    354: #   Return true if client is a manager.
                    355: #
                    356: sub isManager {
                    357:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    358: }
                    359: #
                    360: #   Return tru if client can do client functions
                    361: #
                    362: sub isClient {
                    363:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    364: }
1.161     foxr      365: 
                    366: 
1.156     foxr      367: #
                    368: #   ReadManagerTable: Reads in the current manager table. For now this is
                    369: #                     done on each manager authentication because:
                    370: #                     - These authentications are not frequent
                    371: #                     - This allows dynamic changes to the manager table
                    372: #                       without the need to signal to the lond.
                    373: #
                    374: 
                    375: sub ReadManagerTable {
                    376: 
                    377:     #   Clean out the old table first..
                    378: 
1.166     foxr      379:    foreach my $key (keys %managers) {
                    380:       delete $managers{$key};
                    381:    }
                    382: 
                    383:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    384:    if (!open (MANAGERS, $tablename)) {
                    385:       logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    386:       return;
                    387:    }
                    388:    while(my $host = <MANAGERS>) {
                    389:       chomp($host);
                    390:       if ($host =~ "^#") {                  # Comment line.
                    391:          next;
                    392:       }
                    393:       if (!defined $hostip{$host}) { # This is a non cluster member
1.161     foxr      394: 	    #  The entry is of the form:
                    395: 	    #    cluname:hostname
                    396: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    397: 	    #            the host key.
                    398: 	    #  hostname- The dns name of the host.
                    399: 	    #
1.166     foxr      400:           my($cluname, $dnsname) = split(/:/, $host);
                    401:           
                    402:           my $ip = gethostbyname($dnsname);
                    403:           if(defined($ip)) {                 # bad names don't deserve entry.
                    404:             my $hostip = inet_ntoa($ip);
                    405:             $managers{$hostip} = $cluname;
                    406:             logthis('<font color="green"> registering manager '.
                    407:                     "$dnsname as $cluname with $hostip </font>\n");
                    408:          }
                    409:       } else {
                    410:          logthis('<font color="green"> existing host'." $host</font>\n");
                    411:          $managers{$hostip{$host}} = $host;  # Use info from cluster tab if clumemeber
                    412:       }
                    413:    }
1.156     foxr      414: }
1.140     foxr      415: 
                    416: #
                    417: #  ValidManager: Determines if a given certificate represents a valid manager.
                    418: #                in this primitive implementation, the 'certificate' is
                    419: #                just the connecting loncapa client name.  This is checked
                    420: #                against a valid client list in the configuration.
                    421: #
                    422: #                  
                    423: sub ValidManager {
                    424:     my $certificate = shift; 
                    425: 
1.163     foxr      426:     return isManager;
1.140     foxr      427: }
                    428: #
1.143     foxr      429: #  CopyFile:  Called as part of the process of installing a 
                    430: #             new configuration file.  This function copies an existing
                    431: #             file to a backup file.
                    432: # Parameters:
                    433: #     oldfile  - Name of the file to backup.
                    434: #     newfile  - Name of the backup file.
                    435: # Return:
                    436: #     0   - Failure (errno has failure reason).
                    437: #     1   - Success.
                    438: #
                    439: sub CopyFile {
1.192     foxr      440: 
                    441:     my ($oldfile, $newfile) = @_;
1.143     foxr      442: 
                    443:     #  The file must exist:
                    444: 
                    445:     if(-e $oldfile) {
                    446: 
                    447: 	 # Read the old file.
                    448: 
                    449: 	my $oldfh = IO::File->new("< $oldfile");
                    450: 	if(!$oldfh) {
                    451: 	    return 0;
                    452: 	}
                    453: 	my @contents = <$oldfh>;  # Suck in the entire file.
                    454: 
                    455: 	# write the backup file:
                    456: 
                    457: 	my $newfh = IO::File->new("> $newfile");
                    458: 	if(!(defined $newfh)){
                    459: 	    return 0;
                    460: 	}
                    461: 	my $lines = scalar @contents;
                    462: 	for (my $i =0; $i < $lines; $i++) {
                    463: 	    print $newfh ($contents[$i]);
                    464: 	}
                    465: 
                    466: 	$oldfh->close;
                    467: 	$newfh->close;
                    468: 
                    469: 	chmod(0660, $newfile);
                    470: 
                    471: 	return 1;
                    472: 	    
                    473:     } else {
                    474: 	return 0;
                    475:     }
                    476: }
1.157     foxr      477: #
                    478: #  Host files are passed out with externally visible host IPs.
                    479: #  If, for example, we are behind a fire-wall or NAT host, our 
                    480: #  internally visible IP may be different than the externally
                    481: #  visible IP.  Therefore, we always adjust the contents of the
                    482: #  host file so that the entry for ME is the IP that we believe
                    483: #  we have.  At present, this is defined as the entry that
                    484: #  DNS has for us.  If by some chance we are not able to get a
                    485: #  DNS translation for us, then we assume that the host.tab file
                    486: #  is correct.  
                    487: #    BUGBUGBUG - in the future, we really should see if we can
                    488: #       easily query the interface(s) instead.
                    489: # Parameter(s):
                    490: #     contents    - The contents of the host.tab to check.
                    491: # Returns:
                    492: #     newcontents - The adjusted contents.
                    493: #
                    494: #
                    495: sub AdjustHostContents {
                    496:     my $contents  = shift;
                    497:     my $adjusted;
                    498:     my $me        = $perlvar{'lonHostID'};
                    499: 
1.166     foxr      500:  foreach my $line (split(/\n/,$contents)) {
1.157     foxr      501: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
                    502: 	    chomp($line);
                    503: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    504: 	    if ($id eq $me) {
1.166     foxr      505:           my $ip = gethostbyname($name);
                    506:           my $ipnew = inet_ntoa($ip);
                    507:          $ip = $ipnew;
1.157     foxr      508: 		#  Reconstruct the host line and append to adjusted:
                    509: 		
1.166     foxr      510: 		   my $newline = "$id:$domain:$role:$name:$ip";
                    511: 		   if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    512: 		     $newline .= ":$maxcon:$idleto:$mincon";
                    513: 		   }
                    514: 		   $adjusted .= $newline."\n";
1.157     foxr      515: 		
1.166     foxr      516:       } else {		# Not me, pass unmodified.
                    517: 		   $adjusted .= $line."\n";
                    518:       }
1.157     foxr      519: 	} else {                  # Blank or comment never re-written.
                    520: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    521: 	}
1.166     foxr      522:  }
                    523:  return $adjusted;
1.157     foxr      524: }
1.143     foxr      525: #
                    526: #   InstallFile: Called to install an administrative file:
                    527: #       - The file is created with <name>.tmp
                    528: #       - The <name>.tmp file is then mv'd to <name>
                    529: #   This lugubrious procedure is done to ensure that we are never without
                    530: #   a valid, even if dated, version of the file regardless of who crashes
                    531: #   and when the crash occurs.
                    532: #
                    533: #  Parameters:
                    534: #       Name of the file
                    535: #       File Contents.
                    536: #  Return:
                    537: #      nonzero - success.
                    538: #      0       - failure and $! has an errno.
                    539: #
                    540: sub InstallFile {
1.192     foxr      541: 
                    542:     my ($Filename, $Contents) = @_;
1.143     foxr      543:     my $TempFile = $Filename.".tmp";
                    544: 
                    545:     #  Open the file for write:
                    546: 
                    547:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    548:     if(!(defined $fh)) {
                    549: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    550: 	return 0;
                    551:     }
                    552:     #  write the contents of the file:
                    553: 
                    554:     print $fh ($Contents); 
                    555:     $fh->close;			# In case we ever have a filesystem w. locking
                    556: 
                    557:     chmod(0660, $TempFile);
                    558: 
                    559:     # Now we can move install the file in position.
                    560:     
                    561:     move($TempFile, $Filename);
                    562: 
                    563:     return 1;
                    564: }
1.200     matthew   565: 
                    566: 
1.169     foxr      567: #
                    568: #   ConfigFileFromSelector: converts a configuration file selector
                    569: #                 (one of host or domain at this point) into a 
                    570: #                 configuration file pathname.
                    571: #
                    572: #  Parameters:
                    573: #      selector  - Configuration file selector.
                    574: #  Returns:
                    575: #      Full path to the file or undef if the selector is invalid.
                    576: #
                    577: sub ConfigFileFromSelector {
                    578:     my $selector   = shift;
                    579:     my $tablefile;
                    580: 
                    581:     my $tabledir = $perlvar{'lonTabDir'}.'/';
                    582:     if ($selector eq "hosts") {
                    583: 	$tablefile = $tabledir."hosts.tab";
                    584:     } elsif ($selector eq "domain") {
                    585: 	$tablefile = $tabledir."domain.tab";
                    586:     } else {
                    587: 	return undef;
                    588:     }
                    589:     return $tablefile;
1.143     foxr      590: 
1.169     foxr      591: }
1.143     foxr      592: #
1.141     foxr      593: #   PushFile:  Called to do an administrative push of a file.
                    594: #              - Ensure the file being pushed is one we support.
                    595: #              - Backup the old file to <filename.saved>
                    596: #              - Separate the contents of the new file out from the
                    597: #                rest of the request.
                    598: #              - Write the new file.
                    599: #  Parameter:
                    600: #     Request - The entire user request.  This consists of a : separated
                    601: #               string pushfile:tablename:contents.
                    602: #     NOTE:  The contents may have :'s in it as well making things a bit
                    603: #            more interesting... but not much.
                    604: #  Returns:
                    605: #     String to send to client ("ok" or "refused" if bad file).
                    606: #
                    607: sub PushFile {
                    608:     my $request = shift;    
                    609:     my ($command, $filename, $contents) = split(":", $request, 3);
                    610:     
                    611:     #  At this point in time, pushes for only the following tables are
                    612:     #  supported:
                    613:     #   hosts.tab  ($filename eq host).
                    614:     #   domain.tab ($filename eq domain).
                    615:     # Construct the destination filename or reject the request.
                    616:     #
                    617:     # lonManage is supposed to ensure this, however this session could be
                    618:     # part of some elaborate spoof that managed somehow to authenticate.
                    619:     #
                    620: 
1.169     foxr      621: 
                    622:     my $tablefile = ConfigFileFromSelector($filename);
                    623:     if(! (defined $tablefile)) {
1.141     foxr      624: 	return "refused";
                    625:     }
                    626:     #
                    627:     # >copy< the old table to the backup table
                    628:     #        don't rename in case system crashes/reboots etc. in the time
                    629:     #        window between a rename and write.
                    630:     #
                    631:     my $backupfile = $tablefile;
                    632:     $backupfile    =~ s/\.tab$/.old/;
1.143     foxr      633:     if(!CopyFile($tablefile, $backupfile)) {
                    634: 	&logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
                    635: 	return "error:$!";
                    636:     }
1.141     foxr      637:     &logthis('<font color="green"> Pushfile: backed up '
                    638: 	    .$tablefile." to $backupfile</font>");
                    639:     
1.157     foxr      640:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    641:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    642:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    643:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    644:     #  that possibilty.
                    645: 
                    646:     if($filename eq "host") {
                    647: 	$contents = AdjustHostContents($contents);
                    648:     }
                    649: 
1.141     foxr      650:     #  Install the new file:
                    651: 
1.143     foxr      652:     if(!InstallFile($tablefile, $contents)) {
                    653: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      654: 	 .$tablefile." $! </font>");
1.143     foxr      655: 	return "error:$!";
                    656:     }
                    657:     else {
                    658: 	&logthis('<font color="green"> Installed new '.$tablefile
                    659: 		 ."</font>");
                    660: 
                    661:     }
                    662: 
1.141     foxr      663: 
                    664:     #  Indicate success:
                    665:  
                    666:     return "ok";
                    667: 
                    668: }
1.145     foxr      669: 
                    670: #
                    671: #  Called to re-init either lonc or lond.
                    672: #
                    673: #  Parameters:
                    674: #    request   - The full request by the client.  This is of the form
                    675: #                reinit:<process>  
                    676: #                where <process> is allowed to be either of 
                    677: #                lonc or lond
                    678: #
                    679: #  Returns:
                    680: #     The string to be sent back to the client either:
                    681: #   ok         - Everything worked just fine.
                    682: #   error:why  - There was a failure and why describes the reason.
                    683: #
                    684: #
                    685: sub ReinitProcess {
                    686:     my $request = shift;
                    687: 
1.146     foxr      688: 
                    689:     # separate the request (reinit) from the process identifier and
                    690:     # validate it producing the name of the .pid file for the process.
                    691:     #
                    692:     #
                    693:     my ($junk, $process) = split(":", $request);
1.147     foxr      694:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      695:     if($process eq 'lonc') {
                    696: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      697: 	if (!open(PIDFILE, "< $processpidfile")) {
                    698: 	    return "error:Open failed for $processpidfile";
                    699: 	}
                    700: 	my $loncpid = <PIDFILE>;
                    701: 	close(PIDFILE);
                    702: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    703: 		."</font>");
                    704: 	kill("USR2", $loncpid);
1.146     foxr      705:     } elsif ($process eq 'lond') {
1.147     foxr      706: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    707: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      708:     } else {
                    709: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    710: 		 ."</font>");
                    711: 	return "error:Invalid process identifier $process";
                    712:     }
1.145     foxr      713:     return 'ok';
                    714: }
1.168     foxr      715: #   Validate a line in a configuration file edit script:
                    716: #   Validation includes:
                    717: #     - Ensuring the command is valid.
                    718: #     - Ensuring the command has sufficient parameters
                    719: #   Parameters:
                    720: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      721: #
1.168     foxr      722: #   Return:
                    723: #      0     - Invalid scriptline.
                    724: #      1     - Valid scriptline
                    725: #  NOTE:
                    726: #     Only the command syntax is checked, not the executability of the
                    727: #     command.
                    728: #
                    729: sub isValidEditCommand {
                    730:     my $scriptline = shift;
                    731: 
                    732:     #   Line elements are pipe separated:
                    733: 
                    734:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                    735:     &logthis('<font color="green"> isValideditCommand checking: '.
                    736: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                    737:     
                    738:     if ($command eq "delete") {
                    739: 	#
                    740: 	#   key with no newline.
                    741: 	#
                    742: 	if( ($key eq "") || ($newline ne "")) {
                    743: 	    return 0;		# Must have key but no newline.
                    744: 	} else {
                    745: 	    return 1;		# Valid syntax.
                    746: 	}
1.169     foxr      747:     } elsif ($command eq "replace") {
1.168     foxr      748: 	#
                    749: 	#   key and newline:
                    750: 	#
                    751: 	if (($key eq "") || ($newline eq "")) {
                    752: 	    return 0;
                    753: 	} else {
                    754: 	    return 1;
                    755: 	}
1.169     foxr      756:     } elsif ($command eq "append") {
                    757: 	if (($key ne "") && ($newline eq "")) {
                    758: 	    return 1;
                    759: 	} else {
                    760: 	    return 0;
                    761: 	}
1.168     foxr      762:     } else {
                    763: 	return 0;		# Invalid command.
                    764:     }
                    765:     return 0;			# Should not get here!!!
                    766: }
1.169     foxr      767: #
                    768: #   ApplyEdit - Applies an edit command to a line in a configuration 
                    769: #               file.  It is the caller's responsiblity to validate the
                    770: #               edit line.
                    771: #   Parameters:
                    772: #      $directive - A single edit directive to apply.  
                    773: #                   Edit directives are of the form:
                    774: #                  append|newline      - Appends a new line to the file.
                    775: #                  replace|key|newline - Replaces the line with key value 'key'
                    776: #                  delete|key          - Deletes the line with key value 'key'.
                    777: #      $editor   - A config file editor object that contains the
                    778: #                  file being edited.
                    779: #
                    780: sub ApplyEdit {
1.192     foxr      781: 
                    782:     my ($directive, $editor) = @_;
1.169     foxr      783: 
                    784:     # Break the directive down into its command and its parameters
                    785:     # (at most two at this point.  The meaning of the parameters, if in fact
                    786:     #  they exist depends on the command).
                    787: 
                    788:     my ($command, $p1, $p2) = split(/\|/, $directive);
                    789: 
                    790:     if($command eq "append") {
                    791: 	$editor->Append($p1);	          # p1 - key p2 null.
                    792:     } elsif ($command eq "replace") {
                    793: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                    794:     } elsif ($command eq "delete") {
                    795: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                    796:     } else {			          # Should not get here!!!
                    797: 	die "Invalid command given to ApplyEdit $command"
                    798:     }
                    799: }
                    800: #
                    801: # AdjustOurHost:
                    802: #           Adjusts a host file stored in a configuration file editor object
                    803: #           for the true IP address of this host. This is necessary for hosts
                    804: #           that live behind a firewall.
                    805: #           Those hosts have a publicly distributed IP of the firewall, but
                    806: #           internally must use their actual IP.  We assume that a given
                    807: #           host only has a single IP interface for now.
                    808: # Formal Parameters:
                    809: #     editor   - The configuration file editor to adjust.  This
                    810: #                editor is assumed to contain a hosts.tab file.
                    811: # Strategy:
                    812: #    - Figure out our hostname.
                    813: #    - Lookup the entry for this host.
                    814: #    - Modify the line to contain our IP
                    815: #    - Do a replace for this host.
                    816: sub AdjustOurHost {
                    817:     my $editor        = shift;
                    818: 
                    819:     # figure out who I am.
                    820: 
                    821:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                    822: 
                    823:     #  Get my host file entry.
                    824: 
                    825:     my $ConfigLine    = $editor->Find($myHostName);
                    826:     if(! (defined $ConfigLine)) {
                    827: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                    828:     }
                    829:     # figure out my IP:
                    830:     #   Use the config line to get my hostname.
                    831:     #   Use gethostbyname to translate that into an IP address.
                    832:     #
                    833:     my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
                    834:     my $BinaryIp = gethostbyname($name);
                    835:     my $ip       = inet_ntoa($ip);
                    836:     #
                    837:     #  Reassemble the config line from the elements in the list.
                    838:     #  Note that if the loncnew items were not present before, they will
                    839:     #  be now even if they would be empty
                    840:     #
                    841:     my $newConfigLine = $id;
                    842:     foreach my $item ($domain, $role, $name, $ip, $maxcon, $idleto, $mincon) {
                    843: 	$newConfigLine .= ":".$item;
                    844:     }
                    845:     #  Replace the line:
                    846: 
                    847:     $editor->ReplaceLine($id, $newConfigLine);
                    848:     
                    849: }
                    850: #
                    851: #   ReplaceConfigFile:
                    852: #              Replaces a configuration file with the contents of a
                    853: #              configuration file editor object.
                    854: #              This is done by:
                    855: #              - Copying the target file to <filename>.old
                    856: #              - Writing the new file to <filename>.tmp
                    857: #              - Moving <filename.tmp>  -> <filename>
                    858: #              This laborious process ensures that the system is never without
                    859: #              a configuration file that's at least valid (even if the contents
                    860: #              may be dated).
                    861: #   Parameters:
                    862: #        filename   - Name of the file to modify... this is a full path.
                    863: #        editor     - Editor containing the file.
                    864: #
                    865: sub ReplaceConfigFile {
1.192     foxr      866:     
                    867:     my ($filename, $editor) = @_;
1.168     foxr      868: 
1.169     foxr      869:     CopyFile ($filename, $filename.".old");
                    870: 
                    871:     my $contents  = $editor->Get(); # Get the contents of the file.
                    872: 
                    873:     InstallFile($filename, $contents);
                    874: }
1.168     foxr      875: #   
                    876: #
                    877: #   Called to edit a configuration table  file
1.167     foxr      878: #   Parameters:
                    879: #      request           - The entire command/request sent by lonc or lonManage
                    880: #   Return:
                    881: #      The reply to send to the client.
1.168     foxr      882: #
1.167     foxr      883: sub EditFile {
                    884:     my $request = shift;
                    885: 
                    886:     #  Split the command into it's pieces:  edit:filetype:script
                    887: 
1.168     foxr      888:     my ($request, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr      889: 
                    890:     #  Check the pre-coditions for success:
                    891: 
                    892:     if($request != "edit") {	# Something is amiss afoot alack.
                    893: 	return "error:edit request detected, but request != 'edit'\n";
                    894:     }
                    895:     if( ($filetype ne "hosts")  &&
                    896: 	($filetype ne "domain")) {
                    897: 	return "error:edit requested with invalid file specifier: $filetype \n";
                    898:     }
                    899: 
                    900:     #   Split the edit script and check it's validity.
1.168     foxr      901: 
                    902:     my @scriptlines = split(/\n/, $script);  # one line per element.
                    903:     my $linecount   = scalar(@scriptlines);
                    904:     for(my $i = 0; $i < $linecount; $i++) {
                    905: 	chomp($scriptlines[$i]);
                    906: 	if(!isValidEditCommand($scriptlines[$i])) {
                    907: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                    908: 	}
                    909:     }
1.145     foxr      910: 
1.167     foxr      911:     #   Execute the edit operation.
1.169     foxr      912:     #   - Create a config file editor for the appropriate file and 
                    913:     #   - execute each command in the script:
                    914:     #
                    915:     my $configfile = ConfigFileFromSelector($filetype);
                    916:     if (!(defined $configfile)) {
                    917: 	return "refused\n";
                    918:     }
                    919:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr      920: 
1.169     foxr      921:     for (my $i = 0; $i < $linecount; $i++) {
                    922: 	ApplyEdit($scriptlines[$i], $editor);
                    923:     }
                    924:     # If the file is the host file, ensure that our host is
                    925:     # adjusted to have our ip:
                    926:     #
                    927:     if($filetype eq "host") {
                    928: 	AdjustOurHost($editor);
                    929:     }
                    930:     #  Finally replace the current file with our file.
                    931:     #
                    932:     ReplaceConfigFile($configfile, $editor);
1.167     foxr      933: 
                    934:     return "ok\n";
                    935: }
1.207     foxr      936: 
                    937: #---------------------------------------------------------------
                    938: #
                    939: # Manipulation of hash based databases (factoring out common code
                    940: # for later use as we refactor.
                    941: #
                    942: #  Ties a domain level resource file to a hash.
                    943: #  If requested a history entry is created in the associated hist file.
                    944: #
                    945: #  Parameters:
                    946: #     domain    - Name of the domain in which the resource file lives.
                    947: #     namespace - Name of the hash within that domain.
                    948: #     how       - How to tie the hash (e.g. GDBM_WRCREAT()).
                    949: #     loghead   - Optional parameter, if present a log entry is created
                    950: #                 in the associated history file and this is the first part
                    951: #                  of that entry.
                    952: #     logtail   - Goes along with loghead,  The actual logentry is of the
                    953: #                 form $loghead:<timestamp>:logtail.
                    954: # Returns:
                    955: #    Reference to a hash bound to the db file or alternatively undef
                    956: #    if the tie failed.
                    957: #
1.209     albertel  958: sub tie_domain_hash {
1.210     albertel  959:     my ($domain,$namespace,$how,$loghead,$logtail) = @_;
1.207     foxr      960:     
                    961:     # Filter out any whitespace in the domain name:
                    962:     
                    963:     $domain =~ s/\W//g;
                    964:     
                    965:     # We have enough to go on to tie the hash:
                    966:     
                    967:     my $user_top_dir   = $perlvar{'lonUsersDir'};
                    968:     my $domain_dir     = $user_top_dir."/$domain";
                    969:     my $resource_file  = $domain_dir."/$namespace.db";
                    970:     my %hash;
                    971:     if(tie(%hash, 'GDBM_File', $resource_file, $how, 0640)) {
1.211     albertel  972: 	if (defined($loghead)) {	# Need to log the operation.
1.210     albertel  973: 	    my $logFh = IO::File->new(">>$domain_dir/$namespace.hist");
1.207     foxr      974: 	    if($logFh) {
                    975: 		my $timestamp = time;
                    976: 		print $logFh "$loghead:$timestamp:$logtail\n";
                    977: 	    }
1.210     albertel  978: 	    $logFh->close;
1.207     foxr      979: 	}
                    980: 	return \%hash;		# Return the tied hash.
1.210     albertel  981:     } else {
1.207     foxr      982: 	return undef;		# Tie failed.
                    983:     }
                    984: }
                    985: 
                    986: #
                    987: #   Ties a user's resource file to a hash.  
                    988: #   If necessary, an appropriate history
                    989: #   log file entry is made as well.
                    990: #   This sub factors out common code from the subs that manipulate
                    991: #   the various gdbm files that keep keyword value pairs.
                    992: # Parameters:
                    993: #   domain       - Name of the domain the user is in.
                    994: #   user         - Name of the 'current user'.
                    995: #   namespace    - Namespace representing the file to tie.
                    996: #   how          - What the tie is done to (e.g. GDBM_WRCREAT().
                    997: #   loghead      - Optional first part of log entry if there may be a
                    998: #                  history file.
                    999: #   what         - Optional tail of log entry if there may be a history
                   1000: #                  file.
                   1001: # Returns:
                   1002: #   hash to which the database is tied.  It's up to the caller to untie.
                   1003: #   undef if the has could not be tied.
                   1004: #
1.210     albertel 1005: sub tie_user_hash {
                   1006:     my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
1.207     foxr     1007: 
                   1008:     $namespace=~s/\//\_/g;	# / -> _
                   1009:     $namespace=~s/\W//g;		# whitespace eliminated.
                   1010:     my $proname     = propath($domain, $user);
                   1011:    
                   1012:     #  Tie the database.
                   1013:     
                   1014:     my %hash;
                   1015:     if(tie(%hash, 'GDBM_File', "$proname/$namespace.db",
                   1016: 	   $how, 0640)) {
1.209     albertel 1017: 	# If this is a namespace for which a history is kept,
                   1018: 	# make the history log entry:    
1.211     albertel 1019: 	if (($namespace =~/^nohist\_/) && (defined($loghead))) {
1.209     albertel 1020: 	    my $args = scalar @_;
                   1021: 	    Debug(" Opening history: $namespace $args");
                   1022: 	    my $hfh = IO::File->new(">>$proname/$namespace.hist"); 
                   1023: 	    if($hfh) {
                   1024: 		my $now = time;
                   1025: 		print $hfh "$loghead:$now:$what\n";
                   1026: 	    }
1.210     albertel 1027: 	    $hfh->close;
1.209     albertel 1028: 	}
1.207     foxr     1029: 	return \%hash;
1.209     albertel 1030:     } else {
1.207     foxr     1031: 	return undef;
                   1032:     }
                   1033:     
                   1034: }
1.214     foxr     1035: 
                   1036: #--------------------- Request Handlers --------------------------------------------
                   1037: #
1.215     foxr     1038: #   By convention each request handler registers itself prior to the sub 
                   1039: #   declaration:
1.214     foxr     1040: #
                   1041: 
1.216     foxr     1042: #++
                   1043: #
1.214     foxr     1044: #  Handles ping requests.
                   1045: #  Parameters:
                   1046: #      $cmd    - the actual keyword that invoked us.
                   1047: #      $tail   - the tail of the request that invoked us.
                   1048: #      $replyfd- File descriptor connected to the client
                   1049: #  Implicit Inputs:
                   1050: #      $currenthostid - Global variable that carries the name of the host we are
                   1051: #                       known as.
                   1052: #  Returns:
                   1053: #      1       - Ok to continue processing.
                   1054: #      0       - Program should exit.
                   1055: #  Side effects:
                   1056: #      Reply information is sent to the client.
                   1057: 
                   1058: sub ping_handler {
                   1059:     my ($cmd, $tail, $client) = @_;
                   1060:     Debug("$cmd $tail $client .. $currenthostid:");
                   1061:    
                   1062:     Reply( $client,"$currenthostid\n","$cmd:$tail");
                   1063:    
                   1064:     return 1;
                   1065: }
                   1066: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1067: 
1.216     foxr     1068: #++
1.215     foxr     1069: #
                   1070: # Handles pong requests.  Pong replies with our current host id, and
                   1071: #                         the results of a ping sent to us via our lonc.
                   1072: #
                   1073: # Parameters:
                   1074: #      $cmd    - the actual keyword that invoked us.
                   1075: #      $tail   - the tail of the request that invoked us.
                   1076: #      $replyfd- File descriptor connected to the client
                   1077: #  Implicit Inputs:
                   1078: #      $currenthostid - Global variable that carries the name of the host we are
                   1079: #                       connected to.
                   1080: #  Returns:
                   1081: #      1       - Ok to continue processing.
                   1082: #      0       - Program should exit.
                   1083: #  Side effects:
                   1084: #      Reply information is sent to the client.
                   1085: 
                   1086: sub pong_handler {
                   1087:     my ($cmd, $tail, $replyfd) = @_;
                   1088: 
                   1089:     my $reply=&reply("ping",$clientname);
                   1090:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1091:     return 1;
                   1092: }
                   1093: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1094: 
1.216     foxr     1095: #++
                   1096: #      Called to establish an encrypted session key with the remote client.
                   1097: #      Note that with secure lond, in most cases this function is never
                   1098: #      invoked.  Instead, the secure session key is established either
                   1099: #      via a local file that's locked down tight and only lives for a short
                   1100: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1101: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1102: #      by this sub.  This sub is only used in the old-style insecure
                   1103: #      key negotiation.
                   1104: # Parameters:
                   1105: #      $cmd    - the actual keyword that invoked us.
                   1106: #      $tail   - the tail of the request that invoked us.
                   1107: #      $replyfd- File descriptor connected to the client
                   1108: #  Implicit Inputs:
                   1109: #      $currenthostid - Global variable that carries the name of the host
                   1110: #                       known as.
                   1111: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
                   1112: #  Returns:
                   1113: #      1       - Ok to continue processing.
                   1114: #      0       - Program should exit.
                   1115: #  Implicit Outputs:
                   1116: #      Reply information is sent to the client.
                   1117: #      $cipher is set with a reference to a new IDEA encryption object.
                   1118: #
                   1119: sub establish_key_handler {
                   1120:     my ($cmd, $tail, $replyfd) = @_;
                   1121: 
                   1122:     my $buildkey=time.$$.int(rand 100000);
                   1123:     $buildkey=~tr/1-6/A-F/;
                   1124:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1125:     my $key=$currenthostid.$clientname;
                   1126:     $key=~tr/a-z/A-Z/;
                   1127:     $key=~tr/G-P/0-9/;
                   1128:     $key=~tr/Q-Z/0-9/;
                   1129:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1130:     $key=substr($key,0,32);
                   1131:     my $cipherkey=pack("H32",$key);
                   1132:     $cipher=new IDEA $cipherkey;
                   1133:     &Reply($replyfd, "$buildkey\n", "$cmd:$tail"); 
                   1134:    
                   1135:     return 1;
                   1136: 
                   1137: }
                   1138: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1139: 
1.215     foxr     1140: 
1.217   ! foxr     1141: #     Handler for the load command.  Returns the current system load average
        !          1142: #     to the requestor.
        !          1143: #
        !          1144: # Parameters:
        !          1145: #      $cmd    - the actual keyword that invoked us.
        !          1146: #      $tail   - the tail of the request that invoked us.
        !          1147: #      $replyfd- File descriptor connected to the client
        !          1148: #  Implicit Inputs:
        !          1149: #      $currenthostid - Global variable that carries the name of the host
        !          1150: #                       known as.
        !          1151: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
        !          1152: #  Returns:
        !          1153: #      1       - Ok to continue processing.
        !          1154: #      0       - Program should exit.
        !          1155: #  Side effects:
        !          1156: #      Reply information is sent to the client.
        !          1157: sub load_handler {
        !          1158:     my ($cmd, $tail, $replyfd) = @_;
        !          1159: 
        !          1160:    # Get the load average from /proc/loadavg and calculate it as a percentage of
        !          1161:    # the allowed load limit as set by the perl global variable lonLoadLim
        !          1162: 
        !          1163:     my $loadavg;
        !          1164:     my $loadfile=IO::File->new('/proc/loadavg');
        !          1165:    
        !          1166:     $loadavg=<$loadfile>;
        !          1167:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
        !          1168:    
        !          1169:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
        !          1170: 
        !          1171:     &Reply( $replyfd, "$loadpercent\n", "$cmd:$tail");
        !          1172:    
        !          1173:     return 1;
        !          1174: }
        !          1175: register_handler("load", \&load_handler, 0, 1, 0);
        !          1176: 
        !          1177: #
        !          1178: #   Process the userload request.  This sub returns to the client the current
        !          1179: #  user load average.  It can be invoked either by clients or managers.
        !          1180: #
        !          1181: # Parameters:
        !          1182: #      $cmd    - the actual keyword that invoked us.
        !          1183: #      $tail   - the tail of the request that invoked us.
        !          1184: #      $replyfd- File descriptor connected to the client
        !          1185: #  Implicit Inputs:
        !          1186: #      $currenthostid - Global variable that carries the name of the host
        !          1187: #                       known as.
        !          1188: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
        !          1189: #  Returns:
        !          1190: #      1       - Ok to continue processing.
        !          1191: #      0       - Program should exit
        !          1192: # Implicit inputs:
        !          1193: #     whatever the userload() function requires.
        !          1194: #  Implicit outputs:
        !          1195: #     the reply is written to the client.
        !          1196: #
        !          1197: sub user_load_handler {
        !          1198:     my ($cmd, $tail, $replyfd) = @_;
        !          1199: 
        !          1200:     my $userloadpercent=&userload();
        !          1201:     &Reply($replyfd, "$userloadpercent\n", "$cmd:$tail");
        !          1202:     
        !          1203:     return 1;
        !          1204: }
        !          1205: register_handler("userload", \&user_load_handler, 0, 1, 0);
        !          1206: 
1.214     foxr     1207: 
1.207     foxr     1208: #---------------------------------------------------------------
                   1209: #
                   1210: #   Getting, decoding and dispatching requests:
                   1211: #
                   1212: 
                   1213: #
                   1214: #   Get a Request:
                   1215: #   Gets a Request message from the client.  The transaction
                   1216: #   is defined as a 'line' of text.  We remove the new line
                   1217: #   from the text line.  
                   1218: #   
1.211     albertel 1219: sub get_request {
1.207     foxr     1220:     my $input = <$client>;
                   1221:     chomp($input);
                   1222: 
1.212     foxr     1223:     Debug("get_request: Request = $input\n");
1.207     foxr     1224: 
                   1225:     &status('Processing '.$clientname.':'.$input);
                   1226: 
                   1227:     return $input;
                   1228: }
1.212     foxr     1229: #---------------------------------------------------------------
                   1230: #
                   1231: #  Process a request.  This sub should shrink as each action
                   1232: #  gets farmed out into a separat sub that is registered 
                   1233: #  with the dispatch hash.  
                   1234: #
                   1235: # Parameters:
                   1236: #    user_input   - The request received from the client (lonc).
                   1237: # Returns:
                   1238: #    true to keep processing, false if caller should exit.
                   1239: #
                   1240: sub process_request {
                   1241:     my ($userinput) = @_;      # Easier for now to break style than to
                   1242:                                 # fix all the userinput -> user_input.
                   1243:     my $wasenc    = 0;		# True if request was encrypted.
                   1244: # ------------------------------------------------------------ See if encrypted
                   1245:     if ($userinput =~ /^enc/) {
                   1246: 	$userinput = decipher($userinput);
                   1247: 	$wasenc=1;
                   1248: 	if(!$userinput) {	# Cipher not defined.
                   1249: 	    &Failure($client, "error: Encrypted data without negotated key");
                   1250: 	    return 0;
                   1251: 	}
                   1252:     }
                   1253:     Debug("process_request: $userinput\n");
                   1254:     
1.213     foxr     1255:     #  
                   1256:     #   The 'correct way' to add a command to lond is now to
                   1257:     #   write a sub to execute it and Add it to the command dispatch
                   1258:     #   hash via a call to register_handler..  The comments to that
                   1259:     #   sub should give you enough to go on to show how to do this
                   1260:     #   along with the examples that are building up as this code
                   1261:     #   is getting refactored.   Until all branches of the
                   1262:     #   if/elseif monster below have been factored out into
                   1263:     #   separate procesor subs, if the dispatch hash is missing
                   1264:     #   the command keyword, we will fall through to the remainder
                   1265:     #   of the if/else chain below in order to keep this thing in 
                   1266:     #   working order throughout the transmogrification.
                   1267: 
                   1268:     my ($command, $tail) = split(/:/, $userinput, 2);
                   1269:     chomp($command);
                   1270:     chomp($tail);
                   1271:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     1272:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   1273:     if(!$tail) {
                   1274: 	$tail ="";		# defined but blank.
                   1275:     }
1.213     foxr     1276: 
                   1277:     &Debug("Command received: $command, encoded = $wasenc");
                   1278: 
                   1279:     if(defined $Dispatcher{$command}) {
                   1280: 
                   1281: 	my $dispatch_info = $Dispatcher{$command};
                   1282: 	my $handler       = $$dispatch_info[0];
                   1283: 	my $need_encode   = $$dispatch_info[1];
                   1284: 	my $client_types  = $$dispatch_info[2];
                   1285: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   1286: 	      ."ClientType $client_types");
                   1287:       
                   1288: 	#  Validate the request:
                   1289:       
                   1290: 	my $ok = 1;
                   1291: 	my $requesterprivs = 0;
                   1292: 	if(&isClient()) {
                   1293: 	    $requesterprivs |= $CLIENT_OK;
                   1294: 	}
                   1295: 	if(&isManager()) {
                   1296: 	    $requesterprivs |= $MANAGER_OK;
                   1297: 	}
                   1298: 	if($need_encode && (!$wasenc)) {
                   1299: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   1300: 	    $ok = 0;
                   1301: 	}
                   1302: 	if(($client_types & $requesterprivs) == 0) {
                   1303: 	    Debug("Client not privileged to do this operation");
                   1304: 	    $ok = 0;
                   1305: 	}
                   1306: 
                   1307: 	if($ok) {
                   1308: 	    Debug("Dispatching to handler $command $tail");
                   1309: 	    my $keep_going = &$handler($command, $tail, $client);
                   1310: 	    return $keep_going;
                   1311: 	} else {
                   1312: 	    Debug("Refusing to dispatch because client did not match requirements");
                   1313: 	    Failure($client, "refused\n", $userinput);
                   1314: 	    return 1;
                   1315: 	}
                   1316: 
                   1317:     }    
                   1318: 
1.215     foxr     1319: #------------------- Commands not yet in spearate handlers. --------------
                   1320: 
1.212     foxr     1321: # ----------------------------------------------------------------- currentauth
1.217   ! foxr     1322:     if ($userinput =~ /^currentauth/) {
1.212     foxr     1323: 	if (($wasenc==1)  && isClient) { # Encoded & client only.
                   1324: 	    my ($cmd,$udom,$uname)=split(/:/,$userinput);
                   1325: 	    my $result = GetAuthType($udom, $uname);
                   1326: 	    if($result eq "nouser") {
                   1327: 		print $client "unknown_user\n";
                   1328: 	    }
                   1329: 	    else {
                   1330: 		print $client "$result\n";
                   1331: 	    }
                   1332: 	} else {
                   1333: 	    Reply($client, "refused\n", $userinput);
                   1334: 	    
                   1335: 	}
                   1336: #--------------------------------------------------------------------- pushfile
                   1337:     } elsif($userinput =~ /^pushfile/) {	# encoded & manager.
                   1338: 	if(($wasenc == 1) && isManager) {
                   1339: 	    my $cert = GetCertificate($userinput);
                   1340: 	    if(ValidManager($cert)) {
                   1341: 		my $reply = PushFile($userinput);
                   1342: 		print $client "$reply\n";
                   1343: 	    } else {
                   1344: 		print $client "refused\n";
                   1345: 	    } 
                   1346: 	} else {
                   1347: 	    Reply($client, "refused\n", $userinput);
                   1348: 	    
                   1349: 	}
                   1350: #--------------------------------------------------------------------- reinit
                   1351:     } elsif($userinput =~ /^reinit/) { # Encoded and manager
                   1352: 	if (($wasenc == 1) && isManager) {
                   1353: 	    my $cert = GetCertificate($userinput);
                   1354: 	    if(ValidManager($cert)) {
                   1355: 		chomp($userinput);
                   1356: 		my $reply = ReinitProcess($userinput);
                   1357: 		print $client  "$reply\n";
                   1358: 	    } else {
                   1359: 		print $client "refused\n";
                   1360: 	    }
                   1361: 	} else {
                   1362: 	    Reply($client, "refused\n", $userinput);
                   1363: 	}
                   1364: #------------------------------------------------------------------------- edit
                   1365:     } elsif ($userinput =~ /^edit/) {    # encoded and manager:
                   1366: 	if(($wasenc ==1) && (isManager)) {
                   1367: 	    my $cert = GetCertificate($userinput);
                   1368: 	    if(ValidManager($cert)) {
                   1369: 		my($command, $filetype, $script) = split(/:/, $userinput);
                   1370: 		if (($filetype eq "hosts") || ($filetype eq "domain")) {
                   1371: 		    if($script ne "") {
                   1372: 			Reply($client, EditFile($userinput));
                   1373: 		    } else {
                   1374: 			Reply($client,"refused\n",$userinput);
                   1375: 		    }
                   1376: 		} else {
                   1377: 		    Reply($client,"refused\n",$userinput);
                   1378: 		}
                   1379:             } else {
                   1380: 		Reply($client,"refused\n",$userinput);
                   1381:             }
                   1382: 	} else {
                   1383: 	    Reply($client,"refused\n",$userinput);
                   1384: 	}
                   1385: # ------------------------------------------------------------------------ auth
                   1386:     } elsif ($userinput =~ /^auth/) { # Encoded and client only.
                   1387: 	if (($wasenc==1) && isClient) {
                   1388: 	    my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
                   1389: 	    chomp($upass);
                   1390: 	    $upass=unescape($upass);
                   1391: 	    my $proname=propath($udom,$uname);
                   1392: 	    my $passfilename="$proname/passwd";
                   1393: 	    if (-e $passfilename) {
                   1394: 		my $pf = IO::File->new($passfilename);
                   1395: 		my $realpasswd=<$pf>;
                   1396: 		chomp($realpasswd);
                   1397: 		my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   1398: 		my $pwdcorrect=0;
                   1399: 		if ($howpwd eq 'internal') {
                   1400: 		    &Debug("Internal auth");
                   1401: 		    $pwdcorrect=
                   1402: 			(crypt($upass,$contentpwd) eq $contentpwd);
                   1403: 		} elsif ($howpwd eq 'unix') {
                   1404: 		    &Debug("Unix auth");
                   1405: 		    if((getpwnam($uname))[1] eq "") { #no such user!
                   1406: 			$pwdcorrect = 0;
                   1407: 		    } else {
                   1408: 			$contentpwd=(getpwnam($uname))[1];
                   1409: 			my $pwauth_path="/usr/local/sbin/pwauth";
                   1410: 			unless ($contentpwd eq 'x') {
                   1411: 			    $pwdcorrect=
                   1412: 				(crypt($upass,$contentpwd) eq 
                   1413: 				 $contentpwd);
                   1414: 			}
                   1415: 			
                   1416: 			elsif (-e $pwauth_path) {
                   1417: 			    open PWAUTH, "|$pwauth_path" or
                   1418: 				die "Cannot invoke authentication";
                   1419: 			    print PWAUTH "$uname\n$upass\n";
                   1420: 			    close PWAUTH;
                   1421: 			    $pwdcorrect=!$?;
                   1422: 			}
                   1423: 		    }
                   1424: 		} elsif ($howpwd eq 'krb4') {
                   1425: 		    my $null=pack("C",0);
                   1426: 		    unless ($upass=~/$null/) {
                   1427: 			my $krb4_error = &Authen::Krb4::get_pw_in_tkt
                   1428: 			    ($uname,"",$contentpwd,'krbtgt',
                   1429: 			     $contentpwd,1,$upass);
                   1430: 			if (!$krb4_error) {
                   1431: 			    $pwdcorrect = 1;
                   1432: 			} else { 
                   1433: 			    $pwdcorrect=0; 
                   1434: 			    # log error if it is not a bad password
                   1435: 			    if ($krb4_error != 62) {
                   1436: 				&logthis('krb4:'.$uname.','.
                   1437: 					 &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   1438: 			    }
                   1439: 			}
                   1440: 		    }
                   1441: 		} elsif ($howpwd eq 'krb5') {
                   1442: 		    my $null=pack("C",0);
                   1443: 		    unless ($upass=~/$null/) {
                   1444: 			my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
                   1445: 			my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
                   1446: 			my $krbserver=&Authen::Krb5::parse_name($krbservice);
                   1447: 			my $credentials=&Authen::Krb5::cc_default();
                   1448: 			$credentials->initialize($krbclient);
                   1449: 			my $krbreturn = 
                   1450: 			    &Authen::Krb5::get_in_tkt_with_password(
                   1451: 								    $krbclient,$krbserver,$upass,$credentials);
                   1452: #				  unless ($krbreturn) {
                   1453: #				      &logthis("Krb5 Error: ".
                   1454: #					       &Authen::Krb5::error());
                   1455: #				  }
                   1456: 			$pwdcorrect = ($krbreturn == 1);
                   1457: 		    } else { $pwdcorrect=0; }
                   1458: 		} elsif ($howpwd eq 'localauth') {
                   1459: 		    $pwdcorrect=&localauth::localauth($uname,$upass,
                   1460: 						      $contentpwd);
                   1461: 		}
                   1462: 		if ($pwdcorrect) {
                   1463: 		    print $client "authorized\n";
                   1464: 		} else {
                   1465: 		    print $client "non_authorized\n";
                   1466: 		}  
                   1467: 	    } else {
                   1468: 		print $client "unknown_user\n";
                   1469: 	    }
                   1470: 	} else {
                   1471: 	    Reply($client, "refused\n", $userinput);
                   1472: 	    
                   1473: 	}
                   1474: # ---------------------------------------------------------------------- passwd
                   1475:     } elsif ($userinput =~ /^passwd/) { # encoded and client
                   1476: 	if (($wasenc==1) && isClient) {
                   1477: 	    my 
                   1478: 		($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
                   1479: 	    chomp($npass);
                   1480: 	    $upass=&unescape($upass);
                   1481: 	    $npass=&unescape($npass);
                   1482: 	    &Debug("Trying to change password for $uname");
                   1483: 	    my $proname=propath($udom,$uname);
                   1484: 	    my $passfilename="$proname/passwd";
                   1485: 	    if (-e $passfilename) {
                   1486: 		my $realpasswd;
                   1487: 		{ my $pf = IO::File->new($passfilename);
                   1488: 		  $realpasswd=<$pf>; }
                   1489: 		chomp($realpasswd);
                   1490: 		my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   1491: 		if ($howpwd eq 'internal') {
                   1492: 		    &Debug("internal auth");
                   1493: 		    if (crypt($upass,$contentpwd) eq $contentpwd) {
                   1494: 			my $salt=time;
                   1495: 			$salt=substr($salt,6,2);
                   1496: 			my $ncpass=crypt($npass,$salt);
                   1497: 			{
                   1498: 			    my $pf;
                   1499: 			    if ($pf = IO::File->new(">$passfilename")) {
                   1500: 				print $pf "internal:$ncpass\n";
                   1501: 				&logthis("Result of password change for $uname: pwchange_success");
                   1502: 				print $client "ok\n";
                   1503: 			    } else {
                   1504: 				&logthis("Unable to open $uname passwd to change password");
                   1505: 				print $client "non_authorized\n";
                   1506: 			    }
                   1507: 			}             
                   1508: 			
                   1509: 		    } else {
                   1510: 			print $client "non_authorized\n";
                   1511: 		    }
                   1512: 		} elsif ($howpwd eq 'unix') {
                   1513: 		    # Unix means we have to access /etc/password
                   1514: 		    # one way or another.
                   1515: 		    # First: Make sure the current password is
                   1516: 		    #        correct
                   1517: 		    &Debug("auth is unix");
                   1518: 		    $contentpwd=(getpwnam($uname))[1];
                   1519: 		    my $pwdcorrect = "0";
                   1520: 		    my $pwauth_path="/usr/local/sbin/pwauth";
                   1521: 		    unless ($contentpwd eq 'x') {
                   1522: 			$pwdcorrect=
                   1523: 			    (crypt($upass,$contentpwd) eq $contentpwd);
                   1524: 		    } elsif (-e $pwauth_path) {
                   1525: 			open PWAUTH, "|$pwauth_path" or
                   1526: 			    die "Cannot invoke authentication";
                   1527: 			print PWAUTH "$uname\n$upass\n";
                   1528: 			close PWAUTH;
                   1529: 			&Debug("exited pwauth with $? ($uname,$upass) ");
                   1530: 			$pwdcorrect=($? == 0);
                   1531: 		    }
                   1532: 		    if ($pwdcorrect) {
                   1533: 			my $execdir=$perlvar{'lonDaemons'};
                   1534: 			&Debug("Opening lcpasswd pipeline");
                   1535: 			my $pf = IO::File->new("|$execdir/lcpasswd > $perlvar{'lonDaemons'}/logs/lcpasswd.log");
                   1536: 			print $pf "$uname\n$npass\n$npass\n";
                   1537: 			close $pf;
                   1538: 			my $err = $?;
                   1539: 			my $result = ($err>0 ? 'pwchange_failure' 
                   1540: 				      : 'ok');
                   1541: 			&logthis("Result of password change for $uname: ".
                   1542: 				 &lcpasswdstrerror($?));
                   1543: 			print $client "$result\n";
                   1544: 		    } else {
                   1545: 			print $client "non_authorized\n";
                   1546: 		    }
                   1547: 		} else {
                   1548: 		    print $client "auth_mode_error\n";
                   1549: 		}  
                   1550: 	    } else {
                   1551: 		print $client "unknown_user\n";
                   1552: 	    }
                   1553: 	} else {
                   1554: 	    Reply($client, "refused\n", $userinput);
                   1555: 	    
                   1556: 	}
                   1557: # -------------------------------------------------------------------- makeuser
                   1558:     } elsif ($userinput =~ /^makeuser/) { # encoded and client.
                   1559: 	&Debug("Make user received");
                   1560: 	my $oldumask=umask(0077);
                   1561: 	if (($wasenc==1) && isClient) {
                   1562: 	    my 
                   1563: 		($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
                   1564: 	    &Debug("cmd =".$cmd." $udom =".$udom.
                   1565: 		   " uname=".$uname);
                   1566: 	    chomp($npass);
                   1567: 	    $npass=&unescape($npass);
                   1568: 	    my $proname=propath($udom,$uname);
                   1569: 	    my $passfilename="$proname/passwd";
                   1570: 	    &Debug("Password file created will be:".
                   1571: 		   $passfilename);
                   1572: 	    if (-e $passfilename) {
                   1573: 		print $client "already_exists\n";
                   1574: 	    } elsif ($udom ne $currentdomainid) {
                   1575: 		print $client "not_right_domain\n";
                   1576: 	    } else {
                   1577: 		my @fpparts=split(/\//,$proname);
                   1578: 		my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
                   1579: 		my $fperror='';
                   1580: 		for (my $i=3;$i<=$#fpparts;$i++) {
                   1581: 		    $fpnow.='/'.$fpparts[$i]; 
                   1582: 		    unless (-e $fpnow) {
                   1583: 			unless (mkdir($fpnow,0777)) {
                   1584: 			    $fperror="error: ".($!+0)
                   1585: 				." mkdir failed while attempting "
                   1586: 				."makeuser";
                   1587: 			}
                   1588: 		    }
                   1589: 		}
                   1590: 		unless ($fperror) {
                   1591: 		    my $result=&make_passwd_file($uname, $umode,$npass,
                   1592: 						 $passfilename);
                   1593: 		    print $client $result;
                   1594: 		} else {
                   1595: 		    print $client "$fperror\n";
                   1596: 		}
                   1597: 	    }
                   1598: 	} else {
                   1599: 	    Reply($client, "refused\n", $userinput);
                   1600: 	    
                   1601: 	}
                   1602: 	umask($oldumask);
                   1603: # -------------------------------------------------------------- changeuserauth
                   1604:     } elsif ($userinput =~ /^changeuserauth/) { # encoded & client
                   1605: 	&Debug("Changing authorization");
                   1606: 	if (($wasenc==1) && isClient) {
                   1607: 	    my 
                   1608: 		($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
                   1609: 	    chomp($npass);
                   1610: 	    &Debug("cmd = ".$cmd." domain= ".$udom.
                   1611: 		   "uname =".$uname." umode= ".$umode);
                   1612: 	    $npass=&unescape($npass);
                   1613: 	    my $proname=&propath($udom,$uname);
                   1614: 	    my $passfilename="$proname/passwd";
                   1615: 	    if ($udom ne $currentdomainid) {
                   1616: 		print $client "not_right_domain\n";
                   1617: 	    } else {
                   1618: 		my $result=&make_passwd_file($uname, $umode,$npass,
                   1619: 					     $passfilename);
                   1620: 		print $client $result;
                   1621: 	    }
                   1622: 	} else {
                   1623: 	    Reply($client, "refused\n", $userinput);
                   1624: 	    
                   1625: 	}
                   1626: # ------------------------------------------------------------------------ home
                   1627:     } elsif ($userinput =~ /^home/) { # client clear or encoded
                   1628: 	if(isClient) {
                   1629: 	    my ($cmd,$udom,$uname)=split(/:/,$userinput);
                   1630: 	    chomp($uname);
                   1631: 	    my $proname=propath($udom,$uname);
                   1632: 	    if (-e $proname) {
                   1633: 		print $client "found\n";
                   1634: 	    } else {
                   1635: 		print $client "not_found\n";
                   1636: 	    }
                   1637: 	} else {
                   1638: 	    Reply($client, "refused\n", $userinput);
                   1639: 	    
                   1640: 	}
                   1641: # ---------------------------------------------------------------------- update
                   1642:     } elsif ($userinput =~ /^update/) { # client clear or encoded.
                   1643: 	if(isClient) {
                   1644: 	    my ($cmd,$fname)=split(/:/,$userinput);
                   1645: 	    my $ownership=ishome($fname);
                   1646: 	    if ($ownership eq 'not_owner') {
                   1647: 		if (-e $fname) {
                   1648: 		    my ($dev,$ino,$mode,$nlink,
                   1649: 			$uid,$gid,$rdev,$size,
                   1650: 			$atime,$mtime,$ctime,
                   1651: 			$blksize,$blocks)=stat($fname);
                   1652: 		    my $now=time;
                   1653: 		    my $since=$now-$atime;
                   1654: 		    if ($since>$perlvar{'lonExpire'}) {
                   1655: 			my $reply=
                   1656: 			    &reply("unsub:$fname","$clientname");
                   1657: 				    unlink("$fname");
                   1658: 		    } else {
                   1659: 			my $transname="$fname.in.transfer";
                   1660: 			my $remoteurl=
                   1661: 			    &reply("sub:$fname","$clientname");
                   1662: 			my $response;
                   1663: 			{
                   1664: 			    my $ua=new LWP::UserAgent;
                   1665: 			    my $request=new HTTP::Request('GET',"$remoteurl");
                   1666: 			    $response=$ua->request($request,$transname);
                   1667: 			}
                   1668: 			if ($response->is_error()) {
                   1669: 			    unlink($transname);
                   1670: 			    my $message=$response->status_line;
                   1671: 			    &logthis(
                   1672: 				     "LWP GET: $message for $fname ($remoteurl)");
                   1673: 			} else {
                   1674: 			    if ($remoteurl!~/\.meta$/) {
                   1675: 				my $ua=new LWP::UserAgent;
                   1676: 				my $mrequest=
                   1677: 				    new HTTP::Request('GET',$remoteurl.'.meta');
                   1678: 				my $mresponse=
                   1679: 				    $ua->request($mrequest,$fname.'.meta');
                   1680: 				if ($mresponse->is_error()) {
                   1681: 				    unlink($fname.'.meta');
                   1682: 				}
                   1683: 			    }
                   1684: 			    rename($transname,$fname);
                   1685: 			}
                   1686: 		    }
                   1687: 		    print $client "ok\n";
                   1688: 		} else {
                   1689: 		    print $client "not_found\n";
                   1690: 		}
                   1691: 	    } else {
                   1692: 		print $client "rejected\n";
                   1693: 	    }
                   1694: 	} else {
                   1695: 	    Reply($client, "refused\n", $userinput);
                   1696: 	    
                   1697: 	}
                   1698: # -------------------------------------- fetch a user file from a remote server
                   1699:     } elsif ($userinput =~ /^fetchuserfile/) { # Client clear or enc.
                   1700: 	if(isClient) {
                   1701: 	    my ($cmd,$fname)=split(/:/,$userinput);
                   1702: 	    my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   1703: 	    my $udir=propath($udom,$uname).'/userfiles';
                   1704: 	    unless (-e $udir) { mkdir($udir,0770); }
                   1705: 	    if (-e $udir) {
                   1706: 		$ufile=~s/^[\.\~]+//;
                   1707: 		my $path = $udir;
                   1708: 		if ($ufile =~m|(.+)/([^/]+)$|) {
                   1709: 		    my @parts=split('/',$1);
                   1710: 		    foreach my $part (@parts) {
                   1711: 			$path .= '/'.$part;
                   1712: 			if ((-e $path)!=1) {
                   1713: 			    mkdir($path,0770);
                   1714: 			}
                   1715: 		    }
                   1716: 		}
                   1717: 		my $destname=$udir.'/'.$ufile;
                   1718: 		my $transname=$udir.'/'.$ufile.'.in.transit';
                   1719: 		my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
                   1720: 		my $response;
                   1721: 		{
                   1722: 		    my $ua=new LWP::UserAgent;
                   1723: 		    my $request=new HTTP::Request('GET',"$remoteurl");
                   1724: 		    $response=$ua->request($request,$transname);
                   1725: 		}
                   1726: 		if ($response->is_error()) {
                   1727: 		    unlink($transname);
                   1728: 		    my $message=$response->status_line;
                   1729: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   1730: 		    print $client "failed\n";
                   1731: 		} else {
                   1732: 		    if (!rename($transname,$destname)) {
                   1733: 			&logthis("Unable to move $transname to $destname");
                   1734: 			unlink($transname);
                   1735: 			print $client "failed\n";
                   1736: 		    } else {
                   1737: 			print $client "ok\n";
                   1738: 		    }
                   1739: 		}
                   1740: 	    } else {
                   1741: 		print $client "not_home\n";
                   1742: 	    }
                   1743: 	} else {
                   1744: 	    Reply($client, "refused\n", $userinput);
                   1745: 	}
                   1746: # --------------------------------------------------------- remove a user file 
                   1747:     } elsif ($userinput =~ /^removeuserfile/) { # Client clear or enc.
                   1748: 	if(isClient) {
                   1749: 	    my ($cmd,$fname)=split(/:/,$userinput);
                   1750: 	    my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   1751: 	    &logthis("$udom - $uname - $ufile");
                   1752: 	    if ($ufile =~m|/\.\./|) {
                   1753: 		# any files paths with /../ in them refuse 
                   1754: 		# to deal with
                   1755: 		print $client "refused\n";
                   1756: 	    } else {
                   1757: 		my $udir=propath($udom,$uname);
                   1758: 		if (-e $udir) {
                   1759: 		    my $file=$udir.'/userfiles/'.$ufile;
                   1760: 		    if (-e $file) {
                   1761: 			unlink($file);
                   1762: 			if (-e $file) {
                   1763: 			    print $client "failed\n";
                   1764: 			} else {
                   1765: 			    print $client "ok\n";
                   1766: 			}
                   1767: 		    } else {
                   1768: 			print $client "not_found\n";
                   1769: 		    }
                   1770: 		} else {
                   1771: 		    print $client "not_home\n";
                   1772: 		}
                   1773: 	    }
                   1774: 	} else {
                   1775: 	    Reply($client, "refused\n", $userinput);
                   1776: 	}
                   1777: # ------------------------------------------ authenticate access to a user file
                   1778:     } elsif ($userinput =~ /^tokenauthuserfile/) { # Client only
                   1779: 	if(isClient) {
                   1780: 	    my ($cmd,$fname,$session)=split(/:/,$userinput);
                   1781: 	    chomp($session);
                   1782: 	    my $reply='non_auth';
                   1783: 	    if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
                   1784: 		     $session.'.id')) {
                   1785: 		while (my $line=<ENVIN>) {
                   1786: 		    if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply='ok'; }
                   1787: 			    }
                   1788: 		close(ENVIN);
                   1789: 		print $client $reply."\n";
                   1790: 	    } else {
                   1791: 		print $client "invalid_token\n";
                   1792: 	    }
                   1793: 	} else {
                   1794: 	    Reply($client, "refused\n", $userinput);
                   1795: 	    
                   1796: 	}
                   1797: # ----------------------------------------------------------------- unsubscribe
                   1798:     } elsif ($userinput =~ /^unsub/) {
                   1799: 	if(isClient) {
                   1800: 	    my ($cmd,$fname)=split(/:/,$userinput);
                   1801: 	    if (-e $fname) {
                   1802: 		print $client &unsub($fname,$clientip);
                   1803: 	    } else {
                   1804: 		print $client "not_found\n";
                   1805: 	    }
                   1806: 	} else {
                   1807: 	    Reply($client, "refused\n", $userinput);
                   1808: 	    
                   1809: 	}
                   1810: # ------------------------------------------------------------------- subscribe
                   1811:     } elsif ($userinput =~ /^sub/) {
                   1812: 	if(isClient) {
                   1813: 	    print $client &subscribe($userinput,$clientip);
                   1814: 	} else {
                   1815: 	    Reply($client, "refused\n", $userinput);
                   1816: 	    
                   1817: 	}
                   1818: # ------------------------------------------------------------- current version
                   1819:     } elsif ($userinput =~ /^currentversion/) {
                   1820: 	if(isClient) {
                   1821: 	    my ($cmd,$fname)=split(/:/,$userinput);
                   1822: 	    print $client &currentversion($fname)."\n";
                   1823: 	} else {
                   1824: 	    Reply($client, "refused\n", $userinput);
                   1825: 	    
                   1826: 	}
                   1827: # ------------------------------------------------------------------------- log
                   1828:     } elsif ($userinput =~ /^log/) {
                   1829: 	if(isClient) {
                   1830: 	    my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
                   1831: 	    chomp($what);
                   1832: 	    my $proname=propath($udom,$uname);
                   1833: 	    my $now=time;
                   1834: 	    {
                   1835: 		my $hfh;
                   1836: 		if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   1837: 		    print $hfh "$now:$clientname:$what\n";
                   1838: 		    print $client "ok\n"; 
                   1839: 		} else {
                   1840: 		    print $client "error: ".($!+0)
                   1841: 			." IO::File->new Failed "
                   1842: 			."while attempting log\n";
                   1843: 		}
                   1844: 	    }
                   1845: 	} else {
                   1846: 	    Reply($client, "refused\n", $userinput);
                   1847: 	    
                   1848: 	}
                   1849: # ------------------------------------------------------------------------- put
                   1850:     } elsif ($userinput =~ /^put/) {
                   1851: 	if(isClient) {
                   1852: 	    my ($cmd,$udom,$uname,$namespace,$what)
                   1853: 		=split(/:/,$userinput,5);
                   1854: 	    $namespace=~s/\//\_/g;
                   1855: 	    $namespace=~s/\W//g;
                   1856: 	    if ($namespace ne 'roles') {
                   1857: 		chomp($what);
                   1858: 		my $proname=propath($udom,$uname);
                   1859: 		my $now=time;
                   1860: 		my @pairs=split(/\&/,$what);
                   1861: 		my %hash;
                   1862: 		if (tie(%hash,'GDBM_File',
                   1863: 			"$proname/$namespace.db",
                   1864: 			&GDBM_WRCREAT(),0640)) {
                   1865: 		    unless ($namespace=~/^nohist\_/) {
                   1866: 			my $hfh;
                   1867: 			if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
                   1868: 		    }
                   1869: 		    
                   1870: 		    foreach my $pair (@pairs) {
                   1871: 			my ($key,$value)=split(/=/,$pair);
                   1872: 			$hash{$key}=$value;
                   1873: 		    }
                   1874: 		    if (untie(%hash)) {
                   1875: 			print $client "ok\n";
                   1876: 		    } else {
                   1877: 			print $client "error: ".($!+0)
                   1878: 			    ." untie(GDBM) failed ".
                   1879: 			    "while attempting put\n";
                   1880: 		    }
                   1881: 		} else {
                   1882: 		    print $client "error: ".($!)
                   1883: 			." tie(GDBM) Failed ".
                   1884: 			"while attempting put\n";
                   1885: 		}
                   1886: 	    } else {
                   1887: 		print $client "refused\n";
                   1888: 	    }
                   1889: 	} else {
                   1890: 	    Reply($client, "refused\n", $userinput);
                   1891: 	    
                   1892: 	}
                   1893: # ------------------------------------------------------------------- inc
                   1894:     } elsif ($userinput =~ /^inc:/) {
                   1895: 	if(isClient) {
                   1896: 	    my ($cmd,$udom,$uname,$namespace,$what)
                   1897: 		=split(/:/,$userinput);
                   1898: 	    $namespace=~s/\//\_/g;
                   1899: 	    $namespace=~s/\W//g;
                   1900: 	    if ($namespace ne 'roles') {
                   1901: 		chomp($what);
                   1902: 		my $proname=propath($udom,$uname);
                   1903: 		my $now=time;
                   1904: 		my @pairs=split(/\&/,$what);
                   1905: 		my %hash;
                   1906: 		if (tie(%hash,'GDBM_File',
                   1907: 			"$proname/$namespace.db",
                   1908: 			&GDBM_WRCREAT(),0640)) {
                   1909: 		    unless ($namespace=~/^nohist\_/) {
                   1910: 			my $hfh;
                   1911: 			if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
                   1912: 		    }
                   1913: 		    foreach my $pair (@pairs) {
                   1914: 			my ($key,$value)=split(/=/,$pair);
                   1915: 			# We could check that we have a number...
                   1916: 			if (! defined($value) || $value eq '') {
                   1917: 			    $value = 1;
                   1918: 			}
                   1919: 			$hash{$key}+=$value;
                   1920: 		    }
                   1921: 		    if (untie(%hash)) {
                   1922: 			print $client "ok\n";
                   1923: 		    } else {
                   1924: 			print $client "error: ".($!+0)
                   1925: 			    ." untie(GDBM) failed ".
                   1926: 			    "while attempting inc\n";
                   1927: 		    }
                   1928: 		} else {
                   1929: 		    print $client "error: ".($!)
                   1930: 			." tie(GDBM) Failed ".
                   1931: 			"while attempting inc\n";
                   1932: 		}
                   1933: 	    } else {
                   1934: 		print $client "refused\n";
                   1935: 	    }
                   1936: 	} else {
                   1937: 	    Reply($client, "refused\n", $userinput);
                   1938: 	    
                   1939: 	}
                   1940: # -------------------------------------------------------------------- rolesput
                   1941:     } elsif ($userinput =~ /^rolesput/) {
                   1942: 	if(isClient) {
                   1943: 	    &Debug("rolesput");
                   1944: 	    if ($wasenc==1) {
                   1945: 		my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
                   1946: 		    =split(/:/,$userinput);
                   1947: 		&Debug("cmd = ".$cmd." exedom= ".$exedom.
                   1948: 		       "user = ".$exeuser." udom=".$udom.
                   1949: 		       "what = ".$what);
                   1950: 		my $namespace='roles';
                   1951: 		chomp($what);
                   1952: 		my $proname=propath($udom,$uname);
                   1953: 		my $now=time;
                   1954: 		my @pairs=split(/\&/,$what);
                   1955: 		my %hash;
                   1956: 		if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
                   1957: 		    {
                   1958: 			my $hfh;
                   1959: 			if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { 
                   1960: 			    print $hfh "P:$now:$exedom:$exeuser:$what\n";
                   1961: 			}
                   1962: 		    }
                   1963: 		    
                   1964: 		    foreach my $pair (@pairs) {
                   1965: 			my ($key,$value)=split(/=/,$pair);
                   1966: 			&ManagePermissions($key, $udom, $uname,
                   1967: 					   &GetAuthType( $udom, 
                   1968: 							 $uname));
                   1969: 			$hash{$key}=$value;
                   1970: 		    }
                   1971: 		    if (untie(%hash)) {
                   1972: 			print $client "ok\n";
                   1973: 		    } else {
                   1974: 			print $client "error: ".($!+0)
                   1975: 			    ." untie(GDBM) Failed ".
                   1976: 			    "while attempting rolesput\n";
                   1977: 		    }
                   1978: 		} else {
                   1979: 		    print $client "error: ".($!+0)
                   1980: 			." tie(GDBM) Failed ".
                   1981: 			"while attempting rolesput\n";
                   1982: 			    }
                   1983: 	    } else {
                   1984: 		print $client "refused\n";
                   1985: 	    }
                   1986: 	} else {
                   1987: 	    Reply($client, "refused\n", $userinput);
                   1988: 	    
                   1989: 	}
                   1990: # -------------------------------------------------------------------- rolesdel
                   1991:     } elsif ($userinput =~ /^rolesdel/) {
                   1992: 	if(isClient) {
                   1993: 	    &Debug("rolesdel");
                   1994: 	    if ($wasenc==1) {
                   1995: 		my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
                   1996: 		    =split(/:/,$userinput);
                   1997: 		&Debug("cmd = ".$cmd." exedom= ".$exedom.
                   1998: 		       "user = ".$exeuser." udom=".$udom.
                   1999: 		       "what = ".$what);
                   2000: 		my $namespace='roles';
                   2001: 		chomp($what);
                   2002: 		my $proname=propath($udom,$uname);
                   2003: 		my $now=time;
                   2004: 		my @rolekeys=split(/\&/,$what);
                   2005: 		my %hash;
                   2006: 		if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
                   2007: 		    {
                   2008: 			my $hfh;
                   2009: 			if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { 
                   2010: 			    print $hfh "D:$now:$exedom:$exeuser:$what\n";
                   2011: 			}
                   2012: 		    }
                   2013: 		    foreach my $key (@rolekeys) {
                   2014: 			delete $hash{$key};
                   2015: 		    }
                   2016: 		    if (untie(%hash)) {
                   2017: 			print $client "ok\n";
                   2018: 		    } else {
                   2019: 			print $client "error: ".($!+0)
                   2020: 			    ." untie(GDBM) Failed ".
                   2021: 			    "while attempting rolesdel\n";
                   2022: 		    }
                   2023: 		} else {
                   2024: 		    print $client "error: ".($!+0)
                   2025: 			." tie(GDBM) Failed ".
                   2026: 			"while attempting rolesdel\n";
                   2027: 		}
                   2028: 	    } else {
                   2029: 		print $client "refused\n";
                   2030: 	    }
                   2031: 	} else {
                   2032: 	    Reply($client, "refused\n", $userinput);
                   2033: 	    
                   2034: 	}
                   2035: # ------------------------------------------------------------------------- get
                   2036:     } elsif ($userinput =~ /^get/) {
                   2037: 	if(isClient) {
                   2038: 	    my ($cmd,$udom,$uname,$namespace,$what)
                   2039: 		=split(/:/,$userinput);
                   2040: 	    $namespace=~s/\//\_/g;
                   2041: 	    $namespace=~s/\W//g;
                   2042: 	    chomp($what);
                   2043: 	    my @queries=split(/\&/,$what);
                   2044: 	    my $proname=propath($udom,$uname);
                   2045: 	    my $qresult='';
                   2046: 	    my %hash;
                   2047: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
                   2048: 		for (my $i=0;$i<=$#queries;$i++) {
                   2049: 		    $qresult.="$hash{$queries[$i]}&";
                   2050: 		}
                   2051: 		if (untie(%hash)) {
                   2052: 		    $qresult=~s/\&$//;
                   2053: 		    print $client "$qresult\n";
                   2054: 		} else {
                   2055: 		    print $client "error: ".($!+0)
                   2056: 			." untie(GDBM) Failed ".
                   2057: 			"while attempting get\n";
                   2058: 		}
                   2059: 	    } else {
                   2060: 		if ($!+0 == 2) {
                   2061: 		    print $client "error:No such file or ".
                   2062: 			"GDBM reported bad block error\n";
                   2063: 		} else {
                   2064: 		    print $client "error: ".($!+0)
                   2065: 			." tie(GDBM) Failed ".
                   2066: 			"while attempting get\n";
                   2067: 		}
                   2068: 	    }
                   2069: 	} else {
                   2070: 	    Reply($client, "refused\n", $userinput);
                   2071: 	    
                   2072: 	}
                   2073: # ------------------------------------------------------------------------ eget
                   2074:     } elsif ($userinput =~ /^eget/) {
                   2075: 	if (isClient) {
                   2076: 	    my ($cmd,$udom,$uname,$namespace,$what)
                   2077: 		=split(/:/,$userinput);
                   2078: 	    $namespace=~s/\//\_/g;
                   2079: 	    $namespace=~s/\W//g;
                   2080: 	    chomp($what);
                   2081: 	    my @queries=split(/\&/,$what);
                   2082: 	    my $proname=propath($udom,$uname);
                   2083: 	    my $qresult='';
                   2084: 	    my %hash;
                   2085: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
                   2086: 		for (my $i=0;$i<=$#queries;$i++) {
                   2087: 		    $qresult.="$hash{$queries[$i]}&";
                   2088: 		}
                   2089: 		if (untie(%hash)) {
                   2090: 		    $qresult=~s/\&$//;
                   2091: 		    if ($cipher) {
                   2092: 			my $cmdlength=length($qresult);
                   2093: 			$qresult.="         ";
                   2094: 			my $encqresult='';
                   2095: 			for 
                   2096: 			    (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   2097: 				$encqresult.=
                   2098: 				    unpack("H16",
                   2099: 					   $cipher->encrypt(substr($qresult,$encidx,8)));
                   2100: 			    }
                   2101: 			print $client "enc:$cmdlength:$encqresult\n";
                   2102: 		    } else {
                   2103: 			print $client "error:no_key\n";
                   2104: 		    }
                   2105: 		} else {
                   2106: 		    print $client "error: ".($!+0)
                   2107: 			." untie(GDBM) Failed ".
                   2108: 			"while attempting eget\n";
                   2109: 		}
                   2110: 	    } else {
                   2111: 		print $client "error: ".($!+0)
                   2112: 		    ." tie(GDBM) Failed ".
                   2113: 		    "while attempting eget\n";
                   2114: 	    }
                   2115: 	} else {
                   2116: 	    Reply($client, "refused\n", $userinput);
                   2117: 	    
                   2118: 	}
                   2119: # ------------------------------------------------------------------------- del
                   2120:     } elsif ($userinput =~ /^del/) {
                   2121: 	if(isClient) {
                   2122: 	    my ($cmd,$udom,$uname,$namespace,$what)
                   2123: 		=split(/:/,$userinput);
                   2124: 	    $namespace=~s/\//\_/g;
                   2125: 	    $namespace=~s/\W//g;
                   2126: 	    chomp($what);
                   2127: 	    my $proname=propath($udom,$uname);
                   2128: 	    my $now=time;
                   2129: 	    my @keys=split(/\&/,$what);
                   2130: 	    my %hash;
                   2131: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
                   2132: 		unless ($namespace=~/^nohist\_/) {
                   2133: 		    my $hfh;
                   2134: 		    if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "D:$now:$what\n"; }
                   2135: 		}
                   2136: 		foreach my $key (@keys) {
                   2137: 		    delete($hash{$key});
                   2138: 		}
                   2139: 		if (untie(%hash)) {
                   2140: 		    print $client "ok\n";
                   2141: 		} else {
                   2142: 		    print $client "error: ".($!+0)
                   2143: 			." untie(GDBM) Failed ".
                   2144: 			"while attempting del\n";
                   2145: 		}
                   2146: 	    } else {
                   2147: 		print $client "error: ".($!+0)
                   2148: 		    ." tie(GDBM) Failed ".
                   2149: 		    "while attempting del\n";
                   2150: 	    }
                   2151: 	} else {
                   2152: 	    Reply($client, "refused\n", $userinput);
                   2153: 	    
                   2154: 	}
                   2155: # ------------------------------------------------------------------------ keys
                   2156:     } elsif ($userinput =~ /^keys/) {
                   2157: 	if(isClient) {
                   2158: 	    my ($cmd,$udom,$uname,$namespace)
                   2159: 		=split(/:/,$userinput);
                   2160: 	    $namespace=~s/\//\_/g;
                   2161: 	    $namespace=~s/\W//g;
                   2162: 	    my $proname=propath($udom,$uname);
                   2163: 	    my $qresult='';
                   2164: 	    my %hash;
                   2165: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
                   2166: 		foreach my $key (keys %hash) {
                   2167: 		    $qresult.="$key&";
                   2168: 		}
                   2169: 		if (untie(%hash)) {
                   2170: 		    $qresult=~s/\&$//;
                   2171: 		    print $client "$qresult\n";
                   2172: 		} else {
                   2173: 		    print $client "error: ".($!+0)
                   2174: 			." untie(GDBM) Failed ".
                   2175: 			"while attempting keys\n";
                   2176: 		}
                   2177: 	    } else {
                   2178: 		print $client "error: ".($!+0)
                   2179: 		    ." tie(GDBM) Failed ".
                   2180: 		    "while attempting keys\n";
                   2181: 	    }
                   2182: 	} else {
                   2183: 	    Reply($client, "refused\n", $userinput);
                   2184: 	    
                   2185: 	}
                   2186: # ----------------------------------------------------------------- dumpcurrent
                   2187:     } elsif ($userinput =~ /^currentdump/) {
                   2188: 	if (isClient) {
                   2189: 	    my ($cmd,$udom,$uname,$namespace)
                   2190: 		=split(/:/,$userinput);
                   2191: 	    $namespace=~s/\//\_/g;
                   2192: 	    $namespace=~s/\W//g;
                   2193: 	    my $qresult='';
                   2194: 	    my $proname=propath($udom,$uname);
                   2195: 	    my %hash;
                   2196: 	    if (tie(%hash,'GDBM_File',
                   2197: 		    "$proname/$namespace.db",
                   2198: 		    &GDBM_READER(),0640)) {
                   2199: 			    # Structure of %data:
                   2200: 		# $data{$symb}->{$parameter}=$value;
                   2201: 		# $data{$symb}->{'v.'.$parameter}=$version;
                   2202: 		# since $parameter will be unescaped, we do not
                   2203: 		# have to worry about silly parameter names...
                   2204: 		my %data = ();
                   2205: 		while (my ($key,$value) = each(%hash)) {
                   2206: 		    my ($v,$symb,$param) = split(/:/,$key);
                   2207: 		    next if ($v eq 'version' || $symb eq 'keys');
                   2208: 		    next if (exists($data{$symb}) && 
                   2209: 			     exists($data{$symb}->{$param}) &&
                   2210: 			     $data{$symb}->{'v.'.$param} > $v);
                   2211: 		    $data{$symb}->{$param}=$value;
                   2212: 		    $data{$symb}->{'v.'.$param}=$v;
                   2213: 		}
                   2214: 		if (untie(%hash)) {
                   2215: 		    while (my ($symb,$param_hash) = each(%data)) {
                   2216: 			while(my ($param,$value) = each (%$param_hash)){
                   2217: 			    next if ($param =~ /^v\./);
                   2218: 			    $qresult.=$symb.':'.$param.'='.$value.'&';
                   2219: 			}
                   2220: 		    }
                   2221: 		    chop($qresult);
                   2222: 		    print $client "$qresult\n";
                   2223: 		} else {
                   2224: 		    print $client "error: ".($!+0)
                   2225: 			." untie(GDBM) Failed ".
                   2226: 			"while attempting currentdump\n";
                   2227: 		}
                   2228: 	    } else {
                   2229: 		print $client "error: ".($!+0)
                   2230: 		    ." tie(GDBM) Failed ".
                   2231: 		    "while attempting currentdump\n";
                   2232: 	    }
                   2233: 	} else {
                   2234: 	    Reply($client, "refused\n", $userinput);
                   2235: 	}
                   2236: # ------------------------------------------------------------------------ dump
                   2237:     } elsif ($userinput =~ /^dump/) {
                   2238: 	if(isClient) {
                   2239: 	    my ($cmd,$udom,$uname,$namespace,$regexp)
                   2240: 		=split(/:/,$userinput);
                   2241: 	    $namespace=~s/\//\_/g;
                   2242: 	    $namespace=~s/\W//g;
                   2243: 	    if (defined($regexp)) {
                   2244: 		$regexp=&unescape($regexp);
                   2245: 	    } else {
                   2246: 		$regexp='.';
                   2247: 	    }
                   2248: 	    my $qresult='';
                   2249: 	    my $proname=propath($udom,$uname);
                   2250: 	    my %hash;
                   2251: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
                   2252: 		while (my ($key,$value) = each(%hash)) {
                   2253: 		    if ($regexp eq '.') {
                   2254: 			$qresult.=$key.'='.$value.'&';
                   2255: 		    } else {
                   2256: 			my $unescapeKey = &unescape($key);
                   2257: 			if (eval('$unescapeKey=~/$regexp/')) {
                   2258: 			    $qresult.="$key=$value&";
                   2259: 			}
                   2260: 		    }
                   2261: 		}
                   2262: 		if (untie(%hash)) {
                   2263: 		    chop($qresult);
                   2264: 		    print $client "$qresult\n";
                   2265: 		} else {
                   2266: 		    print $client "error: ".($!+0)
                   2267: 			." untie(GDBM) Failed ".
                   2268: 			"while attempting dump\n";
                   2269: 		}
                   2270: 	    } else {
                   2271: 		print $client "error: ".($!+0)
                   2272: 		    ." tie(GDBM) Failed ".
                   2273: 		    "while attempting dump\n";
                   2274: 	    }
                   2275: 	} else {
                   2276: 	    Reply($client, "refused\n", $userinput);
                   2277: 	    
                   2278: 	}
                   2279: # ----------------------------------------------------------------------- store
                   2280:     } elsif ($userinput =~ /^store/) {
                   2281: 	if(isClient) {
                   2282: 	    my ($cmd,$udom,$uname,$namespace,$rid,$what)
                   2283: 		=split(/:/,$userinput);
                   2284: 	    $namespace=~s/\//\_/g;
                   2285: 	    $namespace=~s/\W//g;
                   2286: 	    if ($namespace ne 'roles') {
                   2287: 		chomp($what);
                   2288: 		my $proname=propath($udom,$uname);
                   2289: 		my $now=time;
                   2290: 		my @pairs=split(/\&/,$what);
                   2291: 		my %hash;
                   2292: 		if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
                   2293: 		    unless ($namespace=~/^nohist\_/) {
                   2294: 			my $hfh;
                   2295: 			if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
                   2296: 			    print $hfh "P:$now:$rid:$what\n";
                   2297: 			}
                   2298: 		    }
                   2299: 		    my @previouskeys=split(/&/,$hash{"keys:$rid"});
                   2300: 		    my $key;
                   2301: 		    $hash{"version:$rid"}++;
                   2302: 		    my $version=$hash{"version:$rid"};
                   2303: 		    my $allkeys=''; 
                   2304: 		    foreach my $pair (@pairs) {
                   2305: 			my ($key,$value)=split(/=/,$pair);
                   2306: 			$allkeys.=$key.':';
                   2307: 			$hash{"$version:$rid:$key"}=$value;
                   2308: 		    }
                   2309: 		    $hash{"$version:$rid:timestamp"}=$now;
                   2310: 		    $allkeys.='timestamp';
                   2311: 		    $hash{"$version:keys:$rid"}=$allkeys;
                   2312: 		    if (untie(%hash)) {
                   2313: 			print $client "ok\n";
                   2314: 		    } else {
                   2315: 			print $client "error: ".($!+0)
                   2316: 			    ." untie(GDBM) Failed ".
                   2317: 			    "while attempting store\n";
                   2318: 				}
                   2319: 		} else {
                   2320: 		    print $client "error: ".($!+0)
                   2321: 			." tie(GDBM) Failed ".
                   2322: 			"while attempting store\n";
                   2323: 		}
                   2324: 	    } else {
                   2325: 		print $client "refused\n";
                   2326: 	    }
                   2327: 	} else {
                   2328: 	    Reply($client, "refused\n", $userinput);
                   2329: 	    
                   2330: 	}
                   2331: # --------------------------------------------------------------------- restore
                   2332:     } elsif ($userinput =~ /^restore/) {
                   2333: 	if(isClient) {
                   2334: 	    my ($cmd,$udom,$uname,$namespace,$rid)
                   2335: 		=split(/:/,$userinput);
                   2336: 	    $namespace=~s/\//\_/g;
                   2337: 	    $namespace=~s/\W//g;
                   2338: 	    chomp($rid);
                   2339: 	    my $proname=propath($udom,$uname);
                   2340: 	    my $qresult='';
                   2341: 	    my %hash;
                   2342: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
                   2343: 		my $version=$hash{"version:$rid"};
                   2344: 		$qresult.="version=$version&";
                   2345: 		my $scope;
                   2346: 		for ($scope=1;$scope<=$version;$scope++) {
                   2347: 		    my $vkeys=$hash{"$scope:keys:$rid"};
                   2348: 		    my @keys=split(/:/,$vkeys);
                   2349: 		    my $key;
                   2350: 		    $qresult.="$scope:keys=$vkeys&";
                   2351: 		    foreach $key (@keys) {
                   2352: 			$qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
                   2353: 		    }                                  
                   2354: 		}
                   2355: 		if (untie(%hash)) {
                   2356: 		    $qresult=~s/\&$//;
                   2357: 		    print $client "$qresult\n";
                   2358: 		} else {
                   2359: 		    print $client "error: ".($!+0)
                   2360: 			." untie(GDBM) Failed ".
                   2361: 			"while attempting restore\n";
                   2362: 		}
                   2363: 	    } else {
                   2364: 		print $client "error: ".($!+0)
                   2365: 		    ." tie(GDBM) Failed ".
                   2366: 		    "while attempting restore\n";
                   2367: 	    }
                   2368: 	} else  {
                   2369: 	    Reply($client, "refused\n", $userinput);
                   2370: 	    
                   2371: 	}
                   2372: # -------------------------------------------------------------------- chatsend
                   2373:     } elsif ($userinput =~ /^chatsend/) {
                   2374: 	if(isClient) {
                   2375: 	    my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
                   2376: 	    &chatadd($cdom,$cnum,$newpost);
                   2377: 	    print $client "ok\n";
                   2378: 	} else {
                   2379: 	    Reply($client, "refused\n", $userinput);
                   2380: 	    
                   2381: 	}
                   2382: # -------------------------------------------------------------------- chatretr
                   2383:     } elsif ($userinput =~ /^chatretr/) {
                   2384: 	if(isClient) {
                   2385: 	    my 
                   2386: 		($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
                   2387: 	    my $reply='';
                   2388: 	    foreach (&getchat($cdom,$cnum,$udom,$uname)) {
                   2389: 		$reply.=&escape($_).':';
                   2390: 	    }
                   2391: 	    $reply=~s/\:$//;
                   2392: 	    print $client $reply."\n";
                   2393: 	} else {
                   2394: 	    Reply($client, "refused\n", $userinput);
                   2395: 	    
                   2396: 	}
                   2397: # ------------------------------------------------------------------- querysend
                   2398:     } elsif ($userinput =~ /^querysend/) {
                   2399: 	if (isClient) {
                   2400: 	    my ($cmd,$query,
                   2401: 		$arg1,$arg2,$arg3)=split(/\:/,$userinput);
                   2402: 	    $query=~s/\n*$//g;
                   2403: 	    print $client "".
                   2404: 		sqlreply("$clientname\&$query".
                   2405: 			 "\&$arg1"."\&$arg2"."\&$arg3")."\n";
                   2406: 	} else {
                   2407: 	    Reply($client, "refused\n", $userinput);
                   2408: 	    
                   2409: 	}
                   2410: # ------------------------------------------------------------------ queryreply
                   2411:     } elsif ($userinput =~ /^queryreply/) {
                   2412: 	if(isClient) {
                   2413: 	    my ($cmd,$id,$reply)=split(/:/,$userinput); 
                   2414: 	    my $store;
                   2415: 	    my $execdir=$perlvar{'lonDaemons'};
                   2416: 	    if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   2417: 		$reply=~s/\&/\n/g;
                   2418: 		print $store $reply;
                   2419: 		close $store;
                   2420: 		my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   2421: 		print $store2 "done\n";
                   2422: 		close $store2;
                   2423: 		print $client "ok\n";
                   2424: 	    }
                   2425: 	    else {
                   2426: 		print $client "error: ".($!+0)
                   2427: 		    ." IO::File->new Failed ".
                   2428: 		    "while attempting queryreply\n";
                   2429: 	    }
                   2430: 	} else {
                   2431: 	    Reply($client, "refused\n", $userinput);
                   2432: 	    
                   2433: 	}
                   2434: # ----------------------------------------------------------------- courseidput
                   2435:     } elsif ($userinput =~ /^courseidput/) {
                   2436: 	if(isClient) {
                   2437: 	    my ($cmd,$udom,$what)=split(/:/,$userinput);
                   2438: 	    chomp($what);
                   2439: 			$udom=~s/\W//g;
                   2440: 	    my $proname=
                   2441: 		"$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
                   2442: 	    my $now=time;
                   2443: 	    my @pairs=split(/\&/,$what);
                   2444: 	    my %hash;
                   2445: 	    if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
                   2446: 		foreach my $pair (@pairs) {
                   2447: 		    my ($key,$descr,$inst_code)=split(/=/,$pair);
                   2448: 		    $hash{$key}=$descr.':'.$inst_code.':'.$now;
                   2449: 		}
                   2450: 		if (untie(%hash)) {
                   2451: 		    print $client "ok\n";
                   2452: 		} else {
                   2453: 		    print $client "error: ".($!+0)
                   2454: 			." untie(GDBM) Failed ".
                   2455: 			"while attempting courseidput\n";
                   2456: 		}
                   2457: 	    } else {
                   2458: 		print $client "error: ".($!+0)
                   2459: 		    ." tie(GDBM) Failed ".
                   2460: 		    "while attempting courseidput\n";
                   2461: 	    }
                   2462: 	} else {
                   2463: 	    Reply($client, "refused\n", $userinput);
                   2464: 	    
                   2465: 	}
                   2466: # ---------------------------------------------------------------- courseiddump
                   2467:     } elsif ($userinput =~ /^courseiddump/) {
                   2468: 	if(isClient) {
                   2469: 	    my ($cmd,$udom,$since,$description)
                   2470: 		=split(/:/,$userinput);
                   2471: 	    if (defined($description)) {
                   2472: 		$description=&unescape($description);
                   2473: 	    } else {
                   2474: 		$description='.';
                   2475: 	    }
                   2476: 	    unless (defined($since)) { $since=0; }
                   2477: 	    my $qresult='';
                   2478: 	    my $proname=
                   2479: 		"$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
                   2480: 	    my %hash;
                   2481: 	    if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
                   2482: 		while (my ($key,$value) = each(%hash)) {
                   2483: 		    my ($descr,$lasttime,$inst_code);
                   2484: 		    if ($value =~ m/^([^\:]*):([^\:]*):(\d+)$/) {
                   2485: 			($descr,$inst_code,$lasttime)=($1,$2,$3);
                   2486: 		    } else {
                   2487: 			($descr,$lasttime) = split(/\:/,$value);
                   2488: 		    }
                   2489: 		    if ($lasttime<$since) { next; }
                   2490: 		    if ($description eq '.') {
                   2491: 			$qresult.=$key.'='.$descr.':'.$inst_code.'&';
                   2492: 		    } else {
                   2493: 			my $unescapeVal = &unescape($descr);
                   2494: 			if (eval('$unescapeVal=~/\Q$description\E/i')) {
                   2495: 			    $qresult.=$key.'='.$descr.':'.$inst_code.'&';
                   2496: 			}
                   2497: 		    }
                   2498: 		}
                   2499: 		if (untie(%hash)) {
                   2500: 		    chop($qresult);
                   2501: 		    print $client "$qresult\n";
                   2502: 		} else {
                   2503: 		    print $client "error: ".($!+0)
                   2504: 			." untie(GDBM) Failed ".
                   2505: 			"while attempting courseiddump\n";
                   2506: 		}
                   2507: 	    } else {
                   2508: 		print $client "error: ".($!+0)
                   2509: 		    ." tie(GDBM) Failed ".
                   2510: 		    "while attempting courseiddump\n";
                   2511: 	    }
                   2512: 	} else {
                   2513: 	    Reply($client, "refused\n", $userinput);
                   2514: 	    
                   2515: 	}
                   2516: # ----------------------------------------------------------------------- idput
                   2517:     } elsif ($userinput =~ /^idput/) {
                   2518: 	if(isClient) {
                   2519: 	    my ($cmd,$udom,$what)=split(/:/,$userinput);
                   2520: 	    chomp($what);
                   2521: 	    $udom=~s/\W//g;
                   2522: 	    my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
                   2523: 	    my $now=time;
                   2524: 	    my @pairs=split(/\&/,$what);
                   2525: 	    my %hash;
                   2526: 	    if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
                   2527: 		{
                   2528: 		    my $hfh;
                   2529: 		    if ($hfh=IO::File->new(">>$proname.hist")) {
                   2530: 			print $hfh "P:$now:$what\n";
                   2531: 		    }
                   2532: 		}
                   2533: 		foreach my $pair (@pairs) {
                   2534: 		    my ($key,$value)=split(/=/,$pair);
                   2535: 		    $hash{$key}=$value;
                   2536: 		}
                   2537: 		if (untie(%hash)) {
                   2538: 		    print $client "ok\n";
                   2539: 		} else {
                   2540: 		    print $client "error: ".($!+0)
                   2541: 			." untie(GDBM) Failed ".
                   2542: 			"while attempting idput\n";
                   2543: 		}
                   2544: 	    } else {
                   2545: 		print $client "error: ".($!+0)
                   2546: 		    ." tie(GDBM) Failed ".
                   2547: 		    "while attempting idput\n";
                   2548: 	    }
                   2549: 	} else {
                   2550: 	    Reply($client, "refused\n", $userinput);
                   2551: 	    
                   2552: 	}
                   2553: # ----------------------------------------------------------------------- idget
                   2554:     } elsif ($userinput =~ /^idget/) {
                   2555: 	if(isClient) {
                   2556: 	    my ($cmd,$udom,$what)=split(/:/,$userinput);
                   2557: 	    chomp($what);
                   2558: 	    $udom=~s/\W//g;
                   2559: 	    my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
                   2560: 	    my @queries=split(/\&/,$what);
                   2561: 	    my $qresult='';
                   2562: 	    my %hash;
                   2563: 	    if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
                   2564: 		for (my $i=0;$i<=$#queries;$i++) {
                   2565: 		    $qresult.="$hash{$queries[$i]}&";
                   2566: 		}
                   2567: 		if (untie(%hash)) {
                   2568: 		    $qresult=~s/\&$//;
                   2569: 		    print $client "$qresult\n";
                   2570: 		} else {
                   2571: 		    print $client "error: ".($!+0)
                   2572: 			." untie(GDBM) Failed ".
                   2573: 			"while attempting idget\n";
                   2574: 		}
                   2575: 	    } else {
                   2576: 		print $client "error: ".($!+0)
                   2577: 		    ." tie(GDBM) Failed ".
                   2578: 		    "while attempting idget\n";
                   2579: 	    }
                   2580: 	} else {
                   2581: 	    Reply($client, "refused\n", $userinput);
                   2582: 	    
                   2583: 	}
                   2584: # ---------------------------------------------------------------------- tmpput
                   2585:     } elsif ($userinput =~ /^tmpput/) {
                   2586: 	if(isClient) {
                   2587: 	    my ($cmd,$what)=split(/:/,$userinput);
                   2588: 	    my $store;
                   2589: 	    $tmpsnum++;
                   2590: 	    my $id=$$.'_'.$clientip.'_'.$tmpsnum;
                   2591: 	    $id=~s/\W/\_/g;
                   2592: 	    $what=~s/\n//g;
                   2593: 	    my $execdir=$perlvar{'lonDaemons'};
                   2594: 	    if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
                   2595: 		print $store $what;
                   2596: 		close $store;
                   2597: 		print $client "$id\n";
                   2598: 	    }
                   2599: 	    else {
                   2600: 		print $client "error: ".($!+0)
                   2601: 		    ."IO::File->new Failed ".
                   2602: 		    "while attempting tmpput\n";
                   2603: 	    }
                   2604: 	} else {
                   2605: 	    Reply($client, "refused\n", $userinput);
                   2606: 	    
                   2607: 	}
                   2608: 	
                   2609: # ---------------------------------------------------------------------- tmpget
                   2610:     } elsif ($userinput =~ /^tmpget/) {
                   2611: 	if(isClient) {
                   2612: 	    my ($cmd,$id)=split(/:/,$userinput);
                   2613: 	    chomp($id);
                   2614: 	    $id=~s/\W/\_/g;
                   2615: 	    my $store;
                   2616: 	    my $execdir=$perlvar{'lonDaemons'};
                   2617: 	    if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   2618: 		my $reply=<$store>;
                   2619: 			    print $client "$reply\n";
                   2620: 		close $store;
                   2621: 	    }
                   2622: 	    else {
                   2623: 		print $client "error: ".($!+0)
                   2624: 		    ."IO::File->new Failed ".
                   2625: 		    "while attempting tmpget\n";
                   2626: 	    }
                   2627: 	} else {
                   2628: 	    Reply($client, "refused\n", $userinput);
                   2629: 	    
                   2630: 	}
                   2631: # ---------------------------------------------------------------------- tmpdel
                   2632:     } elsif ($userinput =~ /^tmpdel/) {
                   2633: 	if(isClient) {
                   2634: 	    my ($cmd,$id)=split(/:/,$userinput);
                   2635: 	    chomp($id);
                   2636: 	    $id=~s/\W/\_/g;
                   2637: 	    my $execdir=$perlvar{'lonDaemons'};
                   2638: 	    if (unlink("$execdir/tmp/$id.tmp")) {
                   2639: 		print $client "ok\n";
                   2640: 	    } else {
                   2641: 		print $client "error: ".($!+0)
                   2642: 		    ."Unlink tmp Failed ".
                   2643: 		    "while attempting tmpdel\n";
                   2644: 	    }
                   2645: 	} else {
                   2646: 	    Reply($client, "refused\n", $userinput);
                   2647: 	    
                   2648: 	}
                   2649: # ----------------------------------------- portfolio directory list (portls)
                   2650:     } elsif ($userinput =~ /^portls/) {
                   2651: 	if(isClient) {
                   2652: 	    my ($cmd,$uname,$udom)=split(/:/,$userinput);
                   2653: 	    my $udir=propath($udom,$uname).'/userfiles/portfolio';
                   2654: 	    my $dirLine='';
                   2655: 	    my $dirContents='';
                   2656: 	    if (opendir(LSDIR,$udir.'/')){
                   2657: 		while ($dirLine = readdir(LSDIR)){
                   2658: 		    $dirContents = $dirContents.$dirLine.'<br />';
                   2659: 		}
                   2660: 	    } else {
                   2661: 		$dirContents = "No directory found\n";
                   2662: 	    }
                   2663: 	    print $client $dirContents."\n";
                   2664: 	} else {
                   2665: 	    Reply($client, "refused\n", $userinput);
                   2666: 	}
                   2667: # -------------------------------------------------------------------------- ls
                   2668:     } elsif ($userinput =~ /^ls/) {
                   2669: 	if(isClient) {
                   2670: 	    my $obs;
                   2671: 	    my $rights;
                   2672: 	    my ($cmd,$ulsdir)=split(/:/,$userinput);
                   2673: 	    my $ulsout='';
                   2674: 	    my $ulsfn;
                   2675: 	    if (-e $ulsdir) {
                   2676: 		if(-d $ulsdir) {
                   2677: 		    if (opendir(LSDIR,$ulsdir)) {
                   2678: 			while ($ulsfn=readdir(LSDIR)) {
                   2679: 			    undef $obs, $rights; 
                   2680: 			    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   2681: 			    #We do some obsolete checking here
                   2682: 			    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   2683: 				open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   2684: 				my @obsolete=<FILE>;
                   2685: 				foreach my $obsolete (@obsolete) {
                   2686: 				    if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; } 
                   2687: 				    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   2688: 				}
                   2689: 			    }
                   2690: 			    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   2691: 			    if($obs eq '1') { $ulsout.="&1"; }
                   2692: 			    else { $ulsout.="&0"; }
                   2693: 			    if($rights eq '1') { $ulsout.="&1:"; }
                   2694: 			    else { $ulsout.="&0:"; }
                   2695: 			}
                   2696: 			closedir(LSDIR);
                   2697: 		    }
                   2698: 		} else {
                   2699: 		    my @ulsstats=stat($ulsdir);
                   2700: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   2701: 		}
                   2702: 	    } else {
                   2703: 		$ulsout='no_such_dir';
                   2704: 	    }
                   2705: 	    if ($ulsout eq '') { $ulsout='empty'; }
                   2706: 	    print $client "$ulsout\n";
                   2707: 	} else {
                   2708: 	    Reply($client, "refused\n", $userinput);
                   2709: 	    
                   2710: 	}
                   2711: # ----------------------------------------------------------------- setannounce
                   2712:     } elsif ($userinput =~ /^setannounce/) {
                   2713: 	if (isClient) {
                   2714: 	    my ($cmd,$announcement)=split(/:/,$userinput);
                   2715: 	    chomp($announcement);
                   2716: 	    $announcement=&unescape($announcement);
                   2717: 	    if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   2718: 					'/announcement.txt')) {
                   2719: 		print $store $announcement;
                   2720: 		close $store;
                   2721: 		print $client "ok\n";
                   2722: 	    } else {
                   2723: 		print $client "error: ".($!+0)."\n";
                   2724: 	    }
                   2725: 	} else {
                   2726: 	    Reply($client, "refused\n", $userinput);
                   2727: 	    
                   2728: 	}
                   2729: # ------------------------------------------------------------------ Hanging up
                   2730:     } elsif (($userinput =~ /^exit/) ||
                   2731: 	     ($userinput =~ /^init/)) { # no restrictions.
                   2732: 	&logthis(
                   2733: 		 "Client $clientip ($clientname) hanging up: $userinput");
                   2734: 	print $client "bye\n";
                   2735: 	$client->shutdown(2);        # shutdown the socket forcibly.
                   2736: 	$client->close();
                   2737: 	return 0;
                   2738: 	
                   2739: # ---------------------------------- set current host/domain
                   2740:     } elsif ($userinput =~ /^sethost:/) {
                   2741: 	if (isClient) {
                   2742: 	    print $client &sethost($userinput)."\n";
                   2743: 	} else {
                   2744: 	    print $client "refused\n";
                   2745: 	}
                   2746: #---------------------------------- request file (?) version.
                   2747:     } elsif ($userinput =~/^version:/) {
                   2748: 	if (isClient) {
                   2749: 	    print $client &version($userinput)."\n";
                   2750: 	} else {
                   2751: 	    print $client "refused\n";
                   2752: 	}
                   2753: #------------------------------- is auto-enrollment enabled?
                   2754:     } elsif ($userinput =~/^autorun:/) {
                   2755: 	if (isClient) {
                   2756: 	    my ($cmd,$cdom) = split(/:/,$userinput);
                   2757: 	    my $outcome = &localenroll::run($cdom);
                   2758: 	    print $client "$outcome\n";
                   2759: 	} else {
                   2760: 	    print $client "0\n";
                   2761: 	}
                   2762: #------------------------------- get official sections (for auto-enrollment).
                   2763:     } elsif ($userinput =~/^autogetsections:/) {
                   2764: 	if (isClient) {
                   2765: 	    my ($cmd,$coursecode,$cdom)=split(/:/,$userinput);
                   2766: 	    my @secs = &localenroll::get_sections($coursecode,$cdom);
                   2767: 	    my $seclist = &escape(join(':',@secs));
                   2768: 	    print $client "$seclist\n";
                   2769: 	} else {
                   2770: 	    print $client "refused\n";
                   2771: 	}
                   2772: #----------------------- validate owner of new course section (for auto-enrollment).
                   2773:     } elsif ($userinput =~/^autonewcourse:/) {
                   2774: 	if (isClient) {
                   2775: 	    my ($cmd,$inst_course_id,$owner,$cdom)=split(/:/,$userinput);
                   2776: 	    my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
                   2777: 	    print $client "$outcome\n";
                   2778: 	} else {
                   2779: 	    print $client "refused\n";
                   2780: 	}
                   2781: #-------------- validate course section in schedule of classes (for auto-enrollment).
                   2782:     } elsif ($userinput =~/^autovalidatecourse:/) {
                   2783: 	if (isClient) {
                   2784: 	    my ($cmd,$inst_course_id,$cdom)=split(/:/,$userinput);
                   2785: 	    my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
                   2786: 	    print $client "$outcome\n";
                   2787: 	} else {
                   2788: 	    print $client "refused\n";
                   2789: 	}
                   2790: #--------------------------- create password for new user (for auto-enrollment).
                   2791:     } elsif ($userinput =~/^autocreatepassword:/) {
                   2792: 	if (isClient) {
                   2793: 	    my ($cmd,$authparam,$cdom)=split(/:/,$userinput);
                   2794: 	    my ($create_passwd,$authchk);
                   2795: 	    ($authparam,$create_passwd,$authchk) = &localenroll::create_password($authparam,$cdom);
                   2796: 	    print $client &escape($authparam.':'.$create_passwd.':'.$authchk)."\n";
                   2797: 	} else {
                   2798: 	    print $client "refused\n";
                   2799: 	}
                   2800: #---------------------------  read and remove temporary files (for auto-enrollment).
                   2801:     } elsif ($userinput =~/^autoretrieve:/) {
                   2802: 	if (isClient) {
                   2803: 	    my ($cmd,$filename) = split(/:/,$userinput);
                   2804: 	    my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
                   2805: 	    if ( (-e $source) && ($filename ne '') ) {
                   2806: 		my $reply = '';
                   2807: 		if (open(my $fh,$source)) {
                   2808: 		    while (<$fh>) {
                   2809: 			chomp($_);
                   2810: 			$_ =~ s/^\s+//g;
                   2811: 			$_ =~ s/\s+$//g;
                   2812: 			$reply .= $_;
                   2813: 		    }
                   2814: 		    close($fh);
                   2815: 		    print $client &escape($reply)."\n";
                   2816: #                                unlink($source);
                   2817: 		} else {
                   2818: 		    print $client "error\n";
                   2819: 		}
                   2820: 	    } else {
                   2821: 		print $client "error\n";
                   2822: 	    }
                   2823: 	} else {
                   2824: 	    print $client "refused\n";
                   2825: 	}
                   2826: #---------------------  read and retrieve institutional code format (for support form).
                   2827:     } elsif ($userinput =~/^autoinstcodeformat:/) {
                   2828: 	if (isClient) {
                   2829: 	    my $reply;
                   2830: 	    my($cmd,$cdom,$course) = split(/:/,$userinput);
                   2831: 	    my @pairs = split/\&/,$course;
                   2832: 	    my %instcodes = ();
                   2833: 	    my %codes = ();
                   2834: 	    my @codetitles = ();
                   2835: 	    my %cat_titles = ();
                   2836: 	    my %cat_order = ();
                   2837: 	    foreach (@pairs) {
                   2838: 		my ($key,$value) = split/=/,$_;
                   2839: 		$instcodes{&unescape($key)} = &unescape($value);
                   2840: 	    }
                   2841: 	    my $formatreply = &localenroll::instcode_format($cdom,\%instcodes,\%codes,\@codetitles,\%cat_titles,\%cat_order);
                   2842: 	    if ($formatreply eq 'ok') {
                   2843: 		my $codes_str = &hash2str(%codes);
                   2844: 		my $codetitles_str = &array2str(@codetitles);
                   2845: 		my $cat_titles_str = &hash2str(%cat_titles);
                   2846: 		my $cat_order_str = &hash2str(%cat_order);
                   2847: 		print $client $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'.$cat_order_str."\n";
                   2848: 	    }
                   2849: 	} else {
                   2850: 	    print $client "refused\n";
                   2851: 	}
                   2852: # ------------------------------------------------------------- unknown command
                   2853: 	
                   2854:     } else {
                   2855: 	# unknown command
                   2856: 	print $client "unknown_cmd\n";
                   2857:     }
                   2858: # -------------------------------------------------------------------- complete
                   2859:     Debug("process_request - returning 1");
                   2860:     return 1;
                   2861: }
1.207     foxr     2862: #
                   2863: #   Decipher encoded traffic
                   2864: #  Parameters:
                   2865: #     input      - Encoded data.
                   2866: #  Returns:
                   2867: #     Decoded data or undef if encryption key was not yet negotiated.
                   2868: #  Implicit input:
                   2869: #     cipher  - This global holds the negotiated encryption key.
                   2870: #
1.211     albertel 2871: sub decipher {
1.207     foxr     2872:     my ($input)  = @_;
                   2873:     my $output = '';
1.212     foxr     2874:     
                   2875:     
1.207     foxr     2876:     if($cipher) {
                   2877: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   2878: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   2879: 	    $output .= 
                   2880: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   2881: 	}
                   2882: 	return substr($output, 0, $enclength);
                   2883:     } else {
                   2884: 	return undef;
                   2885:     }
                   2886: }
                   2887: 
                   2888: #
                   2889: #   Register a command processor.  This function is invoked to register a sub
                   2890: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   2891: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   2892: #   as well:
                   2893: #    - Is the keyword recognized.
                   2894: #    - Is the proper client type attempting the request.
                   2895: #    - Is the request encrypted if it has to be.
                   2896: #   Parameters:
                   2897: #    $request_name         - Name of the request being registered.
                   2898: #                           This is the command request that will match
                   2899: #                           against the hash keywords to lookup the information
                   2900: #                           associated with the dispatch information.
                   2901: #    $procedure           - Reference to a sub to call to process the request.
                   2902: #                           All subs get called as follows:
                   2903: #                             Procedure($cmd, $tail, $replyfd, $key)
                   2904: #                             $cmd    - the actual keyword that invoked us.
                   2905: #                             $tail   - the tail of the request that invoked us.
                   2906: #                             $replyfd- File descriptor connected to the client
                   2907: #    $must_encode          - True if the request must be encoded to be good.
                   2908: #    $client_ok            - True if it's ok for a client to request this.
                   2909: #    $manager_ok           - True if it's ok for a manager to request this.
                   2910: # Side effects:
                   2911: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   2912: #      - On failure, the program will die as it's a bad internal bug to try to 
                   2913: #        register a duplicate command handler.
                   2914: #
1.211     albertel 2915: sub register_handler {
1.212     foxr     2916:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     2917: 
                   2918:     #  Don't allow duplication#
                   2919:    
                   2920:     if (defined $Dispatcher{$request_name}) {
                   2921: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   2922:     }
                   2923:     #   Build the client type mask:
                   2924:     
                   2925:     my $client_type_mask = 0;
                   2926:     if($client_ok) {
                   2927: 	$client_type_mask  |= $CLIENT_OK;
                   2928:     }
                   2929:     if($manager_ok) {
                   2930: 	$client_type_mask  |= $MANAGER_OK;
                   2931:     }
                   2932:    
                   2933:     #  Enter the hash:
                   2934:       
                   2935:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   2936:    
                   2937:     $Dispatcher{$request_name} = \@entry;
                   2938:    
                   2939:    
                   2940: }
                   2941: 
                   2942: 
                   2943: #------------------------------------------------------------------
                   2944: 
                   2945: 
                   2946: 
                   2947: 
1.141     foxr     2948: #
1.96      foxr     2949: #  Convert an error return code from lcpasswd to a string value.
                   2950: #
                   2951: sub lcpasswdstrerror {
                   2952:     my $ErrorCode = shift;
1.97      foxr     2953:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     2954: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   2955:     } else {
1.98      foxr     2956: 	return $passwderrors[$ErrorCode];
1.96      foxr     2957:     }
                   2958: }
                   2959: 
1.97      foxr     2960: #
                   2961: # Convert an error return code from lcuseradd to a string value:
                   2962: #
                   2963: sub lcuseraddstrerror {
                   2964:     my $ErrorCode = shift;
                   2965:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
                   2966: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
                   2967:     } else {
1.98      foxr     2968: 	return $adderrors[$ErrorCode];
1.97      foxr     2969:     }
                   2970: }
                   2971: 
1.23      harris41 2972: # grabs exception and records it to log before exiting
                   2973: sub catchexception {
1.27      albertel 2974:     my ($error)=@_;
1.25      www      2975:     $SIG{'QUIT'}='DEFAULT';
                   2976:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 2977:     &status("Catching exception");
1.190     albertel 2978:     &logthis("<font color='red'>CRITICAL: "
1.134     albertel 2979:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27      albertel 2980:      ."a crash with this error msg->[$error]</font>");
1.57      www      2981:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 2982:     if ($client) { print $client "error: $error\n"; }
1.59      www      2983:     $server->close();
1.27      albertel 2984:     die($error);
1.23      harris41 2985: }
                   2986: 
1.63      www      2987: sub timeout {
1.165     albertel 2988:     &status("Handling Timeout");
1.190     albertel 2989:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      2990:     &catchexception('Timeout');
                   2991: }
1.22      harris41 2992: # -------------------------------- Set signal handlers to record abnormal exits
                   2993: 
                   2994: $SIG{'QUIT'}=\&catchexception;
                   2995: $SIG{__DIE__}=\&catchexception;
                   2996: 
1.81      matthew  2997: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 2998: &status("Read loncapa.conf and loncapa_apache.conf");
                   2999: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     3000: %perlvar=%{$perlvarref};
1.80      harris41 3001: undef $perlvarref;
1.19      www      3002: 
1.35      harris41 3003: # ----------------------------- Make sure this process is running from user=www
                   3004: my $wwwid=getpwnam('www');
                   3005: if ($wwwid!=$<) {
1.134     albertel 3006:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   3007:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 3008:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 3009:  mailto $emailto -s '$subj' > /dev/null");
                   3010:    exit 1;
                   3011: }
                   3012: 
1.19      www      3013: # --------------------------------------------- Check if other instance running
                   3014: 
                   3015: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   3016: 
                   3017: if (-e $pidfile) {
                   3018:    my $lfh=IO::File->new("$pidfile");
                   3019:    my $pide=<$lfh>;
                   3020:    chomp($pide);
1.29      harris41 3021:    if (kill 0 => $pide) { die "already running"; }
1.19      www      3022: }
1.1       albertel 3023: 
                   3024: # ------------------------------------------------------------- Read hosts file
                   3025: 
                   3026: 
                   3027: 
                   3028: # establish SERVER socket, bind and listen.
                   3029: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   3030:                                 Type      => SOCK_STREAM,
                   3031:                                 Proto     => 'tcp',
                   3032:                                 Reuse     => 1,
                   3033:                                 Listen    => 10 )
1.29      harris41 3034:   or die "making socket: $@\n";
1.1       albertel 3035: 
                   3036: # --------------------------------------------------------- Do global variables
                   3037: 
                   3038: # global variables
                   3039: 
1.134     albertel 3040: my %children               = ();       # keys are current child process IDs
1.1       albertel 3041: 
                   3042: sub REAPER {                        # takes care of dead children
                   3043:     $SIG{CHLD} = \&REAPER;
1.165     albertel 3044:     &status("Handling child death");
1.178     foxr     3045:     my $pid;
                   3046:     do {
                   3047: 	$pid = waitpid(-1,&WNOHANG());
                   3048: 	if (defined($children{$pid})) {
                   3049: 	    &logthis("Child $pid died");
                   3050: 	    delete($children{$pid});
1.183     albertel 3051: 	} elsif ($pid > 0) {
1.178     foxr     3052: 	    &logthis("Unknown Child $pid died");
                   3053: 	}
                   3054:     } while ( $pid > 0 );
                   3055:     foreach my $child (keys(%children)) {
                   3056: 	$pid = waitpid($child,&WNOHANG());
                   3057: 	if ($pid > 0) {
                   3058: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   3059: 	    delete($children{$pid});
                   3060: 	}
1.176     albertel 3061:     }
1.165     albertel 3062:     &status("Finished Handling child death");
1.1       albertel 3063: }
                   3064: 
                   3065: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 3066:     &status("Killing children (INT)");
1.1       albertel 3067:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   3068:     kill 'INT' => keys %children;
1.59      www      3069:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 3070:     my $execdir=$perlvar{'lonDaemons'};
                   3071:     unlink("$execdir/logs/lond.pid");
1.190     albertel 3072:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 3073:     &status("Done killing children");
1.1       albertel 3074:     exit;                           # clean up with dignity
                   3075: }
                   3076: 
                   3077: sub HUPSMAN {                      # signal handler for SIGHUP
                   3078:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 3079:     &status("Killing children for restart (HUP)");
1.1       albertel 3080:     kill 'INT' => keys %children;
1.59      www      3081:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 3082:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 3083:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 3084:     unlink("$execdir/logs/lond.pid");
1.165     albertel 3085:     &status("Restarting self (HUP)");
1.1       albertel 3086:     exec("$execdir/lond");         # here we go again
                   3087: }
                   3088: 
1.144     foxr     3089: #
1.148     foxr     3090: #    Kill off hashes that describe the host table prior to re-reading it.
                   3091: #    Hashes affected are:
1.200     matthew  3092: #       %hostid, %hostdom %hostip %hostdns.
1.148     foxr     3093: #
                   3094: sub KillHostHashes {
                   3095:     foreach my $key (keys %hostid) {
                   3096: 	delete $hostid{$key};
                   3097:     }
                   3098:     foreach my $key (keys %hostdom) {
                   3099: 	delete $hostdom{$key};
                   3100:     }
                   3101:     foreach my $key (keys %hostip) {
                   3102: 	delete $hostip{$key};
                   3103:     }
1.200     matthew  3104:     foreach my $key (keys %hostdns) {
                   3105: 	delete $hostdns{$key};
                   3106:     }
1.148     foxr     3107: }
                   3108: #
                   3109: #   Read in the host table from file and distribute it into the various hashes:
                   3110: #
                   3111: #    - %hostid  -  Indexed by IP, the loncapa hostname.
                   3112: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
                   3113: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
                   3114: sub ReadHostTable {
                   3115: 
                   3116:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200     matthew  3117:     my $myloncapaname = $perlvar{'lonHostID'};
                   3118:     Debug("My loncapa name is : $myloncapaname");
1.148     foxr     3119:     while (my $configline=<CONFIG>) {
1.178     foxr     3120: 	if (!($configline =~ /^\s*\#/)) {
                   3121: 	    my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                   3122: 	    chomp($ip); $ip=~s/\D+$//;
1.200     matthew  3123: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
                   3124: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
                   3125: 	    $hostip{$id}=$ip;	      # IP address of host.
                   3126: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
                   3127: 
                   3128: 	    if ($id eq $perlvar{'lonHostID'}) { 
                   3129: 		Debug("Found me in the host table: $name");
                   3130: 		$thisserver=$name; 
                   3131: 	    }
1.178     foxr     3132: 	}
1.148     foxr     3133:     }
                   3134:     close(CONFIG);
                   3135: }
                   3136: #
                   3137: #  Reload the Apache daemon's state.
1.150     foxr     3138: #  This is done by invoking /home/httpd/perl/apachereload
                   3139: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     3140: #
                   3141: sub ReloadApache {
1.150     foxr     3142:     my $execdir = $perlvar{'lonDaemons'};
                   3143:     my $script  = $execdir."/apachereload";
                   3144:     system($script);
1.148     foxr     3145: }
                   3146: 
                   3147: #
1.144     foxr     3148: #   Called in response to a USR2 signal.
                   3149: #   - Reread hosts.tab
                   3150: #   - All children connected to hosts that were removed from hosts.tab
                   3151: #     are killed via SIGINT
                   3152: #   - All children connected to previously existing hosts are sent SIGUSR1
                   3153: #   - Our internal hosts hash is updated to reflect the new contents of
                   3154: #     hosts.tab causing connections from hosts added to hosts.tab to
                   3155: #     now be honored.
                   3156: #
                   3157: sub UpdateHosts {
1.165     albertel 3158:     &status("Reload hosts.tab");
1.147     foxr     3159:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     3160:     #
                   3161:     #  The %children hash has the set of IP's we currently have children
                   3162:     #  on.  These need to be matched against records in the hosts.tab
                   3163:     #  Any ip's no longer in the table get killed off they correspond to
                   3164:     #  either dropped or changed hosts.  Note that the re-read of the table
                   3165:     #  will take care of new and changed hosts as connections come into being.
                   3166: 
                   3167: 
                   3168:     KillHostHashes;
                   3169:     ReadHostTable;
                   3170: 
                   3171:     foreach my $child (keys %children) {
                   3172: 	my $childip = $children{$child};
                   3173: 	if(!$hostid{$childip}) {
1.149     foxr     3174: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   3175: 		    ." $child for ip $childip </font>");
1.148     foxr     3176: 	    kill('INT', $child);
1.149     foxr     3177: 	} else {
                   3178: 	    logthis('<font color="green"> keeping child for ip '
                   3179: 		    ." $childip (pid=$child) </font>");
1.148     foxr     3180: 	}
                   3181:     }
                   3182:     ReloadApache;
1.165     albertel 3183:     &status("Finished reloading hosts.tab");
1.144     foxr     3184: }
                   3185: 
1.148     foxr     3186: 
1.57      www      3187: sub checkchildren {
1.165     albertel 3188:     &status("Checking on the children (sending signals)");
1.57      www      3189:     &initnewstatus();
                   3190:     &logstatus();
                   3191:     &logthis('Going to check on the children');
1.134     albertel 3192:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 3193:     foreach (sort keys %children) {
1.57      www      3194: 	sleep 1;
                   3195:         unless (kill 'USR1' => $_) {
                   3196: 	    &logthis ('Child '.$_.' is dead');
                   3197:             &logstatus($$.' is dead');
                   3198:         } 
1.61      harris41 3199:     }
1.63      www      3200:     sleep 5;
1.212     foxr     3201:     $SIG{ALRM} = sub { Debug("timeout"); 
                   3202: 		       die "timeout";  };
1.113     albertel 3203:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 3204:     &status("Checking on the children (waiting for reports)");
1.63      www      3205:     foreach (sort keys %children) {
                   3206:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 3207:           eval {
                   3208:             alarm(300);
1.63      www      3209: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 3210: 	    kill 9 => $_;
1.131     albertel 3211: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   3212: 	    #$subj="LON: $currenthostid killed lond process $_";
                   3213: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   3214: 	    #$execdir=$perlvar{'lonDaemons'};
                   3215: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.113     albertel 3216: 	    alarm(0);
                   3217: 	  }
1.63      www      3218:         }
                   3219:     }
1.113     albertel 3220:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 3221:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 3222:     &status("Finished checking children");
1.57      www      3223: }
                   3224: 
1.1       albertel 3225: # --------------------------------------------------------------------- Logging
                   3226: 
                   3227: sub logthis {
                   3228:     my $message=shift;
                   3229:     my $execdir=$perlvar{'lonDaemons'};
                   3230:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   3231:     my $now=time;
                   3232:     my $local=localtime($now);
1.58      www      3233:     $lastlog=$local.': '.$message;
1.1       albertel 3234:     print $fh "$local ($$): $message\n";
                   3235: }
                   3236: 
1.77      foxr     3237: # ------------------------- Conditional log if $DEBUG true.
                   3238: sub Debug {
                   3239:     my $message = shift;
                   3240:     if($DEBUG) {
                   3241: 	&logthis($message);
                   3242:     }
                   3243: }
1.161     foxr     3244: 
                   3245: #
                   3246: #   Sub to do replies to client.. this gives a hook for some
                   3247: #   debug tracing too:
                   3248: #  Parameters:
                   3249: #     fd      - File open on client.
                   3250: #     reply   - Text to send to client.
                   3251: #     request - Original request from client.
                   3252: #
                   3253: sub Reply {
1.192     foxr     3254:     my ($fd, $reply, $request) = @_;
1.161     foxr     3255:     print $fd $reply;
                   3256:     Debug("Request was $request  Reply was $reply");
                   3257: 
1.212     foxr     3258:     $Transactions++;
                   3259: 
                   3260: 
                   3261: }
                   3262: 
                   3263: 
                   3264: #
                   3265: #    Sub to report a failure.
                   3266: #    This function:
                   3267: #     -   Increments the failure statistic counters.
                   3268: #     -   Invokes Reply to send the error message to the client.
                   3269: # Parameters:
                   3270: #    fd       - File descriptor open on the client
                   3271: #    reply    - Reply text to emit.
                   3272: #    request  - The original request message (used by Reply
                   3273: #               to debug if that's enabled.
                   3274: # Implicit outputs:
                   3275: #    $Failures- The number of failures is incremented.
                   3276: #    Reply (invoked here) sends a message to the 
                   3277: #    client:
                   3278: #
                   3279: sub Failure {
                   3280:     my $fd      = shift;
                   3281:     my $reply   = shift;
                   3282:     my $request = shift;
                   3283:    
                   3284:     $Failures++;
                   3285:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     3286: }
1.57      www      3287: # ------------------------------------------------------------------ Log status
                   3288: 
                   3289: sub logstatus {
1.178     foxr     3290:     &status("Doing logging");
                   3291:     my $docdir=$perlvar{'lonDocRoot'};
                   3292:     {
                   3293:     my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
1.200     matthew  3294:     print $fh $$."\t".$clientname."\t".$currenthostid."\t"
                   3295: 	.$status."\t".$lastlog."\t $keymode\n";
1.178     foxr     3296:     $fh->close();
                   3297:     }
                   3298:     &status("Finished londstatus.txt");
                   3299:     {
                   3300: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  3301:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     3302:         $fh->close();
                   3303:     }
                   3304:     &status("Finished logging");
1.57      www      3305: }
                   3306: 
                   3307: sub initnewstatus {
                   3308:     my $docdir=$perlvar{'lonDocRoot'};
                   3309:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
                   3310:     my $now=time;
                   3311:     my $local=localtime($now);
                   3312:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      3313:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 3314:     while (my $filename=readdir(DIR)) {
1.64      www      3315:         unlink("$docdir/lon-status/londchld/$filename");
                   3316:     }
                   3317:     closedir(DIR);
1.57      www      3318: }
                   3319: 
                   3320: # -------------------------------------------------------------- Status setting
                   3321: 
                   3322: sub status {
                   3323:     my $what=shift;
                   3324:     my $now=time;
                   3325:     my $local=localtime($now);
1.178     foxr     3326:     $status=$local.': '.$what;
                   3327:     $0='lond: '.$what.' '.$local;
1.57      www      3328: }
1.11      www      3329: 
                   3330: # -------------------------------------------------------- Escape Special Chars
                   3331: 
                   3332: sub escape {
                   3333:     my $str=shift;
                   3334:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   3335:     return $str;
                   3336: }
                   3337: 
                   3338: # ----------------------------------------------------- Un-Escape Special Chars
                   3339: 
                   3340: sub unescape {
                   3341:     my $str=shift;
                   3342:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   3343:     return $str;
                   3344: }
                   3345: 
1.1       albertel 3346: # ----------------------------------------------------------- Send USR1 to lonc
                   3347: 
                   3348: sub reconlonc {
                   3349:     my $peerfile=shift;
                   3350:     &logthis("Trying to reconnect for $peerfile");
                   3351:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                   3352:     if (my $fh=IO::File->new("$loncfile")) {
                   3353: 	my $loncpid=<$fh>;
                   3354:         chomp($loncpid);
                   3355:         if (kill 0 => $loncpid) {
                   3356: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                   3357:             kill USR1 => $loncpid;
                   3358:         } else {
1.9       www      3359: 	    &logthis(
1.190     albertel 3360:               "<font color='red'>CRITICAL: "
1.9       www      3361:              ."lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel 3362:         }
                   3363:     } else {
1.190     albertel 3364:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1       albertel 3365:     }
                   3366: }
                   3367: 
                   3368: # -------------------------------------------------- Non-critical communication
1.11      www      3369: 
1.1       albertel 3370: sub subreply {
                   3371:     my ($cmd,$server)=@_;
                   3372:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                   3373:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   3374:                                       Type    => SOCK_STREAM,
                   3375:                                       Timeout => 10)
                   3376:        or return "con_lost";
                   3377:     print $sclient "$cmd\n";
                   3378:     my $answer=<$sclient>;
                   3379:     chomp($answer);
                   3380:     if (!$answer) { $answer="con_lost"; }
                   3381:     return $answer;
                   3382: }
                   3383: 
                   3384: sub reply {
                   3385:   my ($cmd,$server)=@_;
                   3386:   my $answer;
1.115     albertel 3387:   if ($server ne $currenthostid) { 
1.1       albertel 3388:     $answer=subreply($cmd,$server);
                   3389:     if ($answer eq 'con_lost') {
                   3390: 	$answer=subreply("ping",$server);
                   3391:         if ($answer ne $server) {
1.115     albertel 3392: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1       albertel 3393:            &reconlonc("$perlvar{'lonSockDir'}/$server");
                   3394:         }
                   3395:         $answer=subreply($cmd,$server);
                   3396:     }
                   3397:   } else {
                   3398:     $answer='self_reply';
                   3399:   } 
                   3400:   return $answer;
                   3401: }
                   3402: 
1.13      www      3403: # -------------------------------------------------------------- Talk to lonsql
                   3404: 
1.12      harris41 3405: sub sqlreply {
                   3406:     my ($cmd)=@_;
                   3407:     my $answer=subsqlreply($cmd);
                   3408:     if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
                   3409:     return $answer;
                   3410: }
                   3411: 
                   3412: sub subsqlreply {
                   3413:     my ($cmd)=@_;
                   3414:     my $unixsock="mysqlsock";
                   3415:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   3416:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   3417:                                       Type    => SOCK_STREAM,
                   3418:                                       Timeout => 10)
                   3419:        or return "con_lost";
                   3420:     print $sclient "$cmd\n";
                   3421:     my $answer=<$sclient>;
                   3422:     chomp($answer);
                   3423:     if (!$answer) { $answer="con_lost"; }
                   3424:     return $answer;
                   3425: }
                   3426: 
1.1       albertel 3427: # -------------------------------------------- Return path to profile directory
1.11      www      3428: 
1.1       albertel 3429: sub propath {
                   3430:     my ($udom,$uname)=@_;
                   3431:     $udom=~s/\W//g;
                   3432:     $uname=~s/\W//g;
1.16      www      3433:     my $subdir=$uname.'__';
1.1       albertel 3434:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3435:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   3436:     return $proname;
                   3437: } 
                   3438: 
                   3439: # --------------------------------------- Is this the home server of an author?
1.11      www      3440: 
1.1       albertel 3441: sub ishome {
                   3442:     my $author=shift;
                   3443:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3444:     my ($udom,$uname)=split(/\//,$author);
                   3445:     my $proname=propath($udom,$uname);
                   3446:     if (-e $proname) {
                   3447: 	return 'owner';
                   3448:     } else {
                   3449:         return 'not_owner';
                   3450:     }
                   3451: }
                   3452: 
                   3453: # ======================================================= Continue main program
                   3454: # ---------------------------------------------------- Fork once and dissociate
                   3455: 
1.134     albertel 3456: my $fpid=fork;
1.1       albertel 3457: exit if $fpid;
1.29      harris41 3458: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 3459: 
1.29      harris41 3460: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 3461: 
                   3462: # ------------------------------------------------------- Write our PID on disk
                   3463: 
1.134     albertel 3464: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 3465: open (PIDSAVE,">$execdir/logs/lond.pid");
                   3466: print PIDSAVE "$$\n";
                   3467: close(PIDSAVE);
1.190     albertel 3468: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      3469: &status('Starting');
1.1       albertel 3470: 
1.106     foxr     3471: 
1.1       albertel 3472: 
                   3473: # ----------------------------------------------------- Install signal handlers
                   3474: 
1.57      www      3475: 
1.1       albertel 3476: $SIG{CHLD} = \&REAPER;
                   3477: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   3478: $SIG{HUP}  = \&HUPSMAN;
1.57      www      3479: $SIG{USR1} = \&checkchildren;
1.144     foxr     3480: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     3481: 
1.148     foxr     3482: #  Read the host hashes:
                   3483: 
                   3484: ReadHostTable;
1.106     foxr     3485: 
                   3486: # --------------------------------------------------------------
                   3487: #   Accept connections.  When a connection comes in, it is validated
                   3488: #   and if good, a child process is created to process transactions
                   3489: #   along the connection.
                   3490: 
1.1       albertel 3491: while (1) {
1.165     albertel 3492:     &status('Starting accept');
1.106     foxr     3493:     $client = $server->accept() or next;
1.165     albertel 3494:     &status('Accepted '.$client.' off to spawn');
1.106     foxr     3495:     make_new_child($client);
1.165     albertel 3496:     &status('Finished spawning');
1.1       albertel 3497: }
                   3498: 
1.212     foxr     3499: sub make_new_child {
                   3500:     my $pid;
                   3501: #    my $cipher;     # Now global
                   3502:     my $sigset;
1.178     foxr     3503: 
1.212     foxr     3504:     $client = shift;
                   3505:     &status('Starting new child '.$client);
                   3506:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   3507: 	     ")</font>");    
                   3508:     # block signal for fork
                   3509:     $sigset = POSIX::SigSet->new(SIGINT);
                   3510:     sigprocmask(SIG_BLOCK, $sigset)
                   3511:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     3512: 
1.212     foxr     3513:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     3514: 
1.212     foxr     3515:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   3516: 	                               # connection liveness.
1.178     foxr     3517: 
1.212     foxr     3518:     #
                   3519:     #  Figure out who we're talking to so we can record the peer in 
                   3520:     #  the pid hash.
                   3521:     #
                   3522:     my $caller = getpeername($client);
                   3523:     my ($port,$iaddr);
                   3524:     if (defined($caller) && length($caller) > 0) {
                   3525: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   3526:     } else {
                   3527: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   3528:     }
                   3529:     if (defined($iaddr)) {
                   3530: 	$clientip  = inet_ntoa($iaddr);
                   3531: 	Debug("Connected with $clientip");
                   3532: 	$clientdns = gethostbyaddr($iaddr, AF_INET);
                   3533: 	Debug("Connected with $clientdns by name");
                   3534:     } else {
                   3535: 	&logthis("Unable to determine clientip");
                   3536: 	$clientip='Unavailable';
                   3537:     }
                   3538:     
                   3539:     if ($pid) {
                   3540:         # Parent records the child's birth and returns.
                   3541:         sigprocmask(SIG_UNBLOCK, $sigset)
                   3542:             or die "Can't unblock SIGINT for fork: $!\n";
                   3543:         $children{$pid} = $clientip;
                   3544:         &status('Started child '.$pid);
                   3545:         return;
                   3546:     } else {
                   3547:         # Child can *not* return from this subroutine.
                   3548:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   3549:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   3550:                                 #don't get intercepted
                   3551:         $SIG{USR1}= \&logstatus;
                   3552:         $SIG{ALRM}= \&timeout;
                   3553:         $lastlog='Forked ';
                   3554:         $status='Forked';
1.178     foxr     3555: 
1.212     foxr     3556:         # unblock signals
                   3557:         sigprocmask(SIG_UNBLOCK, $sigset)
                   3558:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     3559: 
1.212     foxr     3560: #        my $tmpsnum=0;            # Now global
                   3561: #---------------------------------------------------- kerberos 5 initialization
                   3562:         &Authen::Krb5::init_context();
                   3563:         &Authen::Krb5::init_ets();
1.209     albertel 3564: 
1.212     foxr     3565: 	&status('Accepted connection');
                   3566: # =============================================================================
                   3567:             # do something with the connection
                   3568: # -----------------------------------------------------------------------------
                   3569: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     3570: 
1.212     foxr     3571: 	ReadManagerTable;	# May also be a manager!!
                   3572: 	
                   3573: 	my $clientrec=($hostid{$clientip}     ne undef);
                   3574: 	my $ismanager=($managers{$clientip}    ne undef);
                   3575: 	$clientname  = "[unknonwn]";
                   3576: 	if($clientrec) {	# Establish client type.
                   3577: 	    $ConnectionType = "client";
                   3578: 	    $clientname = $hostid{$clientip};
                   3579: 	    if($ismanager) {
                   3580: 		$ConnectionType = "both";
                   3581: 	    }
                   3582: 	} else {
                   3583: 	    $ConnectionType = "manager";
                   3584: 	    $clientname = $managers{$clientip};
                   3585: 	}
                   3586: 	my $clientok;
1.178     foxr     3587: 
1.212     foxr     3588: 	if ($clientrec || $ismanager) {
                   3589: 	    &status("Waiting for init from $clientip $clientname");
                   3590: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   3591: 		     $clientip.
                   3592: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   3593: 	    &status("Connecting $clientip  ($clientname))"); 
                   3594: 	    my $remotereq=<$client>;
                   3595: 	    chomp($remotereq);
                   3596: 	    Debug("Got init: $remotereq");
                   3597: 	    my $inikeyword = split(/:/, $remotereq);
                   3598: 	    if ($remotereq =~ /^init/) {
                   3599: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   3600: 		#
                   3601: 		#  If the remote is attempting a local init... give that a try:
                   3602: 		#
                   3603: 		my ($i, $inittype) = split(/:/, $remotereq);
1.209     albertel 3604: 
1.212     foxr     3605: 		# If the connection type is ssl, but I didn't get my
                   3606: 		# certificate files yet, then I'll drop  back to 
                   3607: 		# insecure (if allowed).
                   3608: 		
                   3609: 		if($inittype eq "ssl") {
                   3610: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   3611: 		    my $kfile       = lonssl::KeyFile;
                   3612: 		    if((!$ca)   || 
                   3613: 		       (!$cert) || 
                   3614: 		       (!$kfile)) {
                   3615: 			$inittype = ""; # This forces insecure attempt.
                   3616: 			&logthis("<font color=\"blue\"> Certificates not "
                   3617: 				 ."installed -- trying insecure auth</font>");
1.178     foxr     3618: 		    }
1.212     foxr     3619: 		    else {	# SSL certificates are in place so
                   3620: 		    }		# Leave the inittype alone.
                   3621: 		}
                   3622: 
                   3623: 		if($inittype eq "local") {
                   3624: 		    my $key = LocalConnection($client, $remotereq);
                   3625: 		    if($key) {
                   3626: 			Debug("Got local key $key");
                   3627: 			$clientok     = 1;
                   3628: 			my $cipherkey = pack("H32", $key);
                   3629: 			$cipher       = new IDEA($cipherkey);
                   3630: 			print $client "ok:local\n";
                   3631: 			&logthis('<font color="green"'
                   3632: 				 . "Successful local authentication </font>");
                   3633: 			$keymode = "local"
1.178     foxr     3634: 		    } else {
1.212     foxr     3635: 			Debug("Failed to get local key");
                   3636: 			$clientok = 0;
                   3637: 			shutdown($client, 3);
                   3638: 			close $client;
1.178     foxr     3639: 		    }
1.212     foxr     3640: 		} elsif ($inittype eq "ssl") {
                   3641: 		    my $key = SSLConnection($client);
                   3642: 		    if ($key) {
                   3643: 			$clientok = 1;
                   3644: 			my $cipherkey = pack("H32", $key);
                   3645: 			$cipher       = new IDEA($cipherkey);
                   3646: 			&logthis('<font color="green">'
                   3647: 				 ."Successfull ssl authentication with $clientname </font>");
                   3648: 			$keymode = "ssl";
                   3649: 	     
1.178     foxr     3650: 		    } else {
1.212     foxr     3651: 			$clientok = 0;
                   3652: 			close $client;
1.178     foxr     3653: 		    }
1.212     foxr     3654: 	   
                   3655: 		} else {
                   3656: 		    my $ok = InsecureConnection($client);
                   3657: 		    if($ok) {
                   3658: 			$clientok = 1;
                   3659: 			&logthis('<font color="green">'
                   3660: 				 ."Successful insecure authentication with $clientname </font>");
                   3661: 			print $client "ok\n";
                   3662: 			$keymode = "insecure";
1.178     foxr     3663: 		    } else {
1.212     foxr     3664: 			&logthis('<font color="yellow">'
                   3665: 				  ."Attempted insecure connection disallowed </font>");
                   3666: 			close $client;
                   3667: 			$clientok = 0;
1.178     foxr     3668: 			
                   3669: 		    }
                   3670: 		}
1.212     foxr     3671: 	    } else {
                   3672: 		&logthis(
                   3673: 			 "<font color='blue'>WARNING: "
                   3674: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   3675: 		&status('No init '.$clientip);
                   3676: 	    }
                   3677: 	    
                   3678: 	} else {
                   3679: 	    &logthis(
                   3680: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   3681: 	    &status('Hung up on '.$clientip);
                   3682: 	}
                   3683:  
                   3684: 	if ($clientok) {
                   3685: # ---------------- New known client connecting, could mean machine online again
                   3686: 	    
                   3687: 	    foreach my $id (keys(%hostip)) {
                   3688: 		if ($hostip{$id} ne $clientip ||
                   3689: 		    $hostip{$currenthostid} eq $clientip) {
                   3690: 		    # no need to try to do recon's to myself
                   3691: 		    next;
                   3692: 		}
                   3693: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
                   3694: 	    }
                   3695: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   3696: 	    &status('Will listen to '.$clientname);
                   3697: # ------------------------------------------------------------ Process requests
                   3698: 	    my $keep_going = 1;
                   3699: 	    my $user_input;
                   3700: 	    while(($user_input = get_request) && $keep_going) {
                   3701: 		alarm(120);
                   3702: 		Debug("Main: Got $user_input\n");
                   3703: 		$keep_going = &process_request($user_input);
1.178     foxr     3704: 		alarm(0);
1.212     foxr     3705: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     3706: 	    }
1.212     foxr     3707: 
1.59      www      3708: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     3709: 	}  else {
1.161     foxr     3710: 	    print $client "refused\n";
                   3711: 	    $client->close();
1.190     albertel 3712: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     3713: 		     ."Rejected client $clientip, closing connection</font>");
                   3714: 	}
1.212     foxr     3715:     }            
1.161     foxr     3716:     
1.1       albertel 3717: # =============================================================================
1.161     foxr     3718:     
1.190     albertel 3719:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     3720: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   3721:     
                   3722:     
                   3723:     # this exit is VERY important, otherwise the child will become
                   3724:     # a producer of more and more children, forking yourself into
                   3725:     # process death.
                   3726:     exit;
1.106     foxr     3727:     
1.78      foxr     3728: }
                   3729: 
                   3730: 
                   3731: #
                   3732: #   Checks to see if the input roleput request was to set
                   3733: # an author role.  If so, invokes the lchtmldir script to set
                   3734: # up a correct public_html 
                   3735: # Parameters:
                   3736: #    request   - The request sent to the rolesput subchunk.
                   3737: #                We're looking for  /domain/_au
                   3738: #    domain    - The domain in which the user is having roles doctored.
                   3739: #    user      - Name of the user for which the role is being put.
                   3740: #    authtype  - The authentication type associated with the user.
                   3741: #
                   3742: sub ManagePermissions
                   3743: {
1.192     foxr     3744: 
                   3745:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     3746: 
                   3747:     # See if the request is of the form /$domain/_au
                   3748:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
                   3749: 	my $execdir = $perlvar{'lonDaemons'};
                   3750: 	my $userhome= "/home/$user" ;
1.134     albertel 3751: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.78      foxr     3752: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   3753:     }
                   3754: }
                   3755: #
                   3756: #   GetAuthType - Determines the authorization type of a user in a domain.
                   3757: 
                   3758: #     Returns the authorization type or nouser if there is no such user.
                   3759: #
                   3760: sub GetAuthType 
                   3761: {
1.192     foxr     3762: 
                   3763:     my ($domain, $user)  = @_;
1.78      foxr     3764: 
1.79      foxr     3765:     Debug("GetAuthType( $domain, $user ) \n");
1.78      foxr     3766:     my $proname    = &propath($domain, $user); 
                   3767:     my $passwdfile = "$proname/passwd";
                   3768:     if( -e $passwdfile ) {
                   3769: 	my $pf = IO::File->new($passwdfile);
                   3770: 	my $realpassword = <$pf>;
                   3771: 	chomp($realpassword);
1.79      foxr     3772: 	Debug("Password info = $realpassword\n");
1.78      foxr     3773: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     3774: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.78      foxr     3775: 	my $availinfo = '';
1.91      albertel 3776: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
1.78      foxr     3777: 	    $availinfo = $contentpwd;
                   3778: 	}
1.79      foxr     3779: 
1.78      foxr     3780: 	return "$authtype:$availinfo";
                   3781:     }
                   3782:     else {
1.79      foxr     3783: 	Debug("Returning nouser");
1.78      foxr     3784: 	return "nouser";
                   3785:     }
1.1       albertel 3786: }
                   3787: 
1.84      albertel 3788: sub addline {
                   3789:     my ($fname,$hostid,$ip,$newline)=@_;
                   3790:     my $contents;
                   3791:     my $found=0;
                   3792:     my $expr='^'.$hostid.':'.$ip.':';
                   3793:     $expr =~ s/\./\\\./g;
1.134     albertel 3794:     my $sh;
1.84      albertel 3795:     if ($sh=IO::File->new("$fname.subscription")) {
                   3796: 	while (my $subline=<$sh>) {
                   3797: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   3798: 	}
                   3799: 	$sh->close();
                   3800:     }
                   3801:     $sh=IO::File->new(">$fname.subscription");
                   3802:     if ($contents) { print $sh $contents; }
                   3803:     if ($newline) { print $sh $newline; }
                   3804:     $sh->close();
                   3805:     return $found;
1.86      www      3806: }
                   3807: 
                   3808: sub getchat {
1.122     www      3809:     my ($cdom,$cname,$udom,$uname)=@_;
1.87      www      3810:     my %hash;
                   3811:     my $proname=&propath($cdom,$cname);
                   3812:     my @entries=();
1.88      albertel 3813:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   3814: 	    &GDBM_READER(),0640)) {
                   3815: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   3816: 	untie %hash;
1.123     www      3817:     }
1.124     www      3818:     my @participants=();
1.134     albertel 3819:     my $cutoff=time-60;
1.123     www      3820:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124     www      3821: 	    &GDBM_WRCREAT(),0640)) {
                   3822:         $hash{$uname.':'.$udom}=time;
1.123     www      3823:         foreach (sort keys %hash) {
                   3824: 	    if ($hash{$_}>$cutoff) {
1.124     www      3825: 		$participants[$#participants+1]='active_participant:'.$_;
1.123     www      3826:             }
                   3827:         }
                   3828:         untie %hash;
1.86      www      3829:     }
1.124     www      3830:     return (@participants,@entries);
1.86      www      3831: }
                   3832: 
                   3833: sub chatadd {
1.88      albertel 3834:     my ($cdom,$cname,$newchat)=@_;
                   3835:     my %hash;
                   3836:     my $proname=&propath($cdom,$cname);
                   3837:     my @entries=();
1.142     www      3838:     my $time=time;
1.88      albertel 3839:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   3840: 	    &GDBM_WRCREAT(),0640)) {
                   3841: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   3842: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   3843: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   3844: 	my $newid=$time.'_000000';
                   3845: 	if ($thentime==$time) {
                   3846: 	    $idnum=~s/^0+//;
                   3847: 	    $idnum++;
                   3848: 	    $idnum=substr('000000'.$idnum,-6,6);
                   3849: 	    $newid=$time.'_'.$idnum;
                   3850: 	}
                   3851: 	$hash{$newid}=$newchat;
                   3852: 	my $expired=$time-3600;
                   3853: 	foreach (keys %hash) {
                   3854: 	    my ($thistime)=($_=~/(\d+)\_/);
                   3855: 	    if ($thistime<$expired) {
1.89      www      3856: 		delete $hash{$_};
1.88      albertel 3857: 	    }
                   3858: 	}
                   3859: 	untie %hash;
1.142     www      3860:     }
                   3861:     {
                   3862: 	my $hfh;
                   3863: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
                   3864: 	    print $hfh "$time:".&unescape($newchat)."\n";
                   3865: 	}
1.86      www      3866:     }
1.84      albertel 3867: }
                   3868: 
                   3869: sub unsub {
                   3870:     my ($fname,$clientip)=@_;
                   3871:     my $result;
1.188     foxr     3872:     my $unsubs = 0;		# Number of successful unsubscribes:
                   3873: 
                   3874: 
                   3875:     # An old way subscriptions were handled was to have a 
                   3876:     # subscription marker file:
                   3877: 
                   3878:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     3879:     if (unlink("$fname.$clientname")) {
1.188     foxr     3880: 	$unsubs++;		# Successful unsub via marker file.
                   3881:     } 
                   3882: 
                   3883:     # The more modern way to do it is to have a subscription list
                   3884:     # file:
                   3885: 
1.84      albertel 3886:     if (-e "$fname.subscription") {
1.161     foxr     3887: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     3888: 	if ($found) { 
                   3889: 	    $unsubs++;
                   3890: 	}
                   3891:     } 
                   3892: 
                   3893:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   3894:     #  resource we can return ok:
                   3895: 
                   3896:     if($unsubs) {
                   3897: 	$result = "ok\n";
1.84      albertel 3898:     } else {
1.188     foxr     3899: 	$result = "not_subscribed\n";
1.84      albertel 3900:     }
1.188     foxr     3901: 
1.84      albertel 3902:     return $result;
                   3903: }
                   3904: 
1.101     www      3905: sub currentversion {
                   3906:     my $fname=shift;
                   3907:     my $version=-1;
                   3908:     my $ulsdir='';
                   3909:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   3910:        $ulsdir=$1;
                   3911:     }
1.114     albertel 3912:     my ($fnamere1,$fnamere2);
                   3913:     # remove version if already specified
1.101     www      3914:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 3915:     # get the bits that go before and after the version number
                   3916:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   3917: 	$fnamere1=$1;
                   3918: 	$fnamere2='.'.$2;
                   3919:     }
1.101     www      3920:     if (-e $fname) { $version=1; }
                   3921:     if (-e $ulsdir) {
1.134     albertel 3922: 	if(-d $ulsdir) {
                   3923: 	    if (opendir(LSDIR,$ulsdir)) {
                   3924: 		my $ulsfn;
                   3925: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      3926: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 3927: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   3928: 		    unless (-l $thisfile) {
1.160     www      3929: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 3930: 			    if ($1>$version) { $version=$1; }
                   3931: 			}
                   3932: 		    }
                   3933: 		}
                   3934: 		closedir(LSDIR);
                   3935: 		$version++;
                   3936: 	    }
                   3937: 	}
                   3938:     }
                   3939:     return $version;
1.101     www      3940: }
                   3941: 
                   3942: sub thisversion {
                   3943:     my $fname=shift;
                   3944:     my $version=-1;
                   3945:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   3946: 	$version=$1;
                   3947:     }
                   3948:     return $version;
                   3949: }
                   3950: 
1.84      albertel 3951: sub subscribe {
                   3952:     my ($userinput,$clientip)=@_;
                   3953:     my $result;
                   3954:     my ($cmd,$fname)=split(/:/,$userinput);
                   3955:     my $ownership=&ishome($fname);
                   3956:     if ($ownership eq 'owner') {
1.101     www      3957: # explitly asking for the current version?
                   3958:         unless (-e $fname) {
                   3959:             my $currentversion=&currentversion($fname);
                   3960: 	    if (&thisversion($fname)==$currentversion) {
                   3961:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   3962: 		    my $root=$1;
                   3963:                     my $extension=$2;
                   3964:                     symlink($root.'.'.$extension,
                   3965:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      3966:                     unless ($extension=~/\.meta$/) {
                   3967:                        symlink($root.'.'.$extension.'.meta',
                   3968:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   3969: 		    }
1.101     www      3970:                 }
                   3971:             }
                   3972:         }
1.84      albertel 3973: 	if (-e $fname) {
                   3974: 	    if (-d $fname) {
                   3975: 		$result="directory\n";
                   3976: 	    } else {
1.161     foxr     3977: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 3978: 		my $now=time;
1.161     foxr     3979: 		my $found=&addline($fname,$clientname,$clientip,
                   3980: 				   "$clientname:$clientip:$now\n");
1.84      albertel 3981: 		if ($found) { $result="$fname\n"; }
                   3982: 		# if they were subscribed to only meta data, delete that
                   3983:                 # subscription, when you subscribe to a file you also get
                   3984:                 # the metadata
                   3985: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   3986: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
                   3987: 		$fname="http://$thisserver/".$fname;
                   3988: 		$result="$fname\n";
                   3989: 	    }
                   3990: 	} else {
                   3991: 	    $result="not_found\n";
                   3992: 	}
                   3993:     } else {
                   3994: 	$result="rejected\n";
                   3995:     }
                   3996:     return $result;
                   3997: }
1.91      albertel 3998: 
                   3999: sub make_passwd_file {
1.98      foxr     4000:     my ($uname, $umode,$npass,$passfilename)=@_;
1.91      albertel 4001:     my $result="ok\n";
                   4002:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   4003: 	{
                   4004: 	    my $pf = IO::File->new(">$passfilename");
                   4005: 	    print $pf "$umode:$npass\n";
                   4006: 	}
                   4007:     } elsif ($umode eq 'internal') {
                   4008: 	my $salt=time;
                   4009: 	$salt=substr($salt,6,2);
                   4010: 	my $ncpass=crypt($npass,$salt);
                   4011: 	{
                   4012: 	    &Debug("Creating internal auth");
                   4013: 	    my $pf = IO::File->new(">$passfilename");
                   4014: 	    print $pf "internal:$ncpass\n"; 
                   4015: 	}
                   4016:     } elsif ($umode eq 'localauth') {
                   4017: 	{
                   4018: 	    my $pf = IO::File->new(">$passfilename");
                   4019: 	    print $pf "localauth:$npass\n";
                   4020: 	}
                   4021:     } elsif ($umode eq 'unix') {
                   4022: 	{
1.186     foxr     4023: 	    #
                   4024: 	    #  Don't allow the creation of privileged accounts!!! that would
                   4025: 	    #  be real bad!!!
                   4026: 	    #
                   4027: 	    my $uid = getpwnam($uname);
                   4028: 	    if((defined $uid) && ($uid == 0)) {
                   4029: 		&logthis(">>>Attempted to create privilged account blocked");
                   4030: 		return "no_priv_account_error\n";
                   4031: 	    }
                   4032: 
1.91      albertel 4033: 	    my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
                   4034: 	    {
                   4035: 		&Debug("Executing external: ".$execpath);
1.98      foxr     4036: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  4037: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 4038: 		print $se "$uname\n";
                   4039: 		print $se "$npass\n";
                   4040: 		print $se "$npass\n";
1.97      foxr     4041: 	    }
                   4042: 	    my $useraddok = $?;
                   4043: 	    if($useraddok > 0) {
                   4044: 		&logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
1.91      albertel 4045: 	    }
                   4046: 	    my $pf = IO::File->new(">$passfilename");
                   4047: 	    print $pf "unix:\n";
                   4048: 	}
                   4049:     } elsif ($umode eq 'none') {
                   4050: 	{
                   4051: 	    my $pf = IO::File->new(">$passfilename");
                   4052: 	    print $pf "none:\n";
                   4053: 	}
                   4054:     } else {
                   4055: 	$result="auth_mode_error\n";
                   4056:     }
                   4057:     return $result;
1.121     albertel 4058: }
                   4059: 
                   4060: sub sethost {
                   4061:     my ($remotereq) = @_;
                   4062:     my (undef,$hostid)=split(/:/,$remotereq);
                   4063:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
                   4064:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200     matthew  4065: 	$currenthostid  =$hostid;
1.121     albertel 4066: 	$currentdomainid=$hostdom{$hostid};
                   4067: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
                   4068:     } else {
                   4069: 	&logthis("Requested host id $hostid not an alias of ".
                   4070: 		 $perlvar{'lonHostID'}." refusing connection");
                   4071: 	return 'unable_to_set';
                   4072:     }
                   4073:     return 'ok';
                   4074: }
                   4075: 
                   4076: sub version {
                   4077:     my ($userinput)=@_;
                   4078:     $remoteVERSION=(split(/:/,$userinput))[1];
                   4079:     return "version:$VERSION";
1.127     albertel 4080: }
1.178     foxr     4081: 
1.128     albertel 4082: #There is a copy of this in lonnet.pm
1.127     albertel 4083: sub userload {
                   4084:     my $numusers=0;
                   4085:     {
                   4086: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   4087: 	my $filename;
                   4088: 	my $curtime=time;
                   4089: 	while ($filename=readdir(LONIDS)) {
                   4090: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.138     albertel 4091: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159     albertel 4092: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.127     albertel 4093: 	}
                   4094: 	closedir(LONIDS);
                   4095:     }
                   4096:     my $userloadpercent=0;
                   4097:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   4098:     if ($maxuserload) {
1.129     albertel 4099: 	$userloadpercent=100*$numusers/$maxuserload;
1.127     albertel 4100:     }
1.130     albertel 4101:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127     albertel 4102:     return $userloadpercent;
1.91      albertel 4103: }
                   4104: 
1.205     raeburn  4105: # Routines for serializing arrays and hashes (copies from lonnet)
                   4106: 
                   4107: sub array2str {
                   4108:   my (@array) = @_;
                   4109:   my $result=&arrayref2str(\@array);
                   4110:   $result=~s/^__ARRAY_REF__//;
                   4111:   $result=~s/__END_ARRAY_REF__$//;
                   4112:   return $result;
                   4113: }
                   4114:                                                                                  
                   4115: sub arrayref2str {
                   4116:   my ($arrayref) = @_;
                   4117:   my $result='__ARRAY_REF__';
                   4118:   foreach my $elem (@$arrayref) {
                   4119:     if(ref($elem) eq 'ARRAY') {
                   4120:       $result.=&arrayref2str($elem).'&';
                   4121:     } elsif(ref($elem) eq 'HASH') {
                   4122:       $result.=&hashref2str($elem).'&';
                   4123:     } elsif(ref($elem)) {
                   4124:       #print("Got a ref of ".(ref($elem))." skipping.");
                   4125:     } else {
                   4126:       $result.=&escape($elem).'&';
                   4127:     }
                   4128:   }
                   4129:   $result=~s/\&$//;
                   4130:   $result .= '__END_ARRAY_REF__';
                   4131:   return $result;
                   4132: }
                   4133:                                                                                  
                   4134: sub hash2str {
                   4135:   my (%hash) = @_;
                   4136:   my $result=&hashref2str(\%hash);
                   4137:   $result=~s/^__HASH_REF__//;
                   4138:   $result=~s/__END_HASH_REF__$//;
                   4139:   return $result;
                   4140: }
                   4141:                                                                                  
                   4142: sub hashref2str {
                   4143:   my ($hashref)=@_;
                   4144:   my $result='__HASH_REF__';
                   4145:   foreach (sort(keys(%$hashref))) {
                   4146:     if (ref($_) eq 'ARRAY') {
                   4147:       $result.=&arrayref2str($_).'=';
                   4148:     } elsif (ref($_) eq 'HASH') {
                   4149:       $result.=&hashref2str($_).'=';
                   4150:     } elsif (ref($_)) {
                   4151:       $result.='=';
                   4152:       #print("Got a ref of ".(ref($_))." skipping.");
                   4153:     } else {
                   4154:         if ($_) {$result.=&escape($_).'=';} else { last; }
                   4155:     }
                   4156: 
                   4157:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   4158:       $result.=&arrayref2str($hashref->{$_}).'&';
                   4159:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   4160:       $result.=&hashref2str($hashref->{$_}).'&';
                   4161:     } elsif(ref($hashref->{$_})) {
                   4162:        $result.='&';
                   4163:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
                   4164:     } else {
                   4165:       $result.=&escape($hashref->{$_}).'&';
                   4166:     }
                   4167:   }
                   4168:   $result=~s/\&$//;
                   4169:   $result .= '__END_HASH_REF__';
                   4170:   return $result;
                   4171: }
1.200     matthew  4172: 
1.61      harris41 4173: # ----------------------------------- POD (plain old documentation, CPAN style)
                   4174: 
                   4175: =head1 NAME
                   4176: 
                   4177: lond - "LON Daemon" Server (port "LOND" 5663)
                   4178: 
                   4179: =head1 SYNOPSIS
                   4180: 
1.74      harris41 4181: Usage: B<lond>
                   4182: 
                   4183: Should only be run as user=www.  This is a command-line script which
                   4184: is invoked by B<loncron>.  There is no expectation that a typical user
                   4185: will manually start B<lond> from the command-line.  (In other words,
                   4186: DO NOT START B<lond> YOURSELF.)
1.61      harris41 4187: 
                   4188: =head1 DESCRIPTION
                   4189: 
1.74      harris41 4190: There are two characteristics associated with the running of B<lond>,
                   4191: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   4192: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   4193: subscriptions, etc).  These are described in two large
                   4194: sections below.
                   4195: 
                   4196: B<PROCESS MANAGEMENT>
                   4197: 
1.61      harris41 4198: Preforker - server who forks first. Runs as a daemon. HUPs.
                   4199: Uses IDEA encryption
                   4200: 
1.74      harris41 4201: B<lond> forks off children processes that correspond to the other servers
                   4202: in the network.  Management of these processes can be done at the
                   4203: parent process level or the child process level.
                   4204: 
                   4205: B<logs/lond.log> is the location of log messages.
                   4206: 
                   4207: The process management is now explained in terms of linux shell commands,
                   4208: subroutines internal to this code, and signal assignments:
                   4209: 
                   4210: =over 4
                   4211: 
                   4212: =item *
                   4213: 
                   4214: PID is stored in B<logs/lond.pid>
                   4215: 
                   4216: This is the process id number of the parent B<lond> process.
                   4217: 
                   4218: =item *
                   4219: 
                   4220: SIGTERM and SIGINT
                   4221: 
                   4222: Parent signal assignment:
                   4223:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   4224: 
                   4225: Child signal assignment:
                   4226:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   4227: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   4228:  to restart a new child.)
                   4229: 
                   4230: Command-line invocations:
                   4231:  B<kill> B<-s> SIGTERM I<PID>
                   4232:  B<kill> B<-s> SIGINT I<PID>
                   4233: 
                   4234: Subroutine B<HUNTSMAN>:
                   4235:  This is only invoked for the B<lond> parent I<PID>.
                   4236: This kills all the children, and then the parent.
                   4237: The B<lonc.pid> file is cleared.
                   4238: 
                   4239: =item *
                   4240: 
                   4241: SIGHUP
                   4242: 
                   4243: Current bug:
                   4244:  This signal can only be processed the first time
                   4245: on the parent process.  Subsequent SIGHUP signals
                   4246: have no effect.
                   4247: 
                   4248: Parent signal assignment:
                   4249:  $SIG{HUP}  = \&HUPSMAN;
                   4250: 
                   4251: Child signal assignment:
                   4252:  none (nothing happens)
                   4253: 
                   4254: Command-line invocations:
                   4255:  B<kill> B<-s> SIGHUP I<PID>
                   4256: 
                   4257: Subroutine B<HUPSMAN>:
                   4258:  This is only invoked for the B<lond> parent I<PID>,
                   4259: This kills all the children, and then the parent.
                   4260: The B<lond.pid> file is cleared.
                   4261: 
                   4262: =item *
                   4263: 
                   4264: SIGUSR1
                   4265: 
                   4266: Parent signal assignment:
                   4267:  $SIG{USR1} = \&USRMAN;
                   4268: 
                   4269: Child signal assignment:
                   4270:  $SIG{USR1}= \&logstatus;
                   4271: 
                   4272: Command-line invocations:
                   4273:  B<kill> B<-s> SIGUSR1 I<PID>
                   4274: 
                   4275: Subroutine B<USRMAN>:
                   4276:  When invoked for the B<lond> parent I<PID>,
                   4277: SIGUSR1 is sent to all the children, and the status of
                   4278: each connection is logged.
1.144     foxr     4279: 
                   4280: =item *
                   4281: 
                   4282: SIGUSR2
                   4283: 
                   4284: Parent Signal assignment:
                   4285:     $SIG{USR2} = \&UpdateHosts
                   4286: 
                   4287: Child signal assignment:
                   4288:     NONE
                   4289: 
1.74      harris41 4290: 
                   4291: =item *
                   4292: 
                   4293: SIGCHLD
                   4294: 
                   4295: Parent signal assignment:
                   4296:  $SIG{CHLD} = \&REAPER;
                   4297: 
                   4298: Child signal assignment:
                   4299:  none
                   4300: 
                   4301: Command-line invocations:
                   4302:  B<kill> B<-s> SIGCHLD I<PID>
                   4303: 
                   4304: Subroutine B<REAPER>:
                   4305:  This is only invoked for the B<lond> parent I<PID>.
                   4306: Information pertaining to the child is removed.
                   4307: The socket port is cleaned up.
                   4308: 
                   4309: =back
                   4310: 
                   4311: B<SERVER-SIDE ACTIVITIES>
                   4312: 
                   4313: Server-side information can be accepted in an encrypted or non-encrypted
                   4314: method.
                   4315: 
                   4316: =over 4
                   4317: 
                   4318: =item ping
                   4319: 
                   4320: Query a client in the hosts.tab table; "Are you there?"
                   4321: 
                   4322: =item pong
                   4323: 
                   4324: Respond to a ping query.
                   4325: 
                   4326: =item ekey
                   4327: 
                   4328: Read in encrypted key, make cipher.  Respond with a buildkey.
                   4329: 
                   4330: =item load
                   4331: 
                   4332: Respond with CPU load based on a computation upon /proc/loadavg.
                   4333: 
                   4334: =item currentauth
                   4335: 
                   4336: Reply with current authentication information (only over an
                   4337: encrypted channel).
                   4338: 
                   4339: =item auth
                   4340: 
                   4341: Only over an encrypted channel, reply as to whether a user's
                   4342: authentication information can be validated.
                   4343: 
                   4344: =item passwd
                   4345: 
                   4346: Allow for a password to be set.
                   4347: 
                   4348: =item makeuser
                   4349: 
                   4350: Make a user.
                   4351: 
                   4352: =item passwd
                   4353: 
                   4354: Allow for authentication mechanism and password to be changed.
                   4355: 
                   4356: =item home
1.61      harris41 4357: 
1.74      harris41 4358: Respond to a question "are you the home for a given user?"
                   4359: 
                   4360: =item update
                   4361: 
                   4362: Update contents of a subscribed resource.
                   4363: 
                   4364: =item unsubscribe
                   4365: 
                   4366: The server is unsubscribing from a resource.
                   4367: 
                   4368: =item subscribe
                   4369: 
                   4370: The server is subscribing to a resource.
                   4371: 
                   4372: =item log
                   4373: 
                   4374: Place in B<logs/lond.log>
                   4375: 
                   4376: =item put
                   4377: 
                   4378: stores hash in namespace
                   4379: 
                   4380: =item rolesput
                   4381: 
                   4382: put a role into a user's environment
                   4383: 
                   4384: =item get
                   4385: 
                   4386: returns hash with keys from array
                   4387: reference filled in from namespace
                   4388: 
                   4389: =item eget
                   4390: 
                   4391: returns hash with keys from array
                   4392: reference filled in from namesp (encrypts the return communication)
                   4393: 
                   4394: =item rolesget
                   4395: 
                   4396: get a role from a user's environment
                   4397: 
                   4398: =item del
                   4399: 
                   4400: deletes keys out of array from namespace
                   4401: 
                   4402: =item keys
                   4403: 
                   4404: returns namespace keys
                   4405: 
                   4406: =item dump
                   4407: 
                   4408: dumps the complete (or key matching regexp) namespace into a hash
                   4409: 
                   4410: =item store
                   4411: 
                   4412: stores hash permanently
                   4413: for this url; hashref needs to be given and should be a \%hashname; the
                   4414: remaining args aren't required and if they aren't passed or are '' they will
                   4415: be derived from the ENV
                   4416: 
                   4417: =item restore
                   4418: 
                   4419: returns a hash for a given url
                   4420: 
                   4421: =item querysend
                   4422: 
                   4423: Tells client about the lonsql process that has been launched in response
                   4424: to a sent query.
                   4425: 
                   4426: =item queryreply
                   4427: 
                   4428: Accept information from lonsql and make appropriate storage in temporary
                   4429: file space.
                   4430: 
                   4431: =item idput
                   4432: 
                   4433: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   4434: for each student, defined perhaps by the institutional Registrar.)
                   4435: 
                   4436: =item idget
                   4437: 
                   4438: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   4439: for each student, defined perhaps by the institutional Registrar.)
                   4440: 
                   4441: =item tmpput
                   4442: 
                   4443: Accept and store information in temporary space.
                   4444: 
                   4445: =item tmpget
                   4446: 
                   4447: Send along temporarily stored information.
                   4448: 
                   4449: =item ls
                   4450: 
                   4451: List part of a user's directory.
                   4452: 
1.135     foxr     4453: =item pushtable
                   4454: 
                   4455: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   4456: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   4457: must be restored manually in case of a problem with the new table file.
                   4458: pushtable requires that the request be encrypted and validated via
                   4459: ValidateManager.  The form of the command is:
                   4460: enc:pushtable tablename <tablecontents> \n
                   4461: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   4462: cleartext newline.
                   4463: 
1.74      harris41 4464: =item Hanging up (exit or init)
                   4465: 
                   4466: What to do when a client tells the server that they (the client)
                   4467: are leaving the network.
                   4468: 
                   4469: =item unknown command
                   4470: 
                   4471: If B<lond> is sent an unknown command (not in the list above),
                   4472: it replys to the client "unknown_cmd".
1.135     foxr     4473: 
1.74      harris41 4474: 
                   4475: =item UNKNOWN CLIENT
                   4476: 
                   4477: If the anti-spoofing algorithm cannot verify the client,
                   4478: the client is rejected (with a "refused" message sent
                   4479: to the client, and the connection is closed.
                   4480: 
                   4481: =back
1.61      harris41 4482: 
                   4483: =head1 PREREQUISITES
                   4484: 
                   4485: IO::Socket
                   4486: IO::File
                   4487: Apache::File
                   4488: Symbol
                   4489: POSIX
                   4490: Crypt::IDEA
                   4491: LWP::UserAgent()
                   4492: GDBM_File
                   4493: Authen::Krb4
1.91      albertel 4494: Authen::Krb5
1.61      harris41 4495: 
                   4496: =head1 COREQUISITES
                   4497: 
                   4498: =head1 OSNAMES
                   4499: 
                   4500: linux
                   4501: 
                   4502: =head1 SCRIPT CATEGORIES
                   4503: 
                   4504: Server/Process
                   4505: 
                   4506: =cut

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