Annotation of loncom/lond, revision 1.218

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.218   ! foxr        5: # $Id: lond,v 1.217 2004/07/28 21:33:22 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.218   ! foxr       59: my $VERSION='$Revision: 1.217 $'; #' 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.218   ! foxr     1207: #   Process a request for the authorization type of a user:
        !          1208: #   (userauth).
        !          1209: #
        !          1210: # Parameters:
        !          1211: #      $cmd    - the actual keyword that invoked us.
        !          1212: #      $tail   - the tail of the request that invoked us.
        !          1213: #      $replyfd- File descriptor connected to the client
        !          1214: #  Returns:
        !          1215: #      1       - Ok to continue processing.
        !          1216: #      0       - Program should exit
        !          1217: # Implicit outputs:
        !          1218: #    The user authorization type is written to the client.
        !          1219: #
        !          1220: sub user_authorization_type {
        !          1221:     my ($cmd, $tail, $replyfd) = @_;
        !          1222:    
        !          1223:     my $userinput = "$cmd:$tail";
        !          1224:    
        !          1225:     #  Pull the domain and username out of the command tail.
        !          1226:     # and call GetAuthType to determine the authentication type.
        !          1227:    
        !          1228:     my ($udom,$uname)=split(/:/,$tail);
        !          1229:     my $result = &GetAuthType($udom, $uname);
        !          1230:     if($result eq "nouser") {
        !          1231: 	&Failure( $replyfd, "unknown_user\n", $userinput);
        !          1232:     } else {
        !          1233: 	#
        !          1234: 	# We only want to pass the second field from GetAuthType
        !          1235: 	# for ^krb.. otherwise we'll be handing out the encrypted
        !          1236: 	# password for internals e.g.
        !          1237: 	#
        !          1238: 	my ($type,$otherinfo) = split(/:/,$result);
        !          1239: 	if($type =~ /^krb/) {
        !          1240: 	    $type = $result;
        !          1241: 	}
        !          1242: 	&Reply( $replyfd, "$type\n", $userinput);
        !          1243:     }
        !          1244:   
        !          1245:     return 1;
        !          1246: }
        !          1247: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
        !          1248: 
        !          1249: #   Process a request by a manager to push a hosts or domain table 
        !          1250: #   to us.  We pick apart the command and pass it on to the subs
        !          1251: #   that already exist to do this.
        !          1252: #
        !          1253: # Parameters:
        !          1254: #      $cmd    - the actual keyword that invoked us.
        !          1255: #      $tail   - the tail of the request that invoked us.
        !          1256: #      $client - File descriptor connected to the client
        !          1257: #  Returns:
        !          1258: #      1       - Ok to continue processing.
        !          1259: #      0       - Program should exit
        !          1260: # Implicit Output:
        !          1261: #    a reply is written to the client.
        !          1262: 
        !          1263: sub push_file_handler {
        !          1264:     my ($cmd, $tail, $client) = @_;
        !          1265: 
        !          1266:     my $userinput = "$cmd:$tail";
        !          1267: 
        !          1268:     # At this time we only know that the IP of our partner is a valid manager
        !          1269:     # the code below is a hook to do further authentication (e.g. to resolve
        !          1270:     # spoofing).
        !          1271: 
        !          1272:     my $cert = &GetCertificate($userinput);
        !          1273:     if(&ValidManager($cert)) { 
        !          1274: 
        !          1275: 	# Now presumably we have the bona fides of both the peer host and the
        !          1276: 	# process making the request.
        !          1277:       
        !          1278: 	my $reply = &PushFile($userinput);
        !          1279: 	&Reply($client, "$reply\n", $userinput);
        !          1280: 
        !          1281:     } else {
        !          1282: 	&Failure( $client, "refused\n", $userinput);
        !          1283:     } 
        !          1284: }
        !          1285: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
        !          1286: 
        !          1287: 
        !          1288: 
        !          1289: #   Process a reinit request.  Reinit requests that either
        !          1290: #   lonc or lond be reinitialized so that an updated 
        !          1291: #   host.tab or domain.tab can be processed.
        !          1292: #
        !          1293: # Parameters:
        !          1294: #      $cmd    - the actual keyword that invoked us.
        !          1295: #      $tail   - the tail of the request that invoked us.
        !          1296: #      $client - File descriptor connected to the client
        !          1297: #  Returns:
        !          1298: #      1       - Ok to continue processing.
        !          1299: #      0       - Program should exit
        !          1300: #  Implicit output:
        !          1301: #     a reply is sent to the client.
        !          1302: #
        !          1303: sub reinit_process_handler {
        !          1304:     my ($cmd, $tail, $client) = @_;
        !          1305:    
        !          1306:     my $userinput = "$cmd:$tail";
        !          1307:    
        !          1308:     my $cert = &GetCertificate($userinput);
        !          1309:     if(&ValidManager($cert)) {
        !          1310: 	chomp($userinput);
        !          1311: 	my $reply = &ReinitProcess($userinput);
        !          1312: 	&Reply( $client,  "$reply\n", $userinput);
        !          1313:     } else {
        !          1314: 	&Failure( $client, "refused\n", $userinput);
        !          1315:     }
        !          1316:     return 1;
        !          1317: }
        !          1318: 
        !          1319: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
        !          1320: 
        !          1321: #  Process the editing script for a table edit operation.
        !          1322: #  the editing operation must be encrypted and requested by
        !          1323: #  a manager host.
        !          1324: #
        !          1325: # Parameters:
        !          1326: #      $cmd    - the actual keyword that invoked us.
        !          1327: #      $tail   - the tail of the request that invoked us.
        !          1328: #      $client - File descriptor connected to the client
        !          1329: #  Returns:
        !          1330: #      1       - Ok to continue processing.
        !          1331: #      0       - Program should exit
        !          1332: #  Implicit output:
        !          1333: #     a reply is sent to the client.
        !          1334: #
        !          1335: sub edit_table_handler {
        !          1336:     my ($command, $tail, $client) = @_;
        !          1337:    
        !          1338:     my $userinput = "$command:$tail";
        !          1339: 
        !          1340:     my $cert = &GetCertificate($userinput);
        !          1341:     if(&ValidManager($cert)) {
        !          1342: 	my($filetype, $script) = split(/:/, $tail);
        !          1343: 	if (($filetype eq "hosts") || 
        !          1344: 	    ($filetype eq "domain")) {
        !          1345: 	    if($script ne "") {
        !          1346: 		&Reply($client,              # BUGBUG - EditFile
        !          1347: 		      &EditFile($userinput), #   could fail.
        !          1348: 		      $userinput);
        !          1349: 	    } else {
        !          1350: 		&Failure($client,"refused\n",$userinput);
        !          1351: 	    }
        !          1352: 	} else {
        !          1353: 	    &Failure($client,"refused\n",$userinput);
        !          1354: 	}
        !          1355:     } else {
        !          1356: 	&Failure($client,"refused\n",$userinput);
        !          1357:     }
        !          1358:     return 1;
        !          1359: }
        !          1360: register_handler("edit", \&edit_table_handler, 1, 0, 1);
        !          1361: 
        !          1362: 
        !          1363: 
1.214     foxr     1364: 
1.207     foxr     1365: #---------------------------------------------------------------
                   1366: #
                   1367: #   Getting, decoding and dispatching requests:
                   1368: #
                   1369: 
                   1370: #
                   1371: #   Get a Request:
                   1372: #   Gets a Request message from the client.  The transaction
                   1373: #   is defined as a 'line' of text.  We remove the new line
                   1374: #   from the text line.  
                   1375: #   
1.211     albertel 1376: sub get_request {
1.207     foxr     1377:     my $input = <$client>;
                   1378:     chomp($input);
                   1379: 
1.212     foxr     1380:     Debug("get_request: Request = $input\n");
1.207     foxr     1381: 
                   1382:     &status('Processing '.$clientname.':'.$input);
                   1383: 
                   1384:     return $input;
                   1385: }
1.212     foxr     1386: #---------------------------------------------------------------
                   1387: #
                   1388: #  Process a request.  This sub should shrink as each action
                   1389: #  gets farmed out into a separat sub that is registered 
                   1390: #  with the dispatch hash.  
                   1391: #
                   1392: # Parameters:
                   1393: #    user_input   - The request received from the client (lonc).
                   1394: # Returns:
                   1395: #    true to keep processing, false if caller should exit.
                   1396: #
                   1397: sub process_request {
                   1398:     my ($userinput) = @_;      # Easier for now to break style than to
                   1399:                                 # fix all the userinput -> user_input.
                   1400:     my $wasenc    = 0;		# True if request was encrypted.
                   1401: # ------------------------------------------------------------ See if encrypted
                   1402:     if ($userinput =~ /^enc/) {
                   1403: 	$userinput = decipher($userinput);
                   1404: 	$wasenc=1;
                   1405: 	if(!$userinput) {	# Cipher not defined.
                   1406: 	    &Failure($client, "error: Encrypted data without negotated key");
                   1407: 	    return 0;
                   1408: 	}
                   1409:     }
                   1410:     Debug("process_request: $userinput\n");
                   1411:     
1.213     foxr     1412:     #  
                   1413:     #   The 'correct way' to add a command to lond is now to
                   1414:     #   write a sub to execute it and Add it to the command dispatch
                   1415:     #   hash via a call to register_handler..  The comments to that
                   1416:     #   sub should give you enough to go on to show how to do this
                   1417:     #   along with the examples that are building up as this code
                   1418:     #   is getting refactored.   Until all branches of the
                   1419:     #   if/elseif monster below have been factored out into
                   1420:     #   separate procesor subs, if the dispatch hash is missing
                   1421:     #   the command keyword, we will fall through to the remainder
                   1422:     #   of the if/else chain below in order to keep this thing in 
                   1423:     #   working order throughout the transmogrification.
                   1424: 
                   1425:     my ($command, $tail) = split(/:/, $userinput, 2);
                   1426:     chomp($command);
                   1427:     chomp($tail);
                   1428:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     1429:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   1430:     if(!$tail) {
                   1431: 	$tail ="";		# defined but blank.
                   1432:     }
1.213     foxr     1433: 
                   1434:     &Debug("Command received: $command, encoded = $wasenc");
                   1435: 
                   1436:     if(defined $Dispatcher{$command}) {
                   1437: 
                   1438: 	my $dispatch_info = $Dispatcher{$command};
                   1439: 	my $handler       = $$dispatch_info[0];
                   1440: 	my $need_encode   = $$dispatch_info[1];
                   1441: 	my $client_types  = $$dispatch_info[2];
                   1442: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   1443: 	      ."ClientType $client_types");
                   1444:       
                   1445: 	#  Validate the request:
                   1446:       
                   1447: 	my $ok = 1;
                   1448: 	my $requesterprivs = 0;
                   1449: 	if(&isClient()) {
                   1450: 	    $requesterprivs |= $CLIENT_OK;
                   1451: 	}
                   1452: 	if(&isManager()) {
                   1453: 	    $requesterprivs |= $MANAGER_OK;
                   1454: 	}
                   1455: 	if($need_encode && (!$wasenc)) {
                   1456: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   1457: 	    $ok = 0;
                   1458: 	}
                   1459: 	if(($client_types & $requesterprivs) == 0) {
                   1460: 	    Debug("Client not privileged to do this operation");
                   1461: 	    $ok = 0;
                   1462: 	}
                   1463: 
                   1464: 	if($ok) {
                   1465: 	    Debug("Dispatching to handler $command $tail");
                   1466: 	    my $keep_going = &$handler($command, $tail, $client);
                   1467: 	    return $keep_going;
                   1468: 	} else {
                   1469: 	    Debug("Refusing to dispatch because client did not match requirements");
                   1470: 	    Failure($client, "refused\n", $userinput);
                   1471: 	    return 1;
                   1472: 	}
                   1473: 
                   1474:     }    
                   1475: 
1.215     foxr     1476: #------------------- Commands not yet in spearate handlers. --------------
                   1477: 
