Annotation of loncom/lond, revision 1.219

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

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