File:  [LON-CAPA] / loncom / lond
Revision 1.178.2.3: download - view: text, annotated - select for diffs
Tue Feb 24 11:22:41 2004 UTC (20 years, 2 months ago) by foxr
Branches: Refactoring
Completed first level break up of lond into 1 handler per request type.
The daemon seems, on the whole to work however:
- There is a lot more testing that must be done.
- There's a lot more potential refactoring to be done.
- There's a need to explore what happens to lonc in the presence
  of lond's disconnecting/exiting.

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

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