1.218   ! foxr     1478: 
1.212     foxr     1479: # ------------------------------------------------------------------------ auth
1.218   ! foxr     1480:     if ($userinput =~ /^auth/) { # Encoded and client only.
1.212     foxr     1481: 	if (($wasenc==1) && isClient) {
                   1482: 	    my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
                   1483: 	    chomp($upass);
                   1484: 	    $upass=unescape($upass);
                   1485: 	    my $proname=propath($udom,$uname);
                   1486: 	    my $passfilename="$proname/passwd";
                   1487: 	    if (-e $passfilename) {
                   1488: 		my $pf = IO::File->new($passfilename);
                   1489: 		my $realpasswd=<$pf>;
                   1490: 		chomp($realpasswd);
                   1491: 		my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   1492: 		my $pwdcorrect=0;
                   1493: 		if ($howpwd eq 'internal') {
                   1494: 		    &Debug("Internal auth");
                   1495: 		    $pwdcorrect=
                   1496: 			(crypt($upass,$contentpwd) eq $contentpwd);
                   1497: 		} elsif ($howpwd eq 'unix') {
                   1498: 		    &Debug("Unix auth");
                   1499: 		    if((getpwnam($uname))[1] eq "") { #no such user!
                   1500: 			$pwdcorrect = 0;
                   1501: 		    } else {
                   1502: 			$contentpwd=(getpwnam($uname))[1];
                   1503: 			my $pwauth_path="/usr/local/sbin/pwauth";
                   1504: 			unless ($contentpwd eq 'x') {
                   1505: 			    $pwdcorrect=
                   1506: 				(crypt($upass,$contentpwd) eq 
                   1507: 				 $contentpwd);
                   1508: 			}
                   1509: 			
                   1510: 			elsif (-e $pwauth_path) {
                   1511: 			    open PWAUTH, "|$pwauth_path" or
                   1512: 				die "Cannot invoke authentication";
                   1513: 			    print PWAUTH "$uname\n$upass\n";
                   1514: 			    close PWAUTH;
                   1515: 			    $pwdcorrect=!$?;
                   1516: 			}
                   1517: 		    }
                   1518: 		} elsif ($howpwd eq 'krb4') {
                   1519: 		    my $null=pack("C",0);
                   1520: 		    unless ($upass=~/$null/) {
                   1521: 			my $krb4_error = &Authen::Krb4::get_pw_in_tkt
                   1522: 			    ($uname,"",$contentpwd,'krbtgt',
                   1523: 			     $contentpwd,1,$upass);
                   1524: 			if (!$krb4_error) {
                   1525: 			    $pwdcorrect = 1;
                   1526: 			} else { 
                   1527: 			    $pwdcorrect=0; 
                   1528: 			    # log error if it is not a bad password
                   1529: 			    if ($krb4_error != 62) {
                   1530: 				&logthis('krb4:'.$uname.','.
                   1531: 					 &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   1532: 			    }
                   1533: 			}
                   1534: 		    }
                   1535: 		} elsif ($howpwd eq 'krb5') {
                   1536: 		    my $null=pack("C",0);
                   1537: 		    unless ($upass=~/$null/) {
                   1538: 			my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
                   1539: 			my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
                   1540: 			my $krbserver=&Authen::Krb5::parse_name($krbservice);
                   1541: 			my $credentials=&Authen::Krb5::cc_default();
                   1542: 			$credentials->initialize($krbclient);
                   1543: 			my $krbreturn = 
                   1544: 			    &Authen::Krb5::get_in_tkt_with_password(
                   1545: 								    $krbclient,$krbserver,$upass,$credentials);
                   1546: #				  unless ($krbreturn) {
                   1547: #				      &logthis("Krb5 Error: ".
                   1548: #					       &Authen::Krb5::error());
                   1549: #				  }
                   1550: 			$pwdcorrect = ($krbreturn == 1);
                   1551: 		    } else { $pwdcorrect=0; }
                   1552: 		} elsif ($howpwd eq 'localauth') {
                   1553: 		    $pwdcorrect=&localauth::localauth($uname,$upass,
                   1554: 						      $contentpwd);
                   1555: 		}
                   1556: 		if ($pwdcorrect) {
                   1557: 		    print $client "authorized\n";
                   1558: 		} else {
                   1559: 		    print $client "non_authorized\n";
                   1560: 		}  
                   1561: 	    } else {
                   1562: 		print $client "unknown_user\n";
                   1563: 	    }
                   1564: 	} else {
                   1565: 	    Reply($client, "refused\n", $userinput);
                   1566: 	    
                   1567: 	}
                   1568: # ---------------------------------------------------------------------- passwd
                   1569:     } elsif ($userinput =~ /^passwd/) { # encoded and client
                   1570: 	if (($wasenc==1) && isClient) {
                   1571: 	    my 
                   1572: 		($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
                   1573: 	    chomp($npass);
                   1574: 	    $upass=&unescape($upass);
                   1575: 	    $npass=&unescape($npass);
                   1576: 	    &Debug("Trying to change password for $uname");
                   1577: 	    my $proname=propath($udom,$uname);
                   1578: 	    my $passfilename="$proname/passwd";
                   1579: 	    if (-e $passfilename) {
                   1580: 		my $realpasswd;
                   1581: 		{ my $pf = IO::File->new($passfilename);
                   1582: 		  $realpasswd=<$pf>; }
                   1583: 		chomp($realpasswd);
                   1584: 		my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   1585: 		if ($howpwd eq 'internal') {
                   1586: 		    &Debug("internal auth");
                   1587: 		    if (crypt($upass,$contentpwd) eq $contentpwd) {
                   1588: 			my $salt=time;
                   1589: 			$salt=substr($salt,6,2);
                   1590: 			my $ncpass=crypt($npass,$salt);
                   1591: 			{
                   1592: 			    my $pf;
                   1593: 			    if ($pf = IO::File->new(">$passfilename")) {
                   1594: 				print $pf "internal:$ncpass\n";
                   1595: 				&logthis("Result of password change for $uname: pwchange_success");
                   1596: 				print $client "ok\n";
                   1597: 			    } else {
                   1598: 				&logthis("Unable to open $uname passwd to change password");
                   1599: 				print $client "non_authorized\n";
                   1600: 			    }
                   1601: 			}             
                   1602: 			
                   1603: 		    } else {
                   1604: 			print $client "non_authorized\n";
                   1605: 		    }
                   1606: 		} elsif ($howpwd eq 'unix') {
                   1607: 		    # Unix means we have to access /etc/password
                   1608: 		    # one way or another.
                   1609: 		    # First: Make sure the current password is
                   1610: 		    #        correct
                   1611: 		    &Debug("auth is unix");
                   1612: 		    $contentpwd=(getpwnam($uname))[1];
                   1613: 		    my $pwdcorrect = "0";
                   1614: 		    my $pwauth_path="/usr/local/sbin/pwauth";
                   1615: 		    unless ($contentpwd eq 'x') {
                   1616: 			$pwdcorrect=
                   1617: 			    (crypt($upass,$contentpwd) eq $contentpwd);
                   1618: 		    } elsif (-e $pwauth_path) {
                   1619: 			open PWAUTH, "|$pwauth_path" or
                   1620: 			    die "Cannot invoke authentication";
                   1621: 			print PWAUTH "$uname\n$upass\n";
                   1622: 			close PWAUTH;
                   1623: 			&Debug("exited pwauth with $? ($uname,$upass) ");
                   1624: 			$pwdcorrect=($? == 0);
                   1625: 		    }
                   1626: 		    if ($pwdcorrect) {
                   1627: 			my $execdir=$perlvar{'lonDaemons'};
                   1628: 			&Debug("Opening lcpasswd pipeline");
                   1629: 			my $pf = IO::File->new("|$execdir/lcpasswd > $perlvar{'lonDaemons'}/logs/lcpasswd.log");
                   1630: 			print $pf "$uname\n$npass\n$npass\n";
                   1631: 			close $pf;
                   1632: 			my $err = $?;
                   1633: 			my $result = ($err>0 ? 'pwchange_failure' 
                   1634: 				      : 'ok');
                   1635: 			&logthis("Result of password change for $uname: ".
                   1636: 				 &lcpasswdstrerror($?));
                   1637: 			print $client "$result\n";
                   1638: 		    } else {
                   1639: 			print $client "non_authorized\n";
                   1640: 		    }
                   1641: 		} else {
                   1642: 		    print $client "auth_mode_error\n";
                   1643: 		}  
                   1644: 	    } else {
                   1645: 		print $client "unknown_user\n";
                   1646: 	    }
                   1647: 	} else {
                   1648: 	    Reply($client, "refused\n", $userinput);
                   1649: 	    
                   1650: 	}
                   1651: # -------------------------------------------------------------------- makeuser
                   1652:     } elsif ($userinput =~ /^makeuser/) { # encoded and client.
                   1653: 	&Debug("Make user received");
                   1654: 	my $oldumask=umask(0077);
                   1655: 	if (($wasenc==1) && isClient) {
                   1656: 	    my 
                   1657: 		($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
                   1658: 	    &Debug("cmd =".$cmd." $udom =".$udom.
                   1659: 		   " uname=".$uname);
                   1660: 	    chomp($npass);
                   1661: 	    $npass=&unescape($npass);
                   1662: 	    my $proname=propath($udom,$uname);
                   1663: 	    my $passfilename="$proname/passwd";
                   1664: 	    &Debug("Password file created will be:".
                   1665: 		   $passfilename);
                   1666: 	    if (-e $passfilename) {
                   1667: 		print $client "already_exists\n";
                   1668: 	    } elsif ($udom ne $currentdomainid) {
                   1669: 		print $client "not_right_domain\n";
                   1670: 	    } else {
                   1671: 		my @fpparts=split(/\//,$proname);
                   1672: 		my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
                   1673: 		my $fperror='';
                   1674: 		for (my $i=3;$i<=$#fpparts;$i++) {
                   1675: 		    $fpnow.='/'.$fpparts[$i]; 
                   1676: 		    unless (-e $fpnow) {
                   1677: 			unless (mkdir($fpnow,0777)) {
                   1678: 			    $fperror="error: ".($!+0)
                   1679: 				." mkdir failed while attempting "
                   1680: 				."makeuser";
                   1681: 			}
                   1682: 		    }
                   1683: 		}
                   1684: 		unless ($fperror) {
                   1685: 		    my $result=&make_passwd_file($uname, $umode,$npass,
                   1686: 						 $passfilename);
                   1687: 		    print $client $result;
                   1688: 		} else {
                   1689: 		    print $client "$fperror\n";
                   1690: 		}
                   1691: 	    }
                   1692: 	} else {
                   1693: 	    Reply($client, "refused\n", $userinput);
                   1694: 	    
                   1695: 	}
                   1696: 	umask($oldumask);
                   1697: # -------------------------------------------------------------- changeuserauth
                   1698:     } elsif ($userinput =~ /^changeuserauth/) { # encoded & client
                   1699: 	&Debug("Changing authorization");
                   1700: 	if (($wasenc==1) && isClient) {
                   1701: 	    my 
                   1702: 		($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
                   1703: 	    chomp($npass);
                   1704: 	    &Debug("cmd = ".$cmd." domain= ".$udom.
                   1705: 		   "uname =".$uname." umode= ".$umode);
                   1706: 	    $npass=&unescape($npass);
                   1707: 	    my $proname=&propath($udom,$uname);
                   1708: 	    my $passfilename="$proname/passwd";
                   1709: 	    if ($udom ne $currentdomainid) {
                   1710: 		print $client "not_right_domain\n";
                   1711: 	    } else {
                   1712: 		my $result=&make_passwd_file($uname, $umode,$npass,
                   1713: 					     $passfilename);
                   1714: 		print $client $result;
                   1715: 	    }
                   1716: 	} else {
                   1717: 	    Reply($client, "refused\n", $userinput);
                   1718: 	    
                   1719: 	}
                   1720: # ------------------------------------------------------------------------ home
                   1721:     } elsif ($userinput =~ /^home/) { # client clear or encoded
                   1722: 	if(isClient) {
                   1723: 	    my ($cmd,$udom,$uname)=split(/:/,$userinput);
                   1724: 	    chomp($uname);
                   1725: 	    my $proname=propath($udom,$uname);
                   1726: 	    if (-e $proname) {
                   1727: 		print $client "found\n";
                   1728: 	    } else {
                   1729: 		print $client "not_found\n";
                   1730: 	    }
                   1731: 	} else {
                   1732: 	    Reply($client, "refused\n", $userinput);
                   1733: 	    
                   1734: 	}
                   1735: # ---------------------------------------------------------------------- update
                   1736:     } elsif ($userinput =~ /^update/) { # client clear or encoded.
                   1737: 	if(isClient) {
                   1738: 	    my ($cmd,$fname)=split(/:/,$userinput);
                   1739: 	    my $ownership=ishome($fname);
                   1740: 	    if ($ownership eq 'not_owner') {
                   1741: 		if (-e $fname) {
                   1742: 		    my ($dev,$ino,$mode,$nlink,
                   1743: 			$uid,$gid,$rdev,$size,
                   1744: 			$atime,$mtime,$ctime,
                   1745: 			$blksize,$blocks)=stat($fname);
                   1746: 		    my $now=time;
                   1747: 		    my $since=$now-$atime;
                   1748: 		    if ($since>$perlvar{'lonExpire'}) {
                   1749: 			my $reply=
                   1750: 			    &reply("unsub:$fname","$clientname");
                   1751: 				    unlink("$fname");
                   1752: 		    } else {
                   1753: 			my $transname="$fname.in.transfer";
                   1754: 			my $remoteurl=
                   1755: 			    &reply("sub:$fname","$clientname");
                   1756: 			my $response;
                   1757: 			{
                   1758: 			    my $ua=new LWP::UserAgent;
                   1759: 			    my $request=new HTTP::Request('GET',"$remoteurl");
                   1760: 			    $response=$ua->request($request,$transname);
                   1761: 			}
                   1762: 			if ($response->is_error()) {
                   1763: 			    unlink($transname);
                   1764: 			    my $message=$response->status_line;
                   1765: 			    &logthis(
                   1766: 				     "LWP GET: $message for $fname ($remoteurl)");
                   1767: 			} else {
                   1768: 			    if ($remoteurl!~/\.meta$/) {
                   1769: 				my $ua=new LWP::UserAgent;
                   1770: 				my $mrequest=
                   1771: 				    new HTTP::Request('GET',$remoteurl.'.meta');
                   1772: 				my $mresponse=
                   1773: 				    $ua->request($mrequest,$fname.'.meta');
                   1774: 				if ($mresponse->is_error()) {
                   1775: 				    unlink($fname.'.meta');
                   1776: 				}
                   1777: 			    }
                   1778: 			    rename($transname,$fname);
                   1779: 			}
                   1780: 		    }
                   1781: 		    print $client "ok\n";
                   1782: 		} else {
                   1783: 		    print $client "not_found\n";
                   1784: 		}
                   1785: 	    } else {
                   1786: 		print $client "rejected\n";
                   1787: 	    }
                   1788: 	} else {
                   1789: 	    Reply($client, "refused\n", $userinput);
                   1790: 	    
                   1791: 	}
                   1792: # -------------------------------------- fetch a user file from a remote server
                   1793:     } elsif ($userinput =~ /^fetchuserfile/) { # Client clear or enc.
                   1794: 	if(isClient) {
                   1795: 	    my ($cmd,$fname)=split(/:/,$userinput);
                   1796: 	    my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   1797: 	    my $udir=propath($udom,$uname).'/userfiles';
                   1798: 	    unless (-e $udir) { mkdir($udir,0770); }
                   1799: 	    if (-e $udir) {
                   1800: 		$ufile=~s/^[\.\~]+//;
                   1801: 		my $path = $udir;
                   1802: 		if ($ufile =~m|(.+)/([^/]+)$|) {
                   1803: 		    my @parts=split('/',$1);
                   1804: 		    foreach my $part (@parts) {
                   1805: 			$path .= '/'.$part;
                   1806: 			if ((-e $path)!=1) {
                   1807: 			    mkdir($path,0770);
                   1808: 			}
                   1809: 		    }
                   1810: 		}
                   1811: 		my $destname=$udir.'/'.$ufile;
                   1812: 		my $transname=$udir.'/'.$ufile.'.in.transit';
                   1813: 		my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
                   1814: 		my $response;
                   1815: 		{
                   1816: 		    my $ua=new LWP::UserAgent;
                   1817: 		    my $request=new HTTP::Request('GET',"$remoteurl");
                   1818: 		    $response=$ua->request($request,$transname);
                   1819: 		}
                   1820: 		if ($response->is_error()) {
                   1821: 		    unlink($transname);
                   1822: 		    my $message=$response->status_line;
                   1823: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   1824: 		    print $client "failed\n";
                   1825: 		} else {
                   1826: 		    if (!rename($transname,$destname)) {
                   1827: 			&logthis("Unable to move $transname to $destname");
                   1828: 			unlink($transname);
                   1829: 			print $client "failed\n";
                   1830: 		    } else {
                   1831: 			print $client "ok\n";
                   1832: 		    }
                   1833: 		}
                   1834: 	    } else {
                   1835: 		print $client "not_home\n";
                   1836: 	    }
                   1837: 	} else {
                   1838: 	    Reply($client, "refused\n", $userinput);
                   1839: 	}
                   1840: # --------------------------------------------------------- remove a user file 
                   1841:     } elsif ($userinput =~ /^removeuserfile/) { # Client clear or enc.
                   1842: 	if(isClient) {
                   1843: 	    my ($cmd,$fname)=split(/:/,$userinput);
                   1844: 	    my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   1845: 	    &logthis("$udom - $uname - $ufile");
                   1846: 	    if ($ufile =~m|/\.\./|) {
                   1847: 		# any files paths with /../ in them refuse 
                   1848: 		# to deal with
                   1849: 		print $client "refused\n";
                   1850: 	    } else {
                   1851: 		my $udir=propath($udom,$uname);
                   1852: 		if (-e $udir) {
                   1853: 		    my $file=$udir.'/userfiles/'.$ufile;
                   1854: 		    if (-e $file) {
                   1855: 			unlink($file);
                   1856: 			if (-e $file) {
                   1857: 			    print $client "failed\n";
                   1858: 			} else {
                   1859: 			    print $client "ok\n";
                   1860: 			}
                   1861: 		    } else {
                   1862: 			print $client "not_found\n";
                   1863: 		    }
                   1864: 		} else {
                   1865: 		    print $client "not_home\n";
                   1866: 		}
                   1867: 	    }
                   1868: 	} else {
                   1869: 	    Reply($client, "refused\n", $userinput);
                   1870: 	}
                   1871: # ------------------------------------------ authenticate access to a user file
                   1872:     } elsif ($userinput =~ /^tokenauthuserfile/) { # Client only
                   1873: 	if(isClient) {
                   1874: 	    my ($cmd,$fname,$session)=split(/:/,$userinput);
                   1875: 	    chomp($session);
                   1876: 	    my $reply='non_auth';
                   1877: 	    if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
                   1878: 		     $session.'.id')) {
                   1879: 		while (my $line=<ENVIN>) {
                   1880: 		    if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply='ok'; }
                   1881: 			    }
                   1882: 		close(ENVIN);
                   1883: 		print $client $reply."\n";
                   1884: 	    } else {
                   1885: 		print $client "invalid_token\n";
                   1886: 	    }
                   1887: 	} else {
                   1888: 	    Reply($client, "refused\n", $userinput);
                   1889: 	    
                   1890: 	}
                   1891: # ----------------------------------------------------------------- unsubscribe
                   1892:     } elsif ($userinput =~ /^unsub/) {
                   1893: 	if(isClient) {
                   1894: 	    my ($cmd,$fname)=split(/:/,$userinput);
                   1895: 	    if (-e $fname) {
                   1896: 		print $client &unsub($fname,$clientip);
                   1897: 	    } else {
                   1898: 		print $client "not_found\n";
                   1899: 	    }
                   1900: 	} else {
                   1901: 	    Reply($client, "refused\n", $userinput);
                   1902: 	    
                   1903: 	}
                   1904: # ------------------------------------------------------------------- subscribe
                   1905:     } elsif ($userinput =~ /^sub/) {
                   1906: 	if(isClient) {
                   1907: 	    print $client &subscribe($userinput,$clientip);
                   1908: 	} else {
                   1909: 	    Reply($client, "refused\n", $userinput);
                   1910: 	    
                   1911: 	}
                   1912: # ------------------------------------------------------------- current version
                   1913:     } elsif ($userinput =~ /^currentversion/) {
                   1914: 	if(isClient) {
                   1915: 	    my ($cmd,$fname)=split(/:/,$userinput);
                   1916: 	    print $client &currentversion($fname)."\n";
                   1917: 	} else {
                   1918: 	    Reply($client, "refused\n", $userinput);
                   1919: 	    
                   1920: 	}
                   1921: # ------------------------------------------------------------------------- log
                   1922:     } elsif ($userinput =~ /^log/) {
                   1923: 	if(isClient) {
                   1924: 	    my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
                   1925: 	    chomp($what);
                   1926: 	    my $proname=propath($udom,$uname);
                   1927: 	    my $now=time;
                   1928: 	    {
                   1929: 		my $hfh;
                   1930: 		if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   1931: 		    print $hfh "$now:$clientname:$what\n";
                   1932: 		    print $client "ok\n"; 
                   1933: 		} else {
                   1934: 		    print $client "error: ".($!+0)
                   1935: 			." IO::File->new Failed "
                   1936: 			."while attempting log\n";
                   1937: 		}
                   1938: 	    }
                   1939: 	} else {
                   1940: 	    Reply($client, "refused\n", $userinput);
                   1941: 	    
                   1942: 	}
                   1943: # ------------------------------------------------------------------------- put
                   1944:     } elsif ($userinput =~ /^put/) {
                   1945: 	if(isClient) {
                   1946: 	    my ($cmd,$udom,$uname,$namespace,$what)
                   1947: 		=split(/:/,$userinput,5);
                   1948: 	    $namespace=~s/\//\_/g;
                   1949: 	    $namespace=~s/\W//g;
                   1950: 	    if ($namespace ne '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',
                   1957: 			"$proname/$namespace.db",
                   1958: 			&GDBM_WRCREAT(),0640)) {
                   1959: 		    unless ($namespace=~/^nohist\_/) {
                   1960: 			my $hfh;
                   1961: 			if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
                   1962: 		    }
                   1963: 		    
                   1964: 		    foreach my $pair (@pairs) {
                   1965: 			my ($key,$value)=split(/=/,$pair);
                   1966: 			$hash{$key}=$value;
                   1967: 		    }
                   1968: 		    if (untie(%hash)) {
                   1969: 			print $client "ok\n";
                   1970: 		    } else {
                   1971: 			print $client "error: ".($!+0)
                   1972: 			    ." untie(GDBM) failed ".
                   1973: 			    "while attempting put\n";
                   1974: 		    }
                   1975: 		} else {
                   1976: 		    print $client "error: ".($!)
                   1977: 			." tie(GDBM) Failed ".
                   1978: 			"while attempting put\n";
                   1979: 		}
                   1980: 	    } else {
                   1981: 		print $client "refused\n";
                   1982: 	    }
                   1983: 	} else {
                   1984: 	    Reply($client, "refused\n", $userinput);
                   1985: 	    
                   1986: 	}
                   1987: # ------------------------------------------------------------------- inc
                   1988:     } elsif ($userinput =~ /^inc:/) {
                   1989: 	if(isClient) {
                   1990: 	    my ($cmd,$udom,$uname,$namespace,$what)
                   1991: 		=split(/:/,$userinput);
                   1992: 	    $namespace=~s/\//\_/g;
                   1993: 	    $namespace=~s/\W//g;
                   1994: 	    if ($namespace ne 'roles') {
                   1995: 		chomp($what);
                   1996: 		my $proname=propath($udom,$uname);
                   1997: 		my $now=time;
                   1998: 		my @pairs=split(/\&/,$what);
                   1999: 		my %hash;
                   2000: 		if (tie(%hash,'GDBM_File',
                   2001: 			"$proname/$namespace.db",
                   2002: 			&GDBM_WRCREAT(),0640)) {
                   2003: 		    unless ($namespace=~/^nohist\_/) {
                   2004: 			my $hfh;
                   2005: 			if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
                   2006: 		    }
                   2007: 		    foreach my $pair (@pairs) {
                   2008: 			my ($key,$value)=split(/=/,$pair);
                   2009: 			# We could check that we have a number...
                   2010: 			if (! defined($value) || $value eq '') {
                   2011: 			    $value = 1;
                   2012: 			}
                   2013: 			$hash{$key}+=$value;
                   2014: 		    }
                   2015: 		    if (untie(%hash)) {
                   2016: 			print $client "ok\n";
                   2017: 		    } else {
                   2018: 			print $client "error: ".($!+0)
                   2019: 			    ." untie(GDBM) failed ".
                   2020: 			    "while attempting inc\n";
                   2021: 		    }
                   2022: 		} else {
                   2023: 		    print $client "error: ".($!)
                   2024: 			." tie(GDBM) Failed ".
                   2025: 			"while attempting inc\n";
                   2026: 		}
                   2027: 	    } else {
                   2028: 		print $client "refused\n";
                   2029: 	    }
                   2030: 	} else {
                   2031: 	    Reply($client, "refused\n", $userinput);
                   2032: 	    
                   2033: 	}
                   2034: # -------------------------------------------------------------------- rolesput
                   2035:     } elsif ($userinput =~ /^rolesput/) {
                   2036: 	if(isClient) {
                   2037: 	    &Debug("rolesput");
                   2038: 	    if ($wasenc==1) {
                   2039: 		my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
                   2040: 		    =split(/:/,$userinput);
                   2041: 		&Debug("cmd = ".$cmd." exedom= ".$exedom.
                   2042: 		       "user = ".$exeuser." udom=".$udom.
                   2043: 		       "what = ".$what);
                   2044: 		my $namespace='roles';
                   2045: 		chomp($what);
                   2046: 		my $proname=propath($udom,$uname);
                   2047: 		my $now=time;
                   2048: 		my @pairs=split(/\&/,$what);
                   2049: 		my %hash;
                   2050: 		if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
                   2051: 		    {
                   2052: 			my $hfh;
                   2053: 			if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { 
                   2054: 			    print $hfh "P:$now:$exedom:$exeuser:$what\n";
                   2055: 			}
                   2056: 		    }
                   2057: 		    
                   2058: 		    foreach my $pair (@pairs) {
                   2059: 			my ($key,$value)=split(/=/,$pair);
                   2060: 			&ManagePermissions($key, $udom, $uname,
                   2061: 					   &GetAuthType( $udom, 
                   2062: 							 $uname));
                   2063: 			$hash{$key}=$value;
                   2064: 		    }
                   2065: 		    if (untie(%hash)) {
                   2066: 			print $client "ok\n";
                   2067: 		    } else {
                   2068: 			print $client "error: ".($!+0)
                   2069: 			    ." untie(GDBM) Failed ".
                   2070: 			    "while attempting rolesput\n";
                   2071: 		    }
                   2072: 		} else {
                   2073: 		    print $client "error: ".($!+0)
                   2074: 			." tie(GDBM) Failed ".
                   2075: 			"while attempting rolesput\n";
                   2076: 			    }
                   2077: 	    } else {
                   2078: 		print $client "refused\n";
                   2079: 	    }
                   2080: 	} else {
                   2081: 	    Reply($client, "refused\n", $userinput);
                   2082: 	    
                   2083: 	}
                   2084: # -------------------------------------------------------------------- rolesdel
                   2085:     } elsif ($userinput =~ /^rolesdel/) {
                   2086: 	if(isClient) {
                   2087: 	    &Debug("rolesdel");
                   2088: 	    if ($wasenc==1) {
                   2089: 		my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
                   2090: 		    =split(/:/,$userinput);
                   2091: 		&Debug("cmd = ".$cmd." exedom= ".$exedom.
                   2092: 		       "user = ".$exeuser." udom=".$udom.
                   2093: 		       "what = ".$what);
                   2094: 		my $namespace='roles';
                   2095: 		chomp($what);
                   2096: 		my $proname=propath($udom,$uname);
                   2097: 		my $now=time;
                   2098: 		my @rolekeys=split(/\&/,$what);
                   2099: 		my %hash;
                   2100: 		if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
                   2101: 		    {
                   2102: 			my $hfh;
                   2103: 			if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { 
                   2104: 			    print $hfh "D:$now:$exedom:$exeuser:$what\n";
                   2105: 			}
                   2106: 		    }
                   2107: 		    foreach my $key (@rolekeys) {
                   2108: 			delete $hash{$key};
                   2109: 		    }
                   2110: 		    if (untie(%hash)) {
                   2111: 			print $client "ok\n";
                   2112: 		    } else {
                   2113: 			print $client "error: ".($!+0)
                   2114: 			    ." untie(GDBM) Failed ".
                   2115: 			    "while attempting rolesdel\n";
                   2116: 		    }
                   2117: 		} else {
                   2118: 		    print $client "error: ".($!+0)
                   2119: 			." tie(GDBM) Failed ".
                   2120: 			"while attempting rolesdel\n";
                   2121: 		}
                   2122: 	    } else {
                   2123: 		print $client "refused\n";
                   2124: 	    }
                   2125: 	} else {
                   2126: 	    Reply($client, "refused\n", $userinput);
                   2127: 	    
                   2128: 	}
                   2129: # ------------------------------------------------------------------------- get
                   2130:     } elsif ($userinput =~ /^get/) {
                   2131: 	if(isClient) {
                   2132: 	    my ($cmd,$udom,$uname,$namespace,$what)
                   2133: 		=split(/:/,$userinput);
                   2134: 	    $namespace=~s/\//\_/g;
                   2135: 	    $namespace=~s/\W//g;
                   2136: 	    chomp($what);
                   2137: 	    my @queries=split(/\&/,$what);
                   2138: 	    my $proname=propath($udom,$uname);
                   2139: 	    my $qresult='';
                   2140: 	    my %hash;
                   2141: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
                   2142: 		for (my $i=0;$i<=$#queries;$i++) {
                   2143: 		    $qresult.="$hash{$queries[$i]}&";
                   2144: 		}
                   2145: 		if (untie(%hash)) {
                   2146: 		    $qresult=~s/\&$//;
                   2147: 		    print $client "$qresult\n";
                   2148: 		} else {
                   2149: 		    print $client "error: ".($!+0)
                   2150: 			." untie(GDBM) Failed ".
                   2151: 			"while attempting get\n";
                   2152: 		}
                   2153: 	    } else {
                   2154: 		if ($!+0 == 2) {
                   2155: 		    print $client "error:No such file or ".
                   2156: 			"GDBM reported bad block error\n";
                   2157: 		} else {
                   2158: 		    print $client "error: ".($!+0)
                   2159: 			." tie(GDBM) Failed ".
                   2160: 			"while attempting get\n";
                   2161: 		}
                   2162: 	    }
                   2163: 	} else {
                   2164: 	    Reply($client, "refused\n", $userinput);
                   2165: 	    
                   2166: 	}
                   2167: # ------------------------------------------------------------------------ eget
                   2168:     } elsif ($userinput =~ /^eget/) {
                   2169: 	if (isClient) {
                   2170: 	    my ($cmd,$udom,$uname,$namespace,$what)
                   2171: 		=split(/:/,$userinput);
                   2172: 	    $namespace=~s/\//\_/g;
                   2173: 	    $namespace=~s/\W//g;
                   2174: 	    chomp($what);
                   2175: 	    my @queries=split(/\&/,$what);
                   2176: 	    my $proname=propath($udom,$uname);
                   2177: 	    my $qresult='';
                   2178: 	    my %hash;
                   2179: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
                   2180: 		for (my $i=0;$i<=$#queries;$i++) {
                   2181: 		    $qresult.="$hash{$queries[$i]}&";
                   2182: 		}
                   2183: 		if (untie(%hash)) {
                   2184: 		    $qresult=~s/\&$//;
                   2185: 		    if ($cipher) {
                   2186: 			my $cmdlength=length($qresult);
                   2187: 			$qresult.="         ";
                   2188: 			my $encqresult='';
                   2189: 			for 
                   2190: 			    (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   2191: 				$encqresult.=
                   2192: 				    unpack("H16",
                   2193: 					   $cipher->encrypt(substr($qresult,$encidx,8)));
                   2194: 			    }
                   2195: 			print $client "enc:$cmdlength:$encqresult\n";
                   2196: 		    } else {
                   2197: 			print $client "error:no_key\n";
                   2198: 		    }
                   2199: 		} else {
                   2200: 		    print $client "error: ".($!+0)
                   2201: 			." untie(GDBM) Failed ".
                   2202: 			"while attempting eget\n";
                   2203: 		}
                   2204: 	    } else {
                   2205: 		print $client "error: ".($!+0)
                   2206: 		    ." tie(GDBM) Failed ".
                   2207: 		    "while attempting eget\n";
                   2208: 	    }
                   2209: 	} else {
                   2210: 	    Reply($client, "refused\n", $userinput);
                   2211: 	    
                   2212: 	}
                   2213: # ------------------------------------------------------------------------- del
                   2214:     } elsif ($userinput =~ /^del/) {
                   2215: 	if(isClient) {
                   2216: 	    my ($cmd,$udom,$uname,$namespace,$what)
                   2217: 		=split(/:/,$userinput);
                   2218: 	    $namespace=~s/\//\_/g;
                   2219: 	    $namespace=~s/\W//g;
                   2220: 	    chomp($what);
                   2221: 	    my $proname=propath($udom,$uname);
                   2222: 	    my $now=time;
                   2223: 	    my @keys=split(/\&/,$what);
                   2224: 	    my %hash;
                   2225: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
                   2226: 		unless ($namespace=~/^nohist\_/) {
                   2227: 		    my $hfh;
                   2228: 		    if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "D:$now:$what\n"; }
                   2229: 		}
                   2230: 		foreach my $key (@keys) {
                   2231: 		    delete($hash{$key});
                   2232: 		}
                   2233: 		if (untie(%hash)) {
                   2234: 		    print $client "ok\n";
                   2235: 		} else {
                   2236: 		    print $client "error: ".($!+0)
                   2237: 			." untie(GDBM) Failed ".
                   2238: 			"while attempting del\n";
                   2239: 		}
                   2240: 	    } else {
                   2241: 		print $client "error: ".($!+0)
                   2242: 		    ." tie(GDBM) Failed ".
                   2243: 		    "while attempting del\n";
                   2244: 	    }
                   2245: 	} else {
                   2246: 	    Reply($client, "refused\n", $userinput);
                   2247: 	    
                   2248: 	}
                   2249: # ------------------------------------------------------------------------ keys
                   2250:     } elsif ($userinput =~ /^keys/) {
                   2251: 	if(isClient) {
                   2252: 	    my ($cmd,$udom,$uname,$namespace)
                   2253: 		=split(/:/,$userinput);
                   2254: 	    $namespace=~s/\//\_/g;
                   2255: 	    $namespace=~s/\W//g;
                   2256: 	    my $proname=propath($udom,$uname);
                   2257: 	    my $qresult='';
                   2258: 	    my %hash;
                   2259: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
                   2260: 		foreach my $key (keys %hash) {
                   2261: 		    $qresult.="$key&";
                   2262: 		}
                   2263: 		if (untie(%hash)) {
                   2264: 		    $qresult=~s/\&$//;
                   2265: 		    print $client "$qresult\n";
                   2266: 		} else {
                   2267: 		    print $client "error: ".($!+0)
                   2268: 			." untie(GDBM) Failed ".
                   2269: 			"while attempting keys\n";
                   2270: 		}
                   2271: 	    } else {
                   2272: 		print $client "error: ".($!+0)
                   2273: 		    ." tie(GDBM) Failed ".
                   2274: 		    "while attempting keys\n";
                   2275: 	    }
                   2276: 	} else {
                   2277: 	    Reply($client, "refused\n", $userinput);
                   2278: 	    
                   2279: 	}
                   2280: # ----------------------------------------------------------------- dumpcurrent
                   2281:     } elsif ($userinput =~ /^currentdump/) {
                   2282: 	if (isClient) {
                   2283: 	    my ($cmd,$udom,$uname,$namespace)
                   2284: 		=split(/:/,$userinput);
                   2285: 	    $namespace=~s/\//\_/g;
                   2286: 	    $namespace=~s/\W//g;
                   2287: 	    my $qresult='';
                   2288: 	    my $proname=propath($udom,$uname);
                   2289: 	    my %hash;
                   2290: 	    if (tie(%hash,'GDBM_File',
                   2291: 		    "$proname/$namespace.db",
                   2292: 		    &GDBM_READER(),0640)) {
                   2293: 			    # Structure of %data:
                   2294: 		# $data{$symb}->{$parameter}=$value;
                   2295: 		# $data{$symb}->{'v.'.$parameter}=$version;
                   2296: 		# since $parameter will be unescaped, we do not
                   2297: 		# have to worry about silly parameter names...
                   2298: 		my %data = ();
                   2299: 		while (my ($key,$value) = each(%hash)) {
                   2300: 		    my ($v,$symb,$param) = split(/:/,$key);
                   2301: 		    next if ($v eq 'version' || $symb eq 'keys');
                   2302: 		    next if (exists($data{$symb}) && 
                   2303: 			     exists($data{$symb}->{$param}) &&
                   2304: 			     $data{$symb}->{'v.'.$param} > $v);
                   2305: 		    $data{$symb}->{$param}=$value;
                   2306: 		    $data{$symb}->{'v.'.$param}=$v;
                   2307: 		}
                   2308: 		if (untie(%hash)) {
                   2309: 		    while (my ($symb,$param_hash) = each(%data)) {
                   2310: 			while(my ($param,$value) = each (%$param_hash)){
                   2311: 			    next if ($param =~ /^v\./);
                   2312: 			    $qresult.=$symb.':'.$param.'='.$value.'&';
                   2313: 			}
                   2314: 		    }
                   2315: 		    chop($qresult);
                   2316: 		    print $client "$qresult\n";
                   2317: 		} else {
                   2318: 		    print $client "error: ".($!+0)
                   2319: 			." untie(GDBM) Failed ".
                   2320: 			"while attempting currentdump\n";
                   2321: 		}
                   2322: 	    } else {
                   2323: 		print $client "error: ".($!+0)
                   2324: 		    ." tie(GDBM) Failed ".
                   2325: 		    "while attempting currentdump\n";
                   2326: 	    }
                   2327: 	} else {
                   2328: 	    Reply($client, "refused\n", $userinput);
                   2329: 	}
                   2330: # ------------------------------------------------------------------------ dump
                   2331:     } elsif ($userinput =~ /^dump/) {
                   2332: 	if(isClient) {
                   2333: 	    my ($cmd,$udom,$uname,$namespace,$regexp)
                   2334: 		=split(/:/,$userinput);
                   2335: 	    $namespace=~s/\//\_/g;
                   2336: 	    $namespace=~s/\W//g;
                   2337: 	    if (defined($regexp)) {
                   2338: 		$regexp=&unescape($regexp);
                   2339: 	    } else {
                   2340: 		$regexp='.';
                   2341: 	    }
                   2342: 	    my $qresult='';
                   2343: 	    my $proname=propath($udom,$uname);
                   2344: 	    my %hash;
                   2345: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
                   2346: 		while (my ($key,$value) = each(%hash)) {
                   2347: 		    if ($regexp eq '.') {
                   2348: 			$qresult.=$key.'='.$value.'&';
                   2349: 		    } else {
                   2350: 			my $unescapeKey = &unescape($key);
                   2351: 			if (eval('$unescapeKey=~/$regexp/')) {
                   2352: 			    $qresult.="$key=$value&";
                   2353: 			}
                   2354: 		    }
                   2355: 		}
                   2356: 		if (untie(%hash)) {
                   2357: 		    chop($qresult);
                   2358: 		    print $client "$qresult\n";
                   2359: 		} else {
                   2360: 		    print $client "error: ".($!+0)
                   2361: 			." untie(GDBM) Failed ".
                   2362: 			"while attempting dump\n";
                   2363: 		}
                   2364: 	    } else {
                   2365: 		print $client "error: ".($!+0)
                   2366: 		    ." tie(GDBM) Failed ".
                   2367: 		    "while attempting dump\n";
                   2368: 	    }
                   2369: 	} else {
                   2370: 	    Reply($client, "refused\n", $userinput);
                   2371: 	    
                   2372: 	}
                   2373: # ----------------------------------------------------------------------- store
                   2374:     } elsif ($userinput =~ /^store/) {
                   2375: 	if(isClient) {
                   2376: 	    my ($cmd,$udom,$uname,$namespace,$rid,$what)
                   2377: 		=split(/:/,$userinput);
                   2378: 	    $namespace=~s/\//\_/g;
                   2379: 	    $namespace=~s/\W//g;
                   2380: 	    if ($namespace ne 'roles') {
                   2381: 		chomp($what);
                   2382: 		my $proname=propath($udom,$uname);
                   2383: 		my $now=time;
                   2384: 		my @pairs=split(/\&/,$what);
                   2385: 		my %hash;
                   2386: 		if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
                   2387: 		    unless ($namespace=~/^nohist\_/) {
                   2388: 			my $hfh;
                   2389: 			if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
                   2390: 			    print $hfh "P:$now:$rid:$what\n";
                   2391: 			}
                   2392: 		    }
                   2393: 		    my @previouskeys=split(/&/,$hash{"keys:$rid"});
                   2394: 		    my $key;
                   2395: 		    $hash{"version:$rid"}++;
                   2396: 		    my $version=$hash{"version:$rid"};
                   2397: 		    my $allkeys=''; 
                   2398: 		    foreach my $pair (@pairs) {
                   2399: 			my ($key,$value)=split(/=/,$pair);
                   2400: 			$allkeys.=$key.':';
                   2401: 			$hash{"$version:$rid:$key"}=$value;
                   2402: 		    }
                   2403: 		    $hash{"$version:$rid:timestamp"}=$now;
                   2404: 		    $allkeys.='timestamp';
                   2405: 		    $hash{"$version:keys:$rid"}=$allkeys;
                   2406: 		    if (untie(%hash)) {
                   2407: 			print $client "ok\n";
                   2408: 		    } else {
                   2409: 			print $client "error: ".($!+0)
                   2410: 			    ." untie(GDBM) Failed ".
                   2411: 			    "while attempting store\n";
                   2412: 				}
                   2413: 		} else {
                   2414: 		    print $client "error: ".($!+0)
                   2415: 			." tie(GDBM) Failed ".
                   2416: 			"while attempting store\n";
                   2417: 		}
                   2418: 	    } else {
                   2419: 		print $client "refused\n";
                   2420: 	    }
                   2421: 	} else {
                   2422: 	    Reply($client, "refused\n", $userinput);
                   2423: 	    
                   2424: 	}
                   2425: # --------------------------------------------------------------------- restore
                   2426:     } elsif ($userinput =~ /^restore/) {
                   2427: 	if(isClient) {
                   2428: 	    my ($cmd,$udom,$uname,$namespace,$rid)
                   2429: 		=split(/:/,$userinput);
                   2430: 	    $namespace=~s/\//\_/g;
                   2431: 	    $namespace=~s/\W//g;
                   2432: 	    chomp($rid);
                   2433: 	    my $proname=propath($udom,$uname);
                   2434: 	    my $qresult='';
                   2435: 	    my %hash;
                   2436: 	    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
                   2437: 		my $version=$hash{"version:$rid"};
                   2438: 		$qresult.="version=$version&";
                   2439: 		my $scope;
                   2440: 		for ($scope=1;$scope<=$version;$scope++) {
                   2441: 		    my $vkeys=$hash{"$scope:keys:$rid"};
                   2442: 		    my @keys=split(/:/,$vkeys);
                   2443: 		    my $key;
                   2444: 		    $qresult.="$scope:keys=$vkeys&";
                   2445: 		    foreach $key (@keys) {
                   2446: 			$qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
                   2447: 		    }                                  
                   2448: 		}
                   2449: 		if (untie(%hash)) {
                   2450: 		    $qresult=~s/\&$//;
                   2451: 		    print $client "$qresult\n";
                   2452: 		} else {
                   2453: 		    print $client "error: ".($!+0)
                   2454: 			." untie(GDBM) Failed ".
                   2455: 			"while attempting restore\n";
                   2456: 		}
                   2457: 	    } else {
                   2458: 		print $client "error: ".($!+0)
                   2459: 		    ." tie(GDBM) Failed ".
                   2460: 		    "while attempting restore\n";
                   2461: 	    }
                   2462: 	} else  {
                   2463: 	    Reply($client, "refused\n", $userinput);
                   2464: 	    
                   2465: 	}
                   2466: # -------------------------------------------------------------------- chatsend
                   2467:     } elsif ($userinput =~ /^chatsend/) {
                   2468: 	if(isClient) {
                   2469: 	    my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
                   2470: 	    &chatadd($cdom,$cnum,$newpost);
                   2471: 	    print $client "ok\n";
                   2472: 	} else {
                   2473: 	    Reply($client, "refused\n", $userinput);
                   2474: 	    
                   2475: 	}
                   2476: # -------------------------------------------------------------------- chatretr
                   2477:     } elsif ($userinput =~ /^chatretr/) {
                   2478: 	if(isClient) {
                   2479: 	    my 
                   2480: 		($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
                   2481: 	    my $reply='';
                   2482: 	    foreach (&getchat($cdom,$cnum,$udom,$uname)) {
                   2483: 		$reply.=&escape($_).':';
                   2484: 	    }
                   2485: 	    $reply=~s/\:$//;
                   2486: 	    print $client $reply."\n";
                   2487: 	} else {
                   2488: 	    Reply($client, "refused\n", $userinput);
                   2489: 	    
                   2490: 	}
                   2491: # ------------------------------------------------------------------- querysend
                   2492:     } elsif ($userinput =~ /^querysend/) {
                   2493: 	if (isClient) {
                   2494: 	    my ($cmd,$query,
                   2495: 		$arg1,$arg2,$arg3)=split(/\:/,$userinput);
                   2496: 	    $query=~s/\n*$//g;
                   2497: 	    print $client "".
                   2498: 		sqlreply("$clientname\&$query".
                   2499: 			 "\&$arg1"."\&$arg2"."\&$arg3")."\n";
                   2500: 	} else {
                   2501: 	    Reply($client, "refused\n", $userinput);
                   2502: 	    
                   2503: 	}
                   2504: # ------------------------------------------------------------------ queryreply
                   2505:     } elsif ($userinput =~ /^queryreply/) {
                   2506: 	if(isClient) {
                   2507: 	    my ($cmd,$id,$reply)=split(/:/,$userinput); 
                   2508: 	    my $store;
                   2509: 	    my $execdir=$perlvar{'lonDaemons'};
                   2510: 	    if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   2511: 		$reply=~s/\&/\n/g;
                   2512: 		print $store $reply;
                   2513: 		close $store;
                   2514: 		my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   2515: 		print $store2 "done\n";
                   2516: 		close $store2;
                   2517: 		print $client "ok\n";
                   2518: 	    }
                   2519: 	    else {
                   2520: 		print $client "error: ".($!+0)
                   2521: 		    ." IO::File->new Failed ".
                   2522: 		    "while attempting queryreply\n";
                   2523: 	    }
                   2524: 	} else {
                   2525: 	    Reply($client, "refused\n", $userinput);
                   2526: 	    
                   2527: 	}
                   2528: # ----------------------------------------------------------------- courseidput
                   2529:     } elsif ($userinput =~ /^courseidput/) {
                   2530: 	if(isClient) {
                   2531: 	    my ($cmd,$udom,$what)=split(/:/,$userinput);
                   2532: 	    chomp($what);
                   2533: 			$udom=~s/\W//g;
                   2534: 	    my $proname=
                   2535: 		"$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
                   2536: 	    my $now=time;
                   2537: 	    my @pairs=split(/\&/,$what);
                   2538: 	    my %hash;
                   2539: 	    if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
                   2540: 		foreach my $pair (@pairs) {
                   2541: 		    my ($key,$descr,$inst_code)=split(/=/,$pair);
                   2542: 		    $hash{$key}=$descr.':'.$inst_code.':'.$now;
                   2543: 		}
                   2544: 		if (untie(%hash)) {
                   2545: 		    print $client "ok\n";
                   2546: 		} else {
                   2547: 		    print $client "error: ".($!+0)
                   2548: 			." untie(GDBM) Failed ".
                   2549: 			"while attempting courseidput\n";
                   2550: 		}
                   2551: 	    } else {
                   2552: 		print $client "error: ".($!+0)
                   2553: 		    ." tie(GDBM) Failed ".
                   2554: 		    "while attempting courseidput\n";
                   2555: 	    }
                   2556: 	} else {
                   2557: 	    Reply($client, "refused\n", $userinput);
                   2558: 	    
                   2559: 	}
                   2560: # ---------------------------------------------------------------- courseiddump
                   2561:     } elsif ($userinput =~ /^courseiddump/) {
                   2562: 	if(isClient) {
                   2563: 	    my ($cmd,$udom,$since,$description)
                   2564: 		=split(/:/,$userinput);
                   2565: 	    if (defined($description)) {
                   2566: 		$description=&unescape($description);
                   2567: 	    } else {
                   2568: 		$description='.';
                   2569: 	    }
                   2570: 	    unless (defined($since)) { $since=0; }
                   2571: 	    my $qresult='';
                   2572: 	    my $proname=
                   2573: 		"$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
                   2574: 	    my %hash;
                   2575: 	    if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
                   2576: 		while (my ($key,$value) = each(%hash)) {
                   2577: 		    my ($descr,$lasttime,$inst_code);
                   2578: 		    if ($value =~ m/^([^\:]*):([^\:]*):(\d+)$/) {
                   2579: 			($descr,$inst_code,$lasttime)=($1,$2,$3);
                   2580: 		    } else {
                   2581: 			($descr,$lasttime) = split(/\:/,$value);
                   2582: 		    }
                   2583: 		    if ($lasttime<$since) { next; }
                   2584: 		    if ($description eq '.') {
                   2585: 			$qresult.=$key.'='.$descr.':'.$inst_code.'&';
                   2586: 		    } else {
                   2587: 			my $unescapeVal = &unescape($descr);
                   2588: 			if (eval('$unescapeVal=~/\Q$description\E/i')) {
                   2589: 			    $qresult.=$key.'='.$descr.':'.$inst_code.'&';
                   2590: 			}
                   2591: 		    }
                   2592: 		}
                   2593: 		if (untie(%hash)) {
                   2594: 		    chop($qresult);
                   2595: 		    print $client "$qresult\n";
                   2596: 		} else {
                   2597: 		    print $client "error: ".($!+0)
                   2598: 			." untie(GDBM) Failed ".
                   2599: 			"while attempting courseiddump\n";
                   2600: 		}
                   2601: 	    } else {
                   2602: 		print $client "error: ".($!+0)
                   2603: 		    ." tie(GDBM) Failed ".
                   2604: 		    "while attempting courseiddump\n";
                   2605: 	    }
                   2606: 	} else {
                   2607: 	    Reply($client, "refused\n", $userinput);
                   2608: 	    
                   2609: 	}
                   2610: # ----------------------------------------------------------------------- idput
                   2611:     } elsif ($userinput =~ /^idput/) {
                   2612: 	if(isClient) {
                   2613: 	    my ($cmd,$udom,$what)=split(/:/,$userinput);
                   2614: 	    chomp($what);
                   2615: 	    $udom=~s/\W//g;
                   2616: 	    my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
                   2617: 	    my $now=time;
                   2618: 	    my @pairs=split(/\&/,$what);
                   2619: 	    my %hash;
                   2620: 	    if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
                   2621: 		{
                   2622: 		    my $hfh;
                   2623: 		    if ($hfh=IO::File->new(">>$proname.hist")) {
                   2624: 			print $hfh "P:$now:$what\n";
                   2625: 		    }
                   2626: 		}
                   2627: 		foreach my $pair (@pairs) {
                   2628: 		    my ($key,$value)=split(/=/,$pair);
                   2629: 		    $hash{$key}=$value;
                   2630: 		}
                   2631: 		if (untie(%hash)) {
                   2632: 		    print $client "ok\n";
                   2633: 		} else {
                   2634: 		    print $client "error: ".($!+0)
                   2635: 			." untie(GDBM) Failed ".
                   2636: 			"while attempting idput\n";
                   2637: 		}
                   2638: 	    } else {
                   2639: 		print $client "error: ".($!+0)
                   2640: 		    ." tie(GDBM) Failed ".
                   2641: 		    "while attempting idput\n";
                   2642: 	    }
                   2643: 	} else {
                   2644: 	    Reply($client, "refused\n", $userinput);
                   2645: 	    
                   2646: 	}
                   2647: # ----------------------------------------------------------------------- idget
                   2648:     } elsif ($userinput =~ /^idget/) {
                   2649: 	if(isClient) {
                   2650: 	    my ($cmd,$udom,$what)=split(/:/,$userinput);
                   2651: 	    chomp($what);
                   2652: 	    $udom=~s/\W//g;
                   2653: 	    my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
                   2654: 	    my @queries=split(/\&/,$what);
                   2655: 	    my $qresult='';
                   2656: 	    my %hash;
                   2657: 	    if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
                   2658: 		for (my $i=0;$i<=$#queries;$i++) {
                   2659: 		    $qresult.="$hash{$queries[$i]}&";
                   2660: 		}
                   2661: 		if (untie(%hash)) {
                   2662: 		    $qresult=~s/\&$//;
                   2663: 		    print $client "$qresult\n";
                   2664: 		} else {
                   2665: 		    print $client "error: ".($!+0)
                   2666: 			." untie(GDBM) Failed ".
                   2667: 			"while attempting idget\n";
                   2668: 		}
                   2669: 	    } else {
                   2670: 		print $client "error: ".($!+0)
                   2671: 		    ." tie(GDBM) Failed ".
                   2672: 		    "while attempting idget\n";
                   2673: 	    }
                   2674: 	} else {
                   2675: 	    Reply($client, "refused\n", $userinput);
                   2676: 	    
                   2677: 	}
                   2678: # ---------------------------------------------------------------------- tmpput
                   2679:     } elsif ($userinput =~ /^tmpput/) {
                   2680: 	if(isClient) {
                   2681: 	    my ($cmd,$what)=split(/:/,$userinput);
                   2682: 	    my $store;
                   2683: 	    $tmpsnum++;
                   2684: 	    my $id=$$.'_'.$clientip.'_'.$tmpsnum;
                   2685: 	    $id=~s/\W/\_/g;
                   2686: 	    $what=~s/\n//g;
                   2687: 	    my $execdir=$perlvar{'lonDaemons'};
                   2688: 	    if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
                   2689: 		print $store $what;
                   2690: 		close $store;
                   2691: 		print $client "$id\n";
                   2692: 	    }
                   2693: 	    else {
                   2694: 		print $client "error: ".($!+0)
                   2695: 		    ."IO::File->new Failed ".
                   2696: 		    "while attempting tmpput\n";
                   2697: 	    }
                   2698: 	} else {
                   2699: 	    Reply($client, "refused\n", $userinput);
                   2700: 	    
                   2701: 	}
                   2702: 	
                   2703: # ---------------------------------------------------------------------- tmpget
                   2704:     } elsif ($userinput =~ /^tmpget/) {
                   2705: 	if(isClient) {
                   2706: 	    my ($cmd,$id)=split(/:/,$userinput);
                   2707: 	    chomp($id);
                   2708: 	    $id=~s/\W/\_/g;
                   2709: 	    my $store;
                   2710: 	    my $execdir=$perlvar{'lonDaemons'};
                   2711: 	    if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   2712: 		my $reply=<$store>;
                   2713: 			    print $client "$reply\n";
                   2714: 		close $store;
                   2715: 	    }
                   2716: 	    else {
                   2717: 		print $client "error: ".($!+0)
                   2718: 		    ."IO::File->new Failed ".
                   2719: 		    "while attempting tmpget\n";
                   2720: 	    }
                   2721: 	} else {
                   2722: 	    Reply($client, "refused\n", $userinput);
                   2723: 	    
                   2724: 	}
                   2725: # ---------------------------------------------------------------------- tmpdel
                   2726:     } elsif ($userinput =~ /^tmpdel/) {
                   2727: 	if(isClient) {
                   2728: 	    my ($cmd,$id)=split(/:/,$userinput);
                   2729: 	    chomp($id);
                   2730: 	    $id=~s/\W/\_/g;
                   2731: 	    my $execdir=$perlvar{'lonDaemons'};
                   2732: 	    if (unlink("$execdir/tmp/$id.tmp")) {
                   2733: 		print $client "ok\n";
                   2734: 	    } else {
                   2735: 		print $client "error: ".($!+0)
                   2736: 		    ."Unlink tmp Failed ".
                   2737: 		    "while attempting tmpdel\n";
                   2738: 	    }
                   2739: 	} else {
                   2740: 	    Reply($client, "refused\n", $userinput);
                   2741: 	    
                   2742: 	}
                   2743: # ----------------------------------------- portfolio directory list (portls)
                   2744:     } elsif ($userinput =~ /^portls/) {
                   2745: 	if(isClient) {
                   2746: 	    my ($cmd,$uname,$udom)=split(/:/,$userinput);
                   2747: 	    my $udir=propath($udom,$uname).'/userfiles/portfolio';
                   2748: 	    my $dirLine='';
                   2749: 	    my $dirContents='';
                   2750: 	    if (opendir(LSDIR,$udir.'/')){
                   2751: 		while ($dirLine = readdir(LSDIR)){
                   2752: 		    $dirContents = $dirContents.$dirLine.'<br />';
                   2753: 		}
                   2754: 	    } else {
                   2755: 		$dirContents = "No directory found\n";
                   2756: 	    }
                   2757: 	    print $client $dirContents."\n";
                   2758: 	} else {
                   2759: 	    Reply($client, "refused\n", $userinput);
                   2760: 	}
                   2761: # -------------------------------------------------------------------------- ls
                   2762:     } elsif ($userinput =~ /^ls/) {
                   2763: 	if(isClient) {
                   2764: 	    my $obs;
                   2765: 	    my $rights;
                   2766: 	    my ($cmd,$ulsdir)=split(/:/,$userinput);
                   2767: 	    my $ulsout='';
                   2768: 	    my $ulsfn;
                   2769: 	    if (-e $ulsdir) {
                   2770: 		if(-d $ulsdir) {
                   2771: 		    if (opendir(LSDIR,$ulsdir)) {
                   2772: 			while ($ulsfn=readdir(LSDIR)) {
                   2773: 			    undef $obs, $rights; 
                   2774: 			    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   2775: 			    #We do some obsolete checking here
                   2776: 			    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   2777: 				open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   2778: 				my @obsolete=<FILE>;
                   2779: 				foreach my $obsolete (@obsolete) {
                   2780: 				    if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; } 
                   2781: 				    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   2782: 				}
                   2783: 			    }
                   2784: 			    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   2785: 			    if($obs eq '1') { $ulsout.="&1"; }
                   2786: 			    else { $ulsout.="&0"; }
                   2787: 			    if($rights eq '1') { $ulsout.="&1:"; }
                   2788: 			    else { $ulsout.="&0:"; }
                   2789: 			}
                   2790: 			closedir(LSDIR);
                   2791: 		    }
                   2792: 		} else {
                   2793: 		    my @ulsstats=stat($ulsdir);
                   2794: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   2795: 		}
                   2796: 	    } else {
                   2797: 		$ulsout='no_such_dir';
                   2798: 	    }
                   2799: 	    if ($ulsout eq '') { $ulsout='empty'; }
                   2800: 	    print $client "$ulsout\n";
                   2801: 	} else {
                   2802: 	    Reply($client, "refused\n", $userinput);
                   2803: 	    
                   2804: 	}
                   2805: # ----------------------------------------------------------------- setannounce
                   2806:     } elsif ($userinput =~ /^setannounce/) {
                   2807: 	if (isClient) {
                   2808: 	    my ($cmd,$announcement)=split(/:/,$userinput);
                   2809: 	    chomp($announcement);
                   2810: 	    $announcement=&unescape($announcement);
                   2811: 	    if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   2812: 					'/announcement.txt')) {
                   2813: 		print $store $announcement;
                   2814: 		close $store;
                   2815: 		print $client "ok\n";
                   2816: 	    } else {
                   2817: 		print $client "error: ".($!+0)."\n";
                   2818: 	    }
                   2819: 	} else {
                   2820: 	    Reply($client, "refused\n", $userinput);
                   2821: 	    
                   2822: 	}
                   2823: # ------------------------------------------------------------------ Hanging up
                   2824:     } elsif (($userinput =~ /^exit/) ||
                   2825: 	     ($userinput =~ /^init/)) { # no restrictions.
                   2826: 	&logthis(
                   2827: 		 "Client $clientip ($clientname) hanging up: $userinput");
                   2828: 	print $client "bye\n";
                   2829: 	$client->shutdown(2);        # shutdown the socket forcibly.
                   2830: 	$client->close();
                   2831: 	return 0;
                   2832: 	
                   2833: # ---------------------------------- set current host/domain
                   2834:     } elsif ($userinput =~ /^sethost:/) {
                   2835: 	if (isClient) {
                   2836: 	    print $client &sethost($userinput)."\n";
                   2837: 	} else {
                   2838: 	    print $client "refused\n";
                   2839: 	}
                   2840: #---------------------------------- request file (?) version.
                   2841:     } elsif ($userinput =~/^version:/) {
                   2842: 	if (isClient) {
                   2843: 	    print $client &version($userinput)."\n";
                   2844: 	} else {
                   2845: 	    print $client "refused\n";
                   2846: 	}
                   2847: #------------------------------- is auto-enrollment enabled?
                   2848:     } elsif ($userinput =~/^autorun:/) {
                   2849: 	if (isClient) {
                   2850: 	    my ($cmd,$cdom) = split(/:/,$userinput);
                   2851: 	    my $outcome = &localenroll::run($cdom);
                   2852: 	    print $client "$outcome\n";
                   2853: 	} else {
                   2854: 	    print $client "0\n";
                   2855: 	}
                   2856: #------------------------------- get official sections (for auto-enrollment).
                   2857:     } elsif ($userinput =~/^autogetsections:/) {
                   2858: 	if (isClient) {
                   2859: 	    my ($cmd,$coursecode,$cdom)=split(/:/,$userinput);
                   2860: 	    my @secs = &localenroll::get_sections($coursecode,$cdom);
                   2861: 	    my $seclist = &escape(join(':',@secs));
                   2862: 	    print $client "$seclist\n";
                   2863: 	} else {
                   2864: 	    print $client "refused\n";
                   2865: 	}
                   2866: #----------------------- validate owner of new course section (for auto-enrollment).
                   2867:     } elsif ($userinput =~/^autonewcourse:/) {
                   2868: 	if (isClient) {
                   2869: 	    my ($cmd,$inst_course_id,$owner,$cdom)=split(/:/,$userinput);
                   2870: 	    my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
                   2871: 	    print $client "$outcome\n";
                   2872: 	} else {
                   2873: 	    print $client "refused\n";
                   2874: 	}
                   2875: #-------------- validate course section in schedule of classes (for auto-enrollment).
                   2876:     } elsif ($userinput =~/^autovalidatecourse:/) {
                   2877: 	if (isClient) {
                   2878: 	    my ($cmd,$inst_course_id,$cdom)=split(/:/,$userinput);
                   2879: 	    my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
                   2880: 	    print $client "$outcome\n";
                   2881: 	} else {
                   2882: 	    print $client "refused\n";
                   2883: 	}
                   2884: #--------------------------- create password for new user (for auto-enrollment).
                   2885:     } elsif ($userinput =~/^autocreatepassword:/) {
                   2886: 	if (isClient) {
                   2887: 	    my ($cmd,$authparam,$cdom)=split(/:/,$userinput);
                   2888: 	    my ($create_passwd,$authchk);
                   2889: 	    ($authparam,$create_passwd,$authchk) = &localenroll::create_password($authparam,$cdom);
                   2890: 	    print $client &escape($authparam.':'.$create_passwd.':'.$authchk)."\n";
                   2891: 	} else {
                   2892: 	    print $client "refused\n";
                   2893: 	}
                   2894: #---------------------------  read and remove temporary files (for auto-enrollment).
                   2895:     } elsif ($userinput =~/^autoretrieve:/) {
                   2896: 	if (isClient) {
                   2897: 	    my ($cmd,$filename) = split(/:/,$userinput);
                   2898: 	    my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
                   2899: 	    if ( (-e $source) && ($filename ne '') ) {
                   2900: 		my $reply = '';
                   2901: 		if (open(my $fh,$source)) {
                   2902: 		    while (<$fh>) {
                   2903: 			chomp($_);
                   2904: 			$_ =~ s/^\s+//g;
                   2905: 			$_ =~ s/\s+$//g;
                   2906: 			$reply .= $_;
                   2907: 		    }
                   2908: 		    close($fh);
                   2909: 		    print $client &escape($reply)."\n";
                   2910: #                                unlink($source);
                   2911: 		} else {
                   2912: 		    print $client "error\n";
                   2913: 		}
                   2914: 	    } else {
                   2915: 		print $client "error\n";
                   2916: 	    }
                   2917: 	} else {
                   2918: 	    print $client "refused\n";
                   2919: 	}
                   2920: #---------------------  read and retrieve institutional code format (for support form).
                   2921:     } elsif ($userinput =~/^autoinstcodeformat:/) {
                   2922: 	if (isClient) {
                   2923: 	    my $reply;
                   2924: 	    my($cmd,$cdom,$course) = split(/:/,$userinput);
                   2925: 	    my @pairs = split/\&/,$course;
                   2926: 	    my %instcodes = ();
                   2927: 	    my %codes = ();
                   2928: 	    my @codetitles = ();
                   2929: 	    my %cat_titles = ();
                   2930: 	    my %cat_order = ();
                   2931: 	    foreach (@pairs) {
                   2932: 		my ($key,$value) = split/=/,$_;
                   2933: 		$instcodes{&unescape($key)} = &unescape($value);
                   2934: 	    }
                   2935: 	    my $formatreply = &localenroll::instcode_format($cdom,\%instcodes,\%codes,\@codetitles,\%cat_titles,\%cat_order);
                   2936: 	    if ($formatreply eq 'ok') {
                   2937: 		my $codes_str = &hash2str(%codes);
                   2938: 		my $codetitles_str = &array2str(@codetitles);
                   2939: 		my $cat_titles_str = &hash2str(%cat_titles);
                   2940: 		my $cat_order_str = &hash2str(%cat_order);
                   2941: 		print $client $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'.$cat_order_str."\n";
                   2942: 	    }
                   2943: 	} else {
                   2944: 	    print $client "refused\n";
                   2945: 	}
                   2946: # ------------------------------------------------------------- unknown command
                   2947: 	
                   2948:     } else {
                   2949: 	# unknown command
                   2950: 	print $client "unknown_cmd\n";
                   2951:     }
                   2952: # -------------------------------------------------------------------- complete
                   2953:     Debug("process_request - returning 1");
                   2954:     return 1;
                   2955: }
