File:  [LON-CAPA] / loncom / lond
Revision 1.178.2.9: download - view: text, annotated - select for diffs
Mon Mar 22 09:05:11 2004 UTC (20 years, 1 month ago) by foxr
Branches: Refactoring
Fix up some indentation.

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

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