Annotation of loncom/lond, revision 1.244

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

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