Annotation of loncom/lond, revision 1.220

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

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