1.207     foxr     2956: #
                   2957: #   Decipher encoded traffic
                   2958: #  Parameters:
                   2959: #     input      - Encoded data.
                   2960: #  Returns:
                   2961: #     Decoded data or undef if encryption key was not yet negotiated.
                   2962: #  Implicit input:
                   2963: #     cipher  - This global holds the negotiated encryption key.
                   2964: #
1.211     albertel 2965: sub decipher {
1.207     foxr     2966:     my ($input)  = @_;
                   2967:     my $output = '';
1.212     foxr     2968:     
                   2969:     
1.207     foxr     2970:     if($cipher) {
                   2971: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   2972: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   2973: 	    $output .= 
                   2974: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   2975: 	}
                   2976: 	return substr($output, 0, $enclength);
                   2977:     } else {
                   2978: 	return undef;
                   2979:     }
                   2980: }
                   2981: 
                   2982: #
                   2983: #   Register a command processor.  This function is invoked to register a sub
                   2984: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   2985: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   2986: #   as well:
                   2987: #    - Is the keyword recognized.
                   2988: #    - Is the proper client type attempting the request.
                   2989: #    - Is the request encrypted if it has to be.
                   2990: #   Parameters:
                   2991: #    $request_name         - Name of the request being registered.
                   2992: #                           This is the command request that will match
                   2993: #                           against the hash keywords to lookup the information
                   2994: #                           associated with the dispatch information.
                   2995: #    $procedure           - Reference to a sub to call to process the request.
                   2996: #                           All subs get called as follows:
                   2997: #                             Procedure($cmd, $tail, $replyfd, $key)
                   2998: #                             $cmd    - the actual keyword that invoked us.
                   2999: #                             $tail   - the tail of the request that invoked us.
                   3000: #                             $replyfd- File descriptor connected to the client
                   3001: #    $must_encode          - True if the request must be encoded to be good.
                   3002: #    $client_ok            - True if it's ok for a client to request this.
                   3003: #    $manager_ok           - True if it's ok for a manager to request this.
                   3004: # Side effects:
                   3005: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   3006: #      - On failure, the program will die as it's a bad internal bug to try to 
                   3007: #        register a duplicate command handler.
                   3008: #
1.211     albertel 3009: sub register_handler {
1.212     foxr     3010:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     3011: 
                   3012:     #  Don't allow duplication#
                   3013:    
                   3014:     if (defined $Dispatcher{$request_name}) {
                   3015: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   3016:     }
                   3017:     #   Build the client type mask:
                   3018:     
                   3019:     my $client_type_mask = 0;
                   3020:     if($client_ok) {
                   3021: 	$client_type_mask  |= $CLIENT_OK;
                   3022:     }
                   3023:     if($manager_ok) {
                   3024: 	$client_type_mask  |= $MANAGER_OK;
                   3025:     }
                   3026:    
                   3027:     #  Enter the hash:
                   3028:       
                   3029:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   3030:    
                   3031:     $Dispatcher{$request_name} = \@entry;
                   3032:    
                   3033:    
                   3034: }
                   3035: 
                   3036: 
                   3037: #------------------------------------------------------------------
                   3038: 
                   3039: 
                   3040: 
                   3041: 
1.141     foxr     3042: #
1.96      foxr     3043: #  Convert an error return code from lcpasswd to a string value.
                   3044: #
                   3045: sub lcpasswdstrerror {
                   3046:     my $ErrorCode = shift;
1.97      foxr     3047:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     3048: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   3049:     } else {
1.98      foxr     3050: 	return $passwderrors[$ErrorCode];
1.96      foxr     3051:     }
                   3052: }
                   3053: 
1.97      foxr     3054: #
                   3055: # Convert an error return code from lcuseradd to a string value:
                   3056: #
                   3057: sub lcuseraddstrerror {
                   3058:     my $ErrorCode = shift;
                   3059:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
                   3060: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
                   3061:     } else {
1.98      foxr     3062: 	return $adderrors[$ErrorCode];
1.97      foxr     3063:     }
                   3064: }
                   3065: 
1.23      harris41 3066: # grabs exception and records it to log before exiting
                   3067: sub catchexception {
1.27      albertel 3068:     my ($error)=@_;
1.25      www      3069:     $SIG{'QUIT'}='DEFAULT';
                   3070:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 3071:     &status("Catching exception");
1.190     albertel 3072:     &logthis("<font color='red'>CRITICAL: "
1.134     albertel 3073:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27      albertel 3074:      ."a crash with this error msg->[$error]</font>");
1.57      www      3075:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 3076:     if ($client) { print $client "error: $error\n"; }
1.59      www      3077:     $server->close();
1.27      albertel 3078:     die($error);
1.23      harris41 3079: }
                   3080: 
1.63      www      3081: sub timeout {
1.165     albertel 3082:     &status("Handling Timeout");
1.190     albertel 3083:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      3084:     &catchexception('Timeout');
                   3085: }
1.22      harris41 3086: # -------------------------------- Set signal handlers to record abnormal exits
                   3087: 
                   3088: $SIG{'QUIT'}=\&catchexception;
                   3089: $SIG{__DIE__}=\&catchexception;
                   3090: 
1.81      matthew  3091: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 3092: &status("Read loncapa.conf and loncapa_apache.conf");
                   3093: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     3094: %perlvar=%{$perlvarref};
1.80      harris41 3095: undef $perlvarref;
1.19      www      3096: 
1.35      harris41 3097: # ----------------------------- Make sure this process is running from user=www
                   3098: my $wwwid=getpwnam('www');
                   3099: if ($wwwid!=$<) {
1.134     albertel 3100:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   3101:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 3102:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 3103:  mailto $emailto -s '$subj' > /dev/null");
                   3104:    exit 1;
                   3105: }
                   3106: 
1.19      www      3107: # --------------------------------------------- Check if other instance running
                   3108: 
                   3109: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   3110: 
                   3111: if (-e $pidfile) {
                   3112:    my $lfh=IO::File->new("$pidfile");
                   3113:    my $pide=<$lfh>;
                   3114:    chomp($pide);
1.29      harris41 3115:    if (kill 0 => $pide) { die "already running"; }
1.19      www      3116: }
1.1       albertel 3117: 
                   3118: # ------------------------------------------------------------- Read hosts file
                   3119: 
                   3120: 
                   3121: 
                   3122: # establish SERVER socket, bind and listen.
                   3123: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   3124:                                 Type      => SOCK_STREAM,
                   3125:                                 Proto     => 'tcp',
                   3126:                                 Reuse     => 1,
                   3127:                                 Listen    => 10 )
1.29      harris41 3128:   or die "making socket: $@\n";
1.1       albertel 3129: 
                   3130: # --------------------------------------------------------- Do global variables
                   3131: 
                   3132: # global variables
                   3133: 
1.134     albertel 3134: my %children               = ();       # keys are current child process IDs
1.1       albertel 3135: 
                   3136: sub REAPER {                        # takes care of dead children
                   3137:     $SIG{CHLD} = \&REAPER;
1.165     albertel 3138:     &status("Handling child death");
1.178     foxr     3139:     my $pid;
                   3140:     do {
                   3141: 	$pid = waitpid(-1,&WNOHANG());
                   3142: 	if (defined($children{$pid})) {
                   3143: 	    &logthis("Child $pid died");
                   3144: 	    delete($children{$pid});
1.183     albertel 3145: 	} elsif ($pid > 0) {
1.178     foxr     3146: 	    &logthis("Unknown Child $pid died");
                   3147: 	}
                   3148:     } while ( $pid > 0 );
                   3149:     foreach my $child (keys(%children)) {
                   3150: 	$pid = waitpid($child,&WNOHANG());
                   3151: 	if ($pid > 0) {
                   3152: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   3153: 	    delete($children{$pid});
                   3154: 	}
1.176     albertel 3155:     }
1.165     albertel 3156:     &status("Finished Handling child death");
1.1       albertel 3157: }
                   3158: 
                   3159: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 3160:     &status("Killing children (INT)");
1.1       albertel 3161:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   3162:     kill 'INT' => keys %children;
1.59      www      3163:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 3164:     my $execdir=$perlvar{'lonDaemons'};
                   3165:     unlink("$execdir/logs/lond.pid");
1.190     albertel 3166:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 3167:     &status("Done killing children");
1.1       albertel 3168:     exit;                           # clean up with dignity
                   3169: }
                   3170: 
                   3171: sub HUPSMAN {                      # signal handler for SIGHUP
                   3172:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 3173:     &status("Killing children for restart (HUP)");
1.1       albertel 3174:     kill 'INT' => keys %children;
1.59      www      3175:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 3176:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 3177:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 3178:     unlink("$execdir/logs/lond.pid");
1.165     albertel 3179:     &status("Restarting self (HUP)");
1.1       albertel 3180:     exec("$execdir/lond");         # here we go again
                   3181: }
                   3182: 
1.144     foxr     3183: #
1.148     foxr     3184: #    Kill off hashes that describe the host table prior to re-reading it.
                   3185: #    Hashes affected are:
1.200     matthew  3186: #       %hostid, %hostdom %hostip %hostdns.
1.148     foxr     3187: #
                   3188: sub KillHostHashes {
                   3189:     foreach my $key (keys %hostid) {
                   3190: 	delete $hostid{$key};
                   3191:     }
                   3192:     foreach my $key (keys %hostdom) {
                   3193: 	delete $hostdom{$key};
                   3194:     }
                   3195:     foreach my $key (keys %hostip) {
                   3196: 	delete $hostip{$key};
                   3197:     }
1.200     matthew  3198:     foreach my $key (keys %hostdns) {
                   3199: 	delete $hostdns{$key};
                   3200:     }
1.148     foxr     3201: }
                   3202: #
                   3203: #   Read in the host table from file and distribute it into the various hashes:
                   3204: #
                   3205: #    - %hostid  -  Indexed by IP, the loncapa hostname.
                   3206: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
                   3207: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
                   3208: sub ReadHostTable {
                   3209: 
                   3210:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200     matthew  3211:     my $myloncapaname = $perlvar{'lonHostID'};
                   3212:     Debug("My loncapa name is : $myloncapaname");
1.148     foxr     3213:     while (my $configline=<CONFIG>) {
1.178     foxr     3214: 	if (!($configline =~ /^\s*\#/)) {
                   3215: 	    my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                   3216: 	    chomp($ip); $ip=~s/\D+$//;
1.200     matthew  3217: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
                   3218: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
                   3219: 	    $hostip{$id}=$ip;	      # IP address of host.
                   3220: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
                   3221: 
                   3222: 	    if ($id eq $perlvar{'lonHostID'}) { 
                   3223: 		Debug("Found me in the host table: $name");
                   3224: 		$thisserver=$name; 
                   3225: 	    }
1.178     foxr     3226: 	}
1.148     foxr     3227:     }
                   3228:     close(CONFIG);
                   3229: }
                   3230: #
                   3231: #  Reload the Apache daemon's state.
1.150     foxr     3232: #  This is done by invoking /home/httpd/perl/apachereload
                   3233: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     3234: #
                   3235: sub ReloadApache {
1.150     foxr     3236:     my $execdir = $perlvar{'lonDaemons'};
                   3237:     my $script  = $execdir."/apachereload";
                   3238:     system($script);
1.148     foxr     3239: }
                   3240: 
                   3241: #
1.144     foxr     3242: #   Called in response to a USR2 signal.
                   3243: #   - Reread hosts.tab
                   3244: #   - All children connected to hosts that were removed from hosts.tab
                   3245: #     are killed via SIGINT
                   3246: #   - All children connected to previously existing hosts are sent SIGUSR1
                   3247: #   - Our internal hosts hash is updated to reflect the new contents of
                   3248: #     hosts.tab causing connections from hosts added to hosts.tab to
                   3249: #     now be honored.
                   3250: #
                   3251: sub UpdateHosts {
1.165     albertel 3252:     &status("Reload hosts.tab");
1.147     foxr     3253:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     3254:     #
                   3255:     #  The %children hash has the set of IP's we currently have children
                   3256:     #  on.  These need to be matched against records in the hosts.tab
                   3257:     #  Any ip's no longer in the table get killed off they correspond to
                   3258:     #  either dropped or changed hosts.  Note that the re-read of the table
                   3259:     #  will take care of new and changed hosts as connections come into being.
                   3260: 
                   3261: 
                   3262:     KillHostHashes;
                   3263:     ReadHostTable;
                   3264: 
                   3265:     foreach my $child (keys %children) {
                   3266: 	my $childip = $children{$child};
                   3267: 	if(!$hostid{$childip}) {
1.149     foxr     3268: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   3269: 		    ." $child for ip $childip </font>");
1.148     foxr     3270: 	    kill('INT', $child);
1.149     foxr     3271: 	} else {
                   3272: 	    logthis('<font color="green"> keeping child for ip '
                   3273: 		    ." $childip (pid=$child) </font>");
1.148     foxr     3274: 	}
                   3275:     }
                   3276:     ReloadApache;
1.165     albertel 3277:     &status("Finished reloading hosts.tab");
1.144     foxr     3278: }
                   3279: 
1.148     foxr     3280: 
1.57      www      3281: sub checkchildren {
1.165     albertel 3282:     &status("Checking on the children (sending signals)");
1.57      www      3283:     &initnewstatus();
                   3284:     &logstatus();
                   3285:     &logthis('Going to check on the children');
1.134     albertel 3286:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 3287:     foreach (sort keys %children) {
1.57      www      3288: 	sleep 1;
                   3289:         unless (kill 'USR1' => $_) {
                   3290: 	    &logthis ('Child '.$_.' is dead');
                   3291:             &logstatus($$.' is dead');
                   3292:         } 
1.61      harris41 3293:     }
1.63      www      3294:     sleep 5;
1.212     foxr     3295:     $SIG{ALRM} = sub { Debug("timeout"); 
                   3296: 		       die "timeout";  };
1.113     albertel 3297:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 3298:     &status("Checking on the children (waiting for reports)");
1.63      www      3299:     foreach (sort keys %children) {
                   3300:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 3301:           eval {
                   3302:             alarm(300);
1.63      www      3303: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 3304: 	    kill 9 => $_;
1.131     albertel 3305: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   3306: 	    #$subj="LON: $currenthostid killed lond process $_";
                   3307: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   3308: 	    #$execdir=$perlvar{'lonDaemons'};
                   3309: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.113     albertel 3310: 	    alarm(0);
                   3311: 	  }
1.63      www      3312:         }
                   3313:     }
1.113     albertel 3314:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 3315:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 3316:     &status("Finished checking children");
1.57      www      3317: }
                   3318: 
1.1       albertel 3319: # --------------------------------------------------------------------- Logging
                   3320: 
                   3321: sub logthis {
                   3322:     my $message=shift;
                   3323:     my $execdir=$perlvar{'lonDaemons'};
                   3324:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   3325:     my $now=time;
                   3326:     my $local=localtime($now);
1.58      www      3327:     $lastlog=$local.': '.$message;
1.1       albertel 3328:     print $fh "$local ($$): $message\n";
                   3329: }
                   3330: 
1.77      foxr     3331: # ------------------------- Conditional log if $DEBUG true.
                   3332: sub Debug {
                   3333:     my $message = shift;
                   3334:     if($DEBUG) {
                   3335: 	&logthis($message);
                   3336:     }
                   3337: }
1.161     foxr     3338: 
                   3339: #
                   3340: #   Sub to do replies to client.. this gives a hook for some
                   3341: #   debug tracing too:
                   3342: #  Parameters:
                   3343: #     fd      - File open on client.
                   3344: #     reply   - Text to send to client.
                   3345: #     request - Original request from client.
                   3346: #
                   3347: sub Reply {
1.192     foxr     3348:     my ($fd, $reply, $request) = @_;
1.161     foxr     3349:     print $fd $reply;
                   3350:     Debug("Request was $request  Reply was $reply");
                   3351: 
1.212     foxr     3352:     $Transactions++;
                   3353: 
                   3354: 
                   3355: }
                   3356: 
                   3357: 
                   3358: #
                   3359: #    Sub to report a failure.
                   3360: #    This function:
                   3361: #     -   Increments the failure statistic counters.
                   3362: #     -   Invokes Reply to send the error message to the client.
                   3363: # Parameters:
                   3364: #    fd       - File descriptor open on the client
                   3365: #    reply    - Reply text to emit.
                   3366: #    request  - The original request message (used by Reply
                   3367: #               to debug if that's enabled.
                   3368: # Implicit outputs:
                   3369: #    $Failures- The number of failures is incremented.
                   3370: #    Reply (invoked here) sends a message to the 
                   3371: #    client:
                   3372: #
                   3373: sub Failure {
                   3374:     my $fd      = shift;
                   3375:     my $reply   = shift;
                   3376:     my $request = shift;
                   3377:    
                   3378:     $Failures++;
                   3379:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     3380: }
1.57      www      3381: # ------------------------------------------------------------------ Log status
                   3382: 
                   3383: sub logstatus {
1.178     foxr     3384:     &status("Doing logging");
                   3385:     my $docdir=$perlvar{'lonDocRoot'};
                   3386:     {
                   3387:     my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
1.200     matthew  3388:     print $fh $$."\t".$clientname."\t".$currenthostid."\t"
                   3389: 	.$status."\t".$lastlog."\t $keymode\n";
1.178     foxr     3390:     $fh->close();
                   3391:     }
                   3392:     &status("Finished londstatus.txt");
                   3393:     {
                   3394: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  3395:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     3396:         $fh->close();
                   3397:     }
                   3398:     &status("Finished logging");
1.57      www      3399: }
                   3400: 
                   3401: sub initnewstatus {
                   3402:     my $docdir=$perlvar{'lonDocRoot'};
                   3403:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
                   3404:     my $now=time;
                   3405:     my $local=localtime($now);
                   3406:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      3407:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 3408:     while (my $filename=readdir(DIR)) {
1.64      www      3409:         unlink("$docdir/lon-status/londchld/$filename");
                   3410:     }
                   3411:     closedir(DIR);
1.57      www      3412: }
                   3413: 
                   3414: # -------------------------------------------------------------- Status setting
                   3415: 
                   3416: sub status {
                   3417:     my $what=shift;
                   3418:     my $now=time;
                   3419:     my $local=localtime($now);
1.178     foxr     3420:     $status=$local.': '.$what;
                   3421:     $0='lond: '.$what.' '.$local;
1.57      www      3422: }
1.11      www      3423: 
                   3424: # -------------------------------------------------------- Escape Special Chars
                   3425: 
                   3426: sub escape {
                   3427:     my $str=shift;
                   3428:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   3429:     return $str;
                   3430: }
                   3431: 
                   3432: # ----------------------------------------------------- Un-Escape Special Chars
                   3433: 
                   3434: sub unescape {
                   3435:     my $str=shift;
                   3436:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   3437:     return $str;
                   3438: }
                   3439: 
1.1       albertel 3440: # ----------------------------------------------------------- Send USR1 to lonc
                   3441: 
                   3442: sub reconlonc {
                   3443:     my $peerfile=shift;
                   3444:     &logthis("Trying to reconnect for $peerfile");
                   3445:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                   3446:     if (my $fh=IO::File->new("$loncfile")) {
                   3447: 	my $loncpid=<$fh>;
                   3448:         chomp($loncpid);
                   3449:         if (kill 0 => $loncpid) {
                   3450: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                   3451:             kill USR1 => $loncpid;
                   3452:         } else {
1.9       www      3453: 	    &logthis(
1.190     albertel 3454:               "<font color='red'>CRITICAL: "
1.9       www      3455:              ."lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel 3456:         }
                   3457:     } else {
1.190     albertel 3458:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1       albertel 3459:     }
                   3460: }
                   3461: 
                   3462: # -------------------------------------------------- Non-critical communication
1.11      www      3463: 
1.1       albertel 3464: sub subreply {
                   3465:     my ($cmd,$server)=@_;
                   3466:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                   3467:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   3468:                                       Type    => SOCK_STREAM,
                   3469:                                       Timeout => 10)
                   3470:        or return "con_lost";
                   3471:     print $sclient "$cmd\n";
                   3472:     my $answer=<$sclient>;
                   3473:     chomp($answer);
                   3474:     if (!$answer) { $answer="con_lost"; }
                   3475:     return $answer;
                   3476: }
                   3477: 
                   3478: sub reply {
                   3479:   my ($cmd,$server)=@_;
                   3480:   my $answer;
1.115     albertel 3481:   if ($server ne $currenthostid) { 
1.1       albertel 3482:     $answer=subreply($cmd,$server);
                   3483:     if ($answer eq 'con_lost') {
                   3484: 	$answer=subreply("ping",$server);
                   3485:         if ($answer ne $server) {
1.115     albertel 3486: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1       albertel 3487:            &reconlonc("$perlvar{'lonSockDir'}/$server");
                   3488:         }
                   3489:         $answer=subreply($cmd,$server);
                   3490:     }
                   3491:   } else {
                   3492:     $answer='self_reply';
                   3493:   } 
                   3494:   return $answer;
                   3495: }
                   3496: 
1.13      www      3497: # -------------------------------------------------------------- Talk to lonsql
                   3498: 
1.12      harris41 3499: sub sqlreply {
                   3500:     my ($cmd)=@_;
                   3501:     my $answer=subsqlreply($cmd);
                   3502:     if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
                   3503:     return $answer;
                   3504: }
                   3505: 
                   3506: sub subsqlreply {
                   3507:     my ($cmd)=@_;
                   3508:     my $unixsock="mysqlsock";
                   3509:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   3510:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   3511:                                       Type    => SOCK_STREAM,
                   3512:                                       Timeout => 10)
                   3513:        or return "con_lost";
                   3514:     print $sclient "$cmd\n";
                   3515:     my $answer=<$sclient>;
                   3516:     chomp($answer);
                   3517:     if (!$answer) { $answer="con_lost"; }
                   3518:     return $answer;
                   3519: }
                   3520: 
1.1       albertel 3521: # -------------------------------------------- Return path to profile directory
1.11      www      3522: 
1.1       albertel 3523: sub propath {
                   3524:     my ($udom,$uname)=@_;
                   3525:     $udom=~s/\W//g;
                   3526:     $uname=~s/\W//g;
1.16      www      3527:     my $subdir=$uname.'__';
1.1       albertel 3528:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3529:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   3530:     return $proname;
                   3531: } 
                   3532: 
                   3533: # --------------------------------------- Is this the home server of an author?
1.11      www      3534: 
1.1       albertel 3535: sub ishome {
                   3536:     my $author=shift;
                   3537:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3538:     my ($udom,$uname)=split(/\//,$author);
                   3539:     my $proname=propath($udom,$uname);
                   3540:     if (-e $proname) {
                   3541: 	return 'owner';
                   3542:     } else {
                   3543:         return 'not_owner';
                   3544:     }
                   3545: }
                   3546: 
                   3547: # ======================================================= Continue main program
                   3548: # ---------------------------------------------------- Fork once and dissociate
                   3549: 
1.134     albertel 3550: my $fpid=fork;
1.1       albertel 3551: exit if $fpid;
1.29      harris41 3552: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 3553: 
1.29      harris41 3554: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 3555: 
                   3556: # ------------------------------------------------------- Write our PID on disk
                   3557: 
1.134     albertel 3558: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 3559: open (PIDSAVE,">$execdir/logs/lond.pid");
                   3560: print PIDSAVE "$$\n";
                   3561: close(PIDSAVE);
1.190     albertel 3562: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      3563: &status('Starting');
1.1       albertel 3564: 
1.106     foxr     3565: 
1.1       albertel 3566: 
                   3567: # ----------------------------------------------------- Install signal handlers
                   3568: 
1.57      www      3569: 
1.1       albertel 3570: $SIG{CHLD} = \&REAPER;
                   3571: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   3572: $SIG{HUP}  = \&HUPSMAN;
1.57      www      3573: $SIG{USR1} = \&checkchildren;
1.144     foxr     3574: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     3575: 
1.148     foxr     3576: #  Read the host hashes:
                   3577: 
                   3578: ReadHostTable;
1.106     foxr     3579: 
                   3580: # --------------------------------------------------------------
                   3581: #   Accept connections.  When a connection comes in, it is validated
                   3582: #   and if good, a child process is created to process transactions
                   3583: #   along the connection.
                   3584: 
1.1       albertel 3585: while (1) {
1.165     albertel 3586:     &status('Starting accept');
1.106     foxr     3587:     $client = $server->accept() or next;
1.165     albertel 3588:     &status('Accepted '.$client.' off to spawn');
1.106     foxr     3589:     make_new_child($client);
1.165     albertel 3590:     &status('Finished spawning');
1.1       albertel 3591: }
                   3592: 
1.212     foxr     3593: sub make_new_child {
                   3594:     my $pid;
                   3595: #    my $cipher;     # Now global
                   3596:     my $sigset;
1.178     foxr     3597: 
1.212     foxr     3598:     $client = shift;
                   3599:     &status('Starting new child '.$client);
                   3600:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   3601: 	     ")</font>");    
                   3602:     # block signal for fork
                   3603:     $sigset = POSIX::SigSet->new(SIGINT);
                   3604:     sigprocmask(SIG_BLOCK, $sigset)
                   3605:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     3606: 
1.212     foxr     3607:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     3608: 
1.212     foxr     3609:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   3610: 	                               # connection liveness.
1.178     foxr     3611: 
1.212     foxr     3612:     #
                   3613:     #  Figure out who we're talking to so we can record the peer in 
                   3614:     #  the pid hash.
                   3615:     #
                   3616:     my $caller = getpeername($client);
                   3617:     my ($port,$iaddr);
                   3618:     if (defined($caller) && length($caller) > 0) {
                   3619: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   3620:     } else {
                   3621: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   3622:     }
                   3623:     if (defined($iaddr)) {
                   3624: 	$clientip  = inet_ntoa($iaddr);
                   3625: 	Debug("Connected with $clientip");
                   3626: 	$clientdns = gethostbyaddr($iaddr, AF_INET);
                   3627: 	Debug("Connected with $clientdns by name");
                   3628:     } else {
                   3629: 	&logthis("Unable to determine clientip");
                   3630: 	$clientip='Unavailable';
                   3631:     }
                   3632:     
                   3633:     if ($pid) {
                   3634:         # Parent records the child's birth and returns.
                   3635:         sigprocmask(SIG_UNBLOCK, $sigset)
                   3636:             or die "Can't unblock SIGINT for fork: $!\n";
                   3637:         $children{$pid} = $clientip;
                   3638:         &status('Started child '.$pid);
                   3639:         return;
                   3640:     } else {
                   3641:         # Child can *not* return from this subroutine.
                   3642:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   3643:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   3644:                                 #don't get intercepted
                   3645:         $SIG{USR1}= \&logstatus;
                   3646:         $SIG{ALRM}= \&timeout;
                   3647:         $lastlog='Forked ';
                   3648:         $status='Forked';
1.178     foxr     3649: 
1.212     foxr     3650:         # unblock signals
                   3651:         sigprocmask(SIG_UNBLOCK, $sigset)
                   3652:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     3653: 
1.212     foxr     3654: #        my $tmpsnum=0;            # Now global
                   3655: #---------------------------------------------------- kerberos 5 initialization
                   3656:         &Authen::Krb5::init_context();
                   3657:         &Authen::Krb5::init_ets();
1.209     albertel 3658: 
1.212     foxr     3659: 	&status('Accepted connection');
                   3660: # =============================================================================
                   3661:             # do something with the connection
                   3662: # -----------------------------------------------------------------------------
                   3663: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     3664: 
1.212     foxr     3665: 	ReadManagerTable;	# May also be a manager!!
                   3666: 	
                   3667: 	my $clientrec=($hostid{$clientip}     ne undef);
                   3668: 	my $ismanager=($managers{$clientip}    ne undef);
                   3669: 	$clientname  = "[unknonwn]";
                   3670: 	if($clientrec) {	# Establish client type.
                   3671: 	    $ConnectionType = "client";
                   3672: 	    $clientname = $hostid{$clientip};
                   3673: 	    if($ismanager) {
                   3674: 		$ConnectionType = "both";
                   3675: 	    }
                   3676: 	} else {
                   3677: 	    $ConnectionType = "manager";
                   3678: 	    $clientname = $managers{$clientip};
                   3679: 	}
                   3680: 	my $clientok;
1.178     foxr     3681: 
1.212     foxr     3682: 	if ($clientrec || $ismanager) {
                   3683: 	    &status("Waiting for init from $clientip $clientname");
                   3684: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   3685: 		     $clientip.
                   3686: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   3687: 	    &status("Connecting $clientip  ($clientname))"); 
                   3688: 	    my $remotereq=<$client>;
                   3689: 	    chomp($remotereq);
                   3690: 	    Debug("Got init: $remotereq");
                   3691: 	    my $inikeyword = split(/:/, $remotereq);
                   3692: 	    if ($remotereq =~ /^init/) {
                   3693: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   3694: 		#
                   3695: 		#  If the remote is attempting a local init... give that a try:
                   3696: 		#
                   3697: 		my ($i, $inittype) = split(/:/, $remotereq);
1.209     albertel 3698: 
1.212     foxr     3699: 		# If the connection type is ssl, but I didn't get my
                   3700: 		# certificate files yet, then I'll drop  back to 
                   3701: 		# insecure (if allowed).
                   3702: 		
                   3703: 		if($inittype eq "ssl") {
                   3704: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   3705: 		    my $kfile       = lonssl::KeyFile;
                   3706: 		    if((!$ca)   || 
                   3707: 		       (!$cert) || 
                   3708: 		       (!$kfile)) {
                   3709: 			$inittype = ""; # This forces insecure attempt.
                   3710: 			&logthis("<font color=\"blue\"> Certificates not "
                   3711: 				 ."installed -- trying insecure auth</font>");
1.178     foxr     3712: 		    }
1.212     foxr     3713: 		    else {	# SSL certificates are in place so
                   3714: 		    }		# Leave the inittype alone.
                   3715: 		}
                   3716: 
                   3717: 		if($inittype eq "local") {
                   3718: 		    my $key = LocalConnection($client, $remotereq);
                   3719: 		    if($key) {
                   3720: 			Debug("Got local key $key");
                   3721: 			$clientok     = 1;
                   3722: 			my $cipherkey = pack("H32", $key);
                   3723: 			$cipher       = new IDEA($cipherkey);
                   3724: 			print $client "ok:local\n";
                   3725: 			&logthis('<font color="green"'
                   3726: 				 . "Successful local authentication </font>");
                   3727: 			$keymode = "local"
1.178     foxr     3728: 		    } else {
1.212     foxr     3729: 			Debug("Failed to get local key");
                   3730: 			$clientok = 0;
                   3731: 			shutdown($client, 3);
                   3732: 			close $client;
1.178     foxr     3733: 		    }
1.212     foxr     3734: 		} elsif ($inittype eq "ssl") {
                   3735: 		    my $key = SSLConnection($client);
                   3736: 		    if ($key) {
                   3737: 			$clientok = 1;
                   3738: 			my $cipherkey = pack("H32", $key);
                   3739: 			$cipher       = new IDEA($cipherkey);
                   3740: 			&logthis('<font color="green">'
                   3741: 				 ."Successfull ssl authentication with $clientname </font>");
                   3742: 			$keymode = "ssl";
                   3743: 	     
1.178     foxr     3744: 		    } else {
1.212     foxr     3745: 			$clientok = 0;
                   3746: 			close $client;
1.178     foxr     3747: 		    }
1.212     foxr     3748: 	   
                   3749: 		} else {
                   3750: 		    my $ok = InsecureConnection($client);
                   3751: 		    if($ok) {
                   3752: 			$clientok = 1;
                   3753: 			&logthis('<font color="green">'
                   3754: 				 ."Successful insecure authentication with $clientname </font>");
                   3755: 			print $client "ok\n";
                   3756: 			$keymode = "insecure";
1.178     foxr     3757: 		    } else {
1.212     foxr     3758: 			&logthis('<font color="yellow">'
                   3759: 				  ."Attempted insecure connection disallowed </font>");
                   3760: 			close $client;
                   3761: 			$clientok = 0;
1.178     foxr     3762: 			
                   3763: 		    }
                   3764: 		}
1.212     foxr     3765: 	    } else {
                   3766: 		&logthis(
                   3767: 			 "<font color='blue'>WARNING: "
                   3768: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   3769: 		&status('No init '.$clientip);
                   3770: 	    }
                   3771: 	    
                   3772: 	} else {
                   3773: 	    &logthis(
                   3774: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   3775: 	    &status('Hung up on '.$clientip);
                   3776: 	}
                   3777:  
                   3778: 	if ($clientok) {
                   3779: # ---------------- New known client connecting, could mean machine online again
                   3780: 	    
                   3781: 	    foreach my $id (keys(%hostip)) {
                   3782: 		if ($hostip{$id} ne $clientip ||
                   3783: 		    $hostip{$currenthostid} eq $clientip) {
                   3784: 		    # no need to try to do recon's to myself
                   3785: 		    next;
                   3786: 		}
                   3787: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
                   3788: 	    }
                   3789: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   3790: 	    &status('Will listen to '.$clientname);
                   3791: # ------------------------------------------------------------ Process requests
                   3792: 	    my $keep_going = 1;
                   3793: 	    my $user_input;
                   3794: 	    while(($user_input = get_request) && $keep_going) {
                   3795: 		alarm(120);
                   3796: 		Debug("Main: Got $user_input\n");
                   3797: 		$keep_going = &process_request($user_input);
1.178     foxr     3798: 		alarm(0);
1.212     foxr     3799: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     3800: 	    }
1.212     foxr     3801: 
1.59      www      3802: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     3803: 	}  else {
1.161     foxr     3804: 	    print $client "refused\n";
                   3805: 	    $client->close();
1.190     albertel 3806: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     3807: 		     ."Rejected client $clientip, closing connection</font>");
                   3808: 	}
1.212     foxr     3809:     }            
1.161     foxr     3810:     
1.1       albertel 3811: # =============================================================================
1.161     foxr     3812:     
1.190     albertel 3813:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     3814: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   3815:     
                   3816:     
                   3817:     # this exit is VERY important, otherwise the child will become
                   3818:     # a producer of more and more children, forking yourself into
                   3819:     # process death.
                   3820:     exit;
1.106     foxr     3821:     
1.78      foxr     3822: }
                   3823: 
                   3824: 
                   3825: #
                   3826: #   Checks to see if the input roleput request was to set
                   3827: # an author role.  If so, invokes the lchtmldir script to set
                   3828: # up a correct public_html 
                   3829: # Parameters:
                   3830: #    request   - The request sent to the rolesput subchunk.
                   3831: #                We're looking for  /domain/_au
                   3832: #    domain    - The domain in which the user is having roles doctored.
                   3833: #    user      - Name of the user for which the role is being put.
                   3834: #    authtype  - The authentication type associated with the user.
                   3835: #
                   3836: sub ManagePermissions
                   3837: {
1.192     foxr     3838: 
                   3839:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     3840: 
                   3841:     # See if the request is of the form /$domain/_au
                   3842:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
                   3843: 	my $execdir = $perlvar{'lonDaemons'};
                   3844: 	my $userhome= "/home/$user" ;
1.134     albertel 3845: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.78      foxr     3846: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   3847:     }
                   3848: }
                   3849: #
                   3850: #   GetAuthType - Determines the authorization type of a user in a domain.
                   3851: 
                   3852: #     Returns the authorization type or nouser if there is no such user.
                   3853: #
                   3854: sub GetAuthType 
                   3855: {
1.192     foxr     3856: 
                   3857:     my ($domain, $user)  = @_;
1.78      foxr     3858: 
1.79      foxr     3859:     Debug("GetAuthType( $domain, $user ) \n");
1.78      foxr     3860:     my $proname    = &propath($domain, $user); 
                   3861:     my $passwdfile = "$proname/passwd";
                   3862:     if( -e $passwdfile ) {
                   3863: 	my $pf = IO::File->new($passwdfile);
                   3864: 	my $realpassword = <$pf>;
                   3865: 	chomp($realpassword);
1.79      foxr     3866: 	Debug("Password info = $realpassword\n");
1.78      foxr     3867: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     3868: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.78      foxr     3869: 	my $availinfo = '';
1.91      albertel 3870: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
1.78      foxr     3871: 	    $availinfo = $contentpwd;
                   3872: 	}
1.79      foxr     3873: 
1.78      foxr     3874: 	return "$authtype:$availinfo";
                   3875:     }
                   3876:     else {
1.79      foxr     3877: 	Debug("Returning nouser");
1.78      foxr     3878: 	return "nouser";
                   3879:     }
1.1       albertel 3880: }
                   3881: 
1.84      albertel 3882: sub addline {
                   3883:     my ($fname,$hostid,$ip,$newline)=@_;
                   3884:     my $contents;
                   3885:     my $found=0;
                   3886:     my $expr='^'.$hostid.':'.$ip.':';
                   3887:     $expr =~ s/\./\\\./g;
1.134     albertel 3888:     my $sh;
1.84      albertel 3889:     if ($sh=IO::File->new("$fname.subscription")) {
                   3890: 	while (my $subline=<$sh>) {
                   3891: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   3892: 	}
                   3893: 	$sh->close();
                   3894:     }
                   3895:     $sh=IO::File->new(">$fname.subscription");
                   3896:     if ($contents) { print $sh $contents; }
                   3897:     if ($newline) { print $sh $newline; }
                   3898:     $sh->close();
                   3899:     return $found;
1.86      www      3900: }
                   3901: 
                   3902: sub getchat {
1.122     www      3903:     my ($cdom,$cname,$udom,$uname)=@_;
1.87      www      3904:     my %hash;
                   3905:     my $proname=&propath($cdom,$cname);
                   3906:     my @entries=();
1.88      albertel 3907:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   3908: 	    &GDBM_READER(),0640)) {
                   3909: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   3910: 	untie %hash;
1.123     www      3911:     }
1.124     www      3912:     my @participants=();
1.134     albertel 3913:     my $cutoff=time-60;
1.123     www      3914:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124     www      3915: 	    &GDBM_WRCREAT(),0640)) {
                   3916:         $hash{$uname.':'.$udom}=time;
1.123     www      3917:         foreach (sort keys %hash) {
                   3918: 	    if ($hash{$_}>$cutoff) {
1.124     www      3919: 		$participants[$#participants+1]='active_participant:'.$_;
1.123     www      3920:             }
                   3921:         }
                   3922:         untie %hash;
1.86      www      3923:     }
1.124     www      3924:     return (@participants,@entries);
1.86      www      3925: }
                   3926: 
                   3927: sub chatadd {
1.88      albertel 3928:     my ($cdom,$cname,$newchat)=@_;
                   3929:     my %hash;
                   3930:     my $proname=&propath($cdom,$cname);
                   3931:     my @entries=();
1.142     www      3932:     my $time=time;
1.88      albertel 3933:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   3934: 	    &GDBM_WRCREAT(),0640)) {
                   3935: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   3936: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   3937: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   3938: 	my $newid=$time.'_000000';
                   3939: 	if ($thentime==$time) {
                   3940: 	    $idnum=~s/^0+//;
                   3941: 	    $idnum++;
                   3942: 	    $idnum=substr('000000'.$idnum,-6,6);
                   3943: 	    $newid=$time.'_'.$idnum;
                   3944: 	}
                   3945: 	$hash{$newid}=$newchat;
                   3946: 	my $expired=$time-3600;
                   3947: 	foreach (keys %hash) {
                   3948: 	    my ($thistime)=($_=~/(\d+)\_/);
                   3949: 	    if ($thistime<$expired) {
1.89      www      3950: 		delete $hash{$_};
1.88      albertel 3951: 	    }
                   3952: 	}
                   3953: 	untie %hash;
1.142     www      3954:     }
                   3955:     {
                   3956: 	my $hfh;
                   3957: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
                   3958: 	    print $hfh "$time:".&unescape($newchat)."\n";
                   3959: 	}
1.86      www      3960:     }
1.84      albertel 3961: }
                   3962: 
                   3963: sub unsub {
                   3964:     my ($fname,$clientip)=@_;
                   3965:     my $result;
1.188     foxr     3966:     my $unsubs = 0;		# Number of successful unsubscribes:
                   3967: 
                   3968: 
                   3969:     # An old way subscriptions were handled was to have a 
                   3970:     # subscription marker file:
                   3971: 
                   3972:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     3973:     if (unlink("$fname.$clientname")) {
1.188     foxr     3974: 	$unsubs++;		# Successful unsub via marker file.
                   3975:     } 
                   3976: 
                   3977:     # The more modern way to do it is to have a subscription list
                   3978:     # file:
                   3979: 
1.84      albertel 3980:     if (-e "$fname.subscription") {
1.161     foxr     3981: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     3982: 	if ($found) { 
                   3983: 	    $unsubs++;
                   3984: 	}
                   3985:     } 
                   3986: 
                   3987:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   3988:     #  resource we can return ok:
                   3989: 
                   3990:     if($unsubs) {
                   3991: 	$result = "ok\n";
1.84      albertel 3992:     } else {
1.188     foxr     3993: 	$result = "not_subscribed\n";
1.84      albertel 3994:     }
1.188     foxr     3995: 
1.84      albertel 3996:     return $result;
                   3997: }
                   3998: 
1.101     www      3999: sub currentversion {
                   4000:     my $fname=shift;
                   4001:     my $version=-1;
                   4002:     my $ulsdir='';
                   4003:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   4004:        $ulsdir=$1;
                   4005:     }
1.114     albertel 4006:     my ($fnamere1,$fnamere2);
                   4007:     # remove version if already specified
1.101     www      4008:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 4009:     # get the bits that go before and after the version number
                   4010:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   4011: 	$fnamere1=$1;
                   4012: 	$fnamere2='.'.$2;
                   4013:     }
1.101     www      4014:     if (-e $fname) { $version=1; }
                   4015:     if (-e $ulsdir) {
1.134     albertel 4016: 	if(-d $ulsdir) {
                   4017: 	    if (opendir(LSDIR,$ulsdir)) {
                   4018: 		my $ulsfn;
                   4019: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      4020: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 4021: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   4022: 		    unless (-l $thisfile) {
1.160     www      4023: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 4024: 			    if ($1>$version) { $version=$1; }
                   4025: 			}
                   4026: 		    }
                   4027: 		}
                   4028: 		closedir(LSDIR);
                   4029: 		$version++;
                   4030: 	    }
                   4031: 	}
                   4032:     }
                   4033:     return $version;
1.101     www      4034: }
                   4035: 
                   4036: sub thisversion {
                   4037:     my $fname=shift;
                   4038:     my $version=-1;
                   4039:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   4040: 	$version=$1;
                   4041:     }
                   4042:     return $version;
                   4043: }
                   4044: 
1.84      albertel 4045: sub subscribe {
                   4046:     my ($userinput,$clientip)=@_;
                   4047:     my $result;
                   4048:     my ($cmd,$fname)=split(/:/,$userinput);
                   4049:     my $ownership=&ishome($fname);
                   4050:     if ($ownership eq 'owner') {
1.101     www      4051: # explitly asking for the current version?
                   4052:         unless (-e $fname) {
                   4053:             my $currentversion=&currentversion($fname);
                   4054: 	    if (&thisversion($fname)==$currentversion) {
                   4055:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   4056: 		    my $root=$1;
                   4057:                     my $extension=$2;
                   4058:                     symlink($root.'.'.$extension,
                   4059:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      4060:                     unless ($extension=~/\.meta$/) {
                   4061:                        symlink($root.'.'.$extension.'.meta',
                   4062:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   4063: 		    }
1.101     www      4064:                 }
                   4065:             }
                   4066:         }
1.84      albertel 4067: 	if (-e $fname) {
                   4068: 	    if (-d $fname) {
                   4069: 		$result="directory\n";
                   4070: 	    } else {
1.161     foxr     4071: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 4072: 		my $now=time;
1.161     foxr     4073: 		my $found=&addline($fname,$clientname,$clientip,
                   4074: 				   "$clientname:$clientip:$now\n");
1.84      albertel 4075: 		if ($found) { $result="$fname\n"; }
                   4076: 		# if they were subscribed to only meta data, delete that
                   4077:                 # subscription, when you subscribe to a file you also get
                   4078:                 # the metadata
                   4079: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   4080: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
                   4081: 		$fname="http://$thisserver/".$fname;
                   4082: 		$result="$fname\n";
                   4083: 	    }
                   4084: 	} else {
                   4085: 	    $result="not_found\n";
                   4086: 	}
                   4087:     } else {
                   4088: 	$result="rejected\n";
                   4089:     }
                   4090:     return $result;
                   4091: }
1.91      albertel 4092: 
                   4093: sub make_passwd_file {
1.98      foxr     4094:     my ($uname, $umode,$npass,$passfilename)=@_;
1.91      albertel 4095:     my $result="ok\n";
                   4096:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   4097: 	{
                   4098: 	    my $pf = IO::File->new(">$passfilename");
                   4099: 	    print $pf "$umode:$npass\n";
                   4100: 	}
                   4101:     } elsif ($umode eq 'internal') {
                   4102: 	my $salt=time;
                   4103: 	$salt=substr($salt,6,2);
                   4104: 	my $ncpass=crypt($npass,$salt);
                   4105: 	{
                   4106: 	    &Debug("Creating internal auth");
                   4107: 	    my $pf = IO::File->new(">$passfilename");
                   4108: 	    print $pf "internal:$ncpass\n"; 
                   4109: 	}
                   4110:     } elsif ($umode eq 'localauth') {
                   4111: 	{
                   4112: 	    my $pf = IO::File->new(">$passfilename");
                   4113: 	    print $pf "localauth:$npass\n";
                   4114: 	}
                   4115:     } elsif ($umode eq 'unix') {
                   4116: 	{
1.186     foxr     4117: 	    #
                   4118: 	    #  Don't allow the creation of privileged accounts!!! that would
                   4119: 	    #  be real bad!!!
                   4120: 	    #
                   4121: 	    my $uid = getpwnam($uname);
                   4122: 	    if((defined $uid) && ($uid == 0)) {
                   4123: 		&logthis(">>>Attempted to create privilged account blocked");
                   4124: 		return "no_priv_account_error\n";
                   4125: 	    }
                   4126: 
1.91      albertel 4127: 	    my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
                   4128: 	    {
                   4129: 		&Debug("Executing external: ".$execpath);
1.98      foxr     4130: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  4131: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 4132: 		print $se "$uname\n";
                   4133: 		print $se "$npass\n";
                   4134: 		print $se "$npass\n";
1.97      foxr     4135: 	    }
                   4136: 	    my $useraddok = $?;
                   4137: 	    if($useraddok > 0) {
                   4138: 		&logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
1.91      albertel 4139: 	    }
                   4140: 	    my $pf = IO::File->new(">$passfilename");
                   4141: 	    print $pf "unix:\n";
                   4142: 	}
                   4143:     } elsif ($umode eq 'none') {
                   4144: 	{
                   4145: 	    my $pf = IO::File->new(">$passfilename");
                   4146: 	    print $pf "none:\n";
                   4147: 	}
                   4148:     } else {
                   4149: 	$result="auth_mode_error\n";
                   4150:     }
                   4151:     return $result;
1.121     albertel 4152: }
                   4153: 
                   4154: sub sethost {
                   4155:     my ($remotereq) = @_;
                   4156:     my (undef,$hostid)=split(/:/,$remotereq);
                   4157:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
                   4158:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200     matthew  4159: 	$currenthostid  =$hostid;
1.121     albertel 4160: 	$currentdomainid=$hostdom{$hostid};
                   4161: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
                   4162:     } else {
                   4163: 	&logthis("Requested host id $hostid not an alias of ".
                   4164: 		 $perlvar{'lonHostID'}." refusing connection");
                   4165: 	return 'unable_to_set';
                   4166:     }
                   4167:     return 'ok';
                   4168: }
                   4169: 
                   4170: sub version {
                   4171:     my ($userinput)=@_;
                   4172:     $remoteVERSION=(split(/:/,$userinput))[1];
                   4173:     return "version:$VERSION";
1.127     albertel 4174: }
1.178     foxr     4175: 
1.128     albertel 4176: #There is a copy of this in lonnet.pm
1.127     albertel 4177: sub userload {
                   4178:     my $numusers=0;
                   4179:     {
                   4180: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   4181: 	my $filename;
                   4182: 	my $curtime=time;
                   4183: 	while ($filename=readdir(LONIDS)) {
                   4184: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.138     albertel 4185: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159     albertel 4186: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.127     albertel 4187: 	}
                   4188: 	closedir(LONIDS);
                   4189:     }
                   4190:     my $userloadpercent=0;
                   4191:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   4192:     if ($maxuserload) {
1.129     albertel 4193: 	$userloadpercent=100*$numusers/$maxuserload;
1.127     albertel 4194:     }
1.130     albertel 4195:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127     albertel 4196:     return $userloadpercent;
1.91      albertel 4197: }
                   4198: 
1.205     raeburn  4199: # Routines for serializing arrays and hashes (copies from lonnet)
                   4200: 
                   4201: sub array2str {
                   4202:   my (@array) = @_;
                   4203:   my $result=&arrayref2str(\@array);
                   4204:   $result=~s/^__ARRAY_REF__//;
                   4205:   $result=~s/__END_ARRAY_REF__$//;
                   4206:   return $result;
                   4207: }
                   4208:                                                                                  
                   4209: sub arrayref2str {
                   4210:   my ($arrayref) = @_;
                   4211:   my $result='__ARRAY_REF__';
                   4212:   foreach my $elem (@$arrayref) {
                   4213:     if(ref($elem) eq 'ARRAY') {
                   4214:       $result.=&arrayref2str($elem).'&';
                   4215:     } elsif(ref($elem) eq 'HASH') {
                   4216:       $result.=&hashref2str($elem).'&';
                   4217:     } elsif(ref($elem)) {
                   4218:       #print("Got a ref of ".(ref($elem))." skipping.");
                   4219:     } else {
                   4220:       $result.=&escape($elem).'&';
                   4221:     }
                   4222:   }
                   4223:   $result=~s/\&$//;
                   4224:   $result .= '__END_ARRAY_REF__';
                   4225:   return $result;
                   4226: }
                   4227:                                                                                  
                   4228: sub hash2str {
                   4229:   my (%hash) = @_;
                   4230:   my $result=&hashref2str(\%hash);
                   4231:   $result=~s/^__HASH_REF__//;
                   4232:   $result=~s/__END_HASH_REF__$//;
                   4233:   return $result;
                   4234: }
                   4235:                                                                                  
                   4236: sub hashref2str {
                   4237:   my ($hashref)=@_;
                   4238:   my $result='__HASH_REF__';
                   4239:   foreach (sort(keys(%$hashref))) {
                   4240:     if (ref($_) eq 'ARRAY') {
                   4241:       $result.=&arrayref2str($_).'=';
                   4242:     } elsif (ref($_) eq 'HASH') {
                   4243:       $result.=&hashref2str($_).'=';
                   4244:     } elsif (ref($_)) {
                   4245:       $result.='=';
                   4246:       #print("Got a ref of ".(ref($_))." skipping.");
                   4247:     } else {
                   4248:         if ($_) {$result.=&escape($_).'=';} else { last; }
                   4249:     }
                   4250: 
                   4251:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   4252:       $result.=&arrayref2str($hashref->{$_}).'&';
                   4253:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   4254:       $result.=&hashref2str($hashref->{$_}).'&';
                   4255:     } elsif(ref($hashref->{$_})) {
                   4256:        $result.='&';
                   4257:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
                   4258:     } else {
                   4259:       $result.=&escape($hashref->{$_}).'&';
                   4260:     }
                   4261:   }
                   4262:   $result=~s/\&$//;
                   4263:   $result .= '__END_HASH_REF__';
                   4264:   return $result;
                   4265: }
1.200     matthew  4266: 
1.61      harris41 4267: # ----------------------------------- POD (plain old documentation, CPAN style)
                   4268: 
                   4269: =head1 NAME
                   4270: 
                   4271: lond - "LON Daemon" Server (port "LOND" 5663)
                   4272: 
                   4273: =head1 SYNOPSIS
                   4274: 
1.74      harris41 4275: Usage: B<lond>
                   4276: 
                   4277: Should only be run as user=www.  This is a command-line script which
                   4278: is invoked by B<loncron>.  There is no expectation that a typical user
                   4279: will manually start B<lond> from the command-line.  (In other words,
                   4280: DO NOT START B<lond> YOURSELF.)
1.61      harris41 4281: 
                   4282: =head1 DESCRIPTION
                   4283: 
1.74      harris41 4284: There are two characteristics associated with the running of B<lond>,
                   4285: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   4286: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   4287: subscriptions, etc).  These are described in two large
                   4288: sections below.
                   4289: 
                   4290: B<PROCESS MANAGEMENT>
                   4291: 
1.61      harris41 4292: Preforker - server who forks first. Runs as a daemon. HUPs.
                   4293: Uses IDEA encryption
                   4294: 
1.74      harris41 4295: B<lond> forks off children processes that correspond to the other servers
                   4296: in the network.  Management of these processes can be done at the
                   4297: parent process level or the child process level.
                   4298: 
                   4299: B<logs/lond.log> is the location of log messages.
                   4300: 
                   4301: The process management is now explained in terms of linux shell commands,
                   4302: subroutines internal to this code, and signal assignments:
                   4303: 
                   4304: =over 4
                   4305: 
                   4306: =item *
                   4307: 
                   4308: PID is stored in B<logs/lond.pid>
                   4309: 
                   4310: This is the process id number of the parent B<lond> process.
                   4311: 
                   4312: =item *
                   4313: 
                   4314: SIGTERM and SIGINT
                   4315: 
                   4316: Parent signal assignment:
                   4317:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   4318: 
                   4319: Child signal assignment:
                   4320:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   4321: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   4322:  to restart a new child.)
                   4323: 
                   4324: Command-line invocations:
                   4325:  B<kill> B<-s> SIGTERM I<PID>
                   4326:  B<kill> B<-s> SIGINT I<PID>
                   4327: 
                   4328: Subroutine B<HUNTSMAN>:
                   4329:  This is only invoked for the B<lond> parent I<PID>.
                   4330: This kills all the children, and then the parent.
                   4331: The B<lonc.pid> file is cleared.
                   4332: 
                   4333: =item *
                   4334: 
                   4335: SIGHUP
                   4336: 
                   4337: Current bug:
                   4338:  This signal can only be processed the first time
                   4339: on the parent process.  Subsequent SIGHUP signals
                   4340: have no effect.
                   4341: 
                   4342: Parent signal assignment:
                   4343:  $SIG{HUP}  = \&HUPSMAN;
                   4344: 
                   4345: Child signal assignment:
                   4346:  none (nothing happens)
                   4347: 
                   4348: Command-line invocations:
                   4349:  B<kill> B<-s> SIGHUP I<PID>
                   4350: 
                   4351: Subroutine B<HUPSMAN>:
                   4352:  This is only invoked for the B<lond> parent I<PID>,
                   4353: This kills all the children, and then the parent.
                   4354: The B<lond.pid> file is cleared.
                   4355: 
                   4356: =item *
                   4357: 
                   4358: SIGUSR1
                   4359: 
                   4360: Parent signal assignment:
                   4361:  $SIG{USR1} = \&USRMAN;
                   4362: 
                   4363: Child signal assignment:
                   4364:  $SIG{USR1}= \&logstatus;
                   4365: 
                   4366: Command-line invocations:
                   4367:  B<kill> B<-s> SIGUSR1 I<PID>
                   4368: 
                   4369: Subroutine B<USRMAN>:
                   4370:  When invoked for the B<lond> parent I<PID>,
                   4371: SIGUSR1 is sent to all the children, and the status of
                   4372: each connection is logged.
1.144     foxr     4373: 
                   4374: =item *
                   4375: 
                   4376: SIGUSR2
                   4377: 
                   4378: Parent Signal assignment:
                   4379:     $SIG{USR2} = \&UpdateHosts
                   4380: 
                   4381: Child signal assignment:
                   4382:     NONE
                   4383: 
1.74      harris41 4384: 
                   4385: =item *
                   4386: 
                   4387: SIGCHLD
                   4388: 
                   4389: Parent signal assignment:
                   4390:  $SIG{CHLD} = \&REAPER;
                   4391: 
                   4392: Child signal assignment:
                   4393:  none
                   4394: 
                   4395: Command-line invocations:
                   4396:  B<kill> B<-s> SIGCHLD I<PID>
                   4397: 
                   4398: Subroutine B<REAPER>:
                   4399:  This is only invoked for the B<lond> parent I<PID>.
                   4400: Information pertaining to the child is removed.
                   4401: The socket port is cleaned up.
                   4402: 
                   4403: =back
                   4404: 
                   4405: B<SERVER-SIDE ACTIVITIES>
                   4406: 
                   4407: Server-side information can be accepted in an encrypted or non-encrypted
                   4408: method.
                   4409: 
                   4410: =over 4
                   4411: 
                   4412: =item ping
                   4413: 
                   4414: Query a client in the hosts.tab table; "Are you there?"
                   4415: 
                   4416: =item pong
                   4417: 
                   4418: Respond to a ping query.
                   4419: 
                   4420: =item ekey
                   4421: 
                   4422: Read in encrypted key, make cipher.  Respond with a buildkey.
                   4423: 
                   4424: =item load
                   4425: 
                   4426: Respond with CPU load based on a computation upon /proc/loadavg.
                   4427: 
                   4428: =item currentauth
                   4429: 
                   4430: Reply with current authentication information (only over an
                   4431: encrypted channel).
                   4432: 
                   4433: =item auth
                   4434: 
                   4435: Only over an encrypted channel, reply as to whether a user's
                   4436: authentication information can be validated.
                   4437: 
                   4438: =item passwd
                   4439: 
                   4440: Allow for a password to be set.
                   4441: 
                   4442: =item makeuser
                   4443: 
                   4444: Make a user.
                   4445: 
                   4446: =item passwd
                   4447: 
                   4448: Allow for authentication mechanism and password to be changed.
                   4449: 
                   4450: =item home
1.61      harris41 4451: 
1.74      harris41 4452: Respond to a question "are you the home for a given user?"
                   4453: 
                   4454: =item update
                   4455: 
                   4456: Update contents of a subscribed resource.
                   4457: 
                   4458: =item unsubscribe
                   4459: 
                   4460: The server is unsubscribing from a resource.
                   4461: 
                   4462: =item subscribe
                   4463: 
                   4464: The server is subscribing to a resource.
                   4465: 
                   4466: =item log
                   4467: 
                   4468: Place in B<logs/lond.log>
                   4469: 
                   4470: =item put
                   4471: 
                   4472: stores hash in namespace
                   4473: 
                   4474: =item rolesput
                   4475: 
                   4476: put a role into a user's environment
                   4477: 
                   4478: =item get
                   4479: 
                   4480: returns hash with keys from array
                   4481: reference filled in from namespace
                   4482: 
                   4483: =item eget
                   4484: 
                   4485: returns hash with keys from array
                   4486: reference filled in from namesp (encrypts the return communication)
                   4487: 
                   4488: =item rolesget
                   4489: 
                   4490: get a role from a user's environment
                   4491: 
                   4492: =item del
                   4493: 
                   4494: deletes keys out of array from namespace
                   4495: 
                   4496: =item keys
                   4497: 
                   4498: returns namespace keys
                   4499: 
                   4500: =item dump
                   4501: 
                   4502: dumps the complete (or key matching regexp) namespace into a hash
                   4503: 
                   4504: =item store
                   4505: 
                   4506: stores hash permanently
                   4507: for this url; hashref needs to be given and should be a \%hashname; the
                   4508: remaining args aren't required and if they aren't passed or are '' they will
                   4509: be derived from the ENV
                   4510: 
                   4511: =item restore
                   4512: 
                   4513: returns a hash for a given url
                   4514: 
                   4515: =item querysend
                   4516: 
                   4517: Tells client about the lonsql process that has been launched in response
                   4518: to a sent query.
                   4519: 
                   4520: =item queryreply
                   4521: 
                   4522: Accept information from lonsql and make appropriate storage in temporary
                   4523: file space.
                   4524: 
                   4525: =item idput
                   4526: 
                   4527: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   4528: for each student, defined perhaps by the institutional Registrar.)
                   4529: 
                   4530: =item idget
                   4531: 
                   4532: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   4533: for each student, defined perhaps by the institutional Registrar.)
                   4534: 
                   4535: =item tmpput
                   4536: 
                   4537: Accept and store information in temporary space.
                   4538: 
                   4539: =item tmpget
                   4540: 
                   4541: Send along temporarily stored information.
                   4542: 
                   4543: =item ls
                   4544: 
                   4545: List part of a user's directory.
                   4546: 
1.135     foxr     4547: =item pushtable
                   4548: 
                   4549: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   4550: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   4551: must be restored manually in case of a problem with the new table file.
                   4552: pushtable requires that the request be encrypted and validated via
                   4553: ValidateManager.  The form of the command is:
                   4554: enc:pushtable tablename <tablecontents> \n
                   4555: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   4556: cleartext newline.
                   4557: 
1.74      harris41 4558: =item Hanging up (exit or init)
                   4559: 
                   4560: What to do when a client tells the server that they (the client)
                   4561: are leaving the network.
                   4562: 
                   4563: =item unknown command
                   4564: 
                   4565: If B<lond> is sent an unknown command (not in the list above),
                   4566: it replys to the client "unknown_cmd".
1.135     foxr     4567: 
1.74      harris41 4568: 
                   4569: =item UNKNOWN CLIENT
                   4570: 
                   4571: If the anti-spoofing algorithm cannot verify the client,
                   4572: the client is rejected (with a "refused" message sent
                   4573: to the client, and the connection is closed.
                   4574: 
                   4575: =back
1.61      harris41 4576: 
                   4577: =head1 PREREQUISITES
                   4578: 
                   4579: IO::Socket
                   4580: IO::File
                   4581: Apache::File
                   4582: Symbol
                   4583: POSIX
                   4584: Crypt::IDEA
                   4585: LWP::UserAgent()
                   4586: GDBM_File
                   4587: Authen::Krb4
1.91      albertel 4588: Authen::Krb5
1.61      harris41 4589: 
                   4590: =head1 COREQUISITES
                   4591: 
                   4592: =head1 OSNAMES
                   4593: 
                   4594: linux
                   4595: 
                   4596: =head1 SCRIPT CATEGORIES
                   4597: 
                   4598: Server/Process
                   4599: 
                   4600: =cut

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