Annotation of loncom/lond, revision 1.178.2.2

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.178.2.1  foxr        5: # $Id: lond,v 1.169 2003/12/30 11:28:16 foxr Exp $
1.60      www         6: #
                      7: # Copyright Michigan State University Board of Trustees
                      8: #
                      9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                     10: #
                     11: # LON-CAPA is free software; you can redistribute it and/or modify
                     12: # it under the terms of the GNU General Public License as published by
1.167     foxr       13: # the Free Software Foundation; either version 2 of the License, or 
1.60      www        14: # (at your option) any later version.
                     15: #
                     16: # LON-CAPA is distributed in the hope that it will be useful,
                     17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     19: # GNU General Public License for more details.
                     20: #
                     21: # You should have received a copy of the GNU General Public License
                     22: # along with LON-CAPA; if not, write to the Free Software
1.178.2.1  foxr       23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA    
1.60      www        24: #
                     25: # /home/httpd/html/adm/gpl.txt
                     26: #
1.161     foxr       27: 
                     28: 
1.60      www        29: # http://www.lon-capa.org/
                     30: #
1.54      harris41   31: 
1.134     albertel   32: use strict;
1.80      harris41   33: use lib '/home/httpd/lib/perl/';
                     34: use LONCAPA::Configuration;
                     35: 
1.1       albertel   36: use IO::Socket;
                     37: use IO::File;
1.126     albertel   38: #use Apache::File;
1.1       albertel   39: use Symbol;
                     40: use POSIX;
                     41: use Crypt::IDEA;
                     42: use LWP::UserAgent();
1.3       www        43: use GDBM_File;
                     44: use Authen::Krb4;
1.91      albertel   45: use Authen::Krb5;
1.49      albertel   46: use lib '/home/httpd/lib/perl/';
                     47: use localauth;
1.143     foxr       48: use File::Copy;
1.169     foxr       49: use LONCAPA::ConfigFileEdit;
1.1       albertel   50: 
1.178.2.2! foxr       51: my $DEBUG = 1;		       # Non zero to enable debug log entries.
1.77      foxr       52: 
1.57      www        53: my $status='';
                     54: my $lastlog='';
                     55: 
1.178.2.1  foxr       56: my $VERSION='$Revision: 1.169 $'; #' stupid emacs
1.121     albertel   57: my $remoteVERSION;
1.115     albertel   58: my $currenthostid;
                     59: my $currentdomainid;
1.134     albertel   60: 
                     61: my $client;
1.140     foxr       62: my $clientip;
1.161     foxr       63: my $clientname;
1.140     foxr       64: 
1.178.2.1  foxr       65: my $cipher;			# Cipher key negotiated with client.
                     66: my $tmpsnum = 0;;		# Id of tmpputs.
                     67: 
1.134     albertel   68: my $server;
                     69: my $thisserver;
                     70: 
1.178.2.1  foxr       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);
1.178.2.2! foxr      629:    Debug(" Authenticate domain = $udom, user = $uname, password = $upass");
1.178.2.1  foxr      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) {
1.178.2.2! foxr      638:      Debug("Located password file: $passfilename");
        !           639: 
1.178.2.1  foxr      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:       #
1.178.2.2! foxr      648:      Debug("Authenticating via $howpwd");
1.178.2.1  foxr      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: RegisterHandler("idget", \&GetIdHandler, 0, 1, 0);
                   2427: #------------------------------------------------------------------------------------
                   2428: #
                   2429: #   Process a Request.  Takes a request from the client validates
                   2430: #   it and performs the operation requested by it.  Returns
                   2431: #   a response to the client.
                   2432: #
                   2433: #  Parameters:
                   2434: #      request      - A string containing the user's request.
                   2435: #  Returns:
                   2436: #      0            - Requested to exit, caller should shut down.
                   2437: #      1            - Accept additional requests from the client.
                   2438: #
                   2439: sub ProcessRequest {
                   2440:    my $Request      = shift;
                   2441:    my $KeepGoing    = 1;	# Assume we're not asked to stop.
                   2442:     
                   2443:    my $wasenc=0;
                   2444:    my $userinput = $Request;   # for compatibility with oldcode <yeach>
                   2445: 
                   2446: 
                   2447: # ------------------------------------------------------------ See if encrypted
                   2448:    
                   2449:    if($userinput =~ /^enc/) {
                   2450:       $wasenc = 1;
                   2451:       $userinput = Decipher($userinput);
                   2452:       if(! $userinput) {
                   2453:          Failure($client,"error:Encrypted data without negotiating key");
                   2454:          return 0;                      # Break off with this imposter.
                   2455:       }
                   2456:    }
                   2457:    # Split off the request keyword from the rest of the stuff.
                   2458:    
                   2459:    my ($command, $tail) = split(/:/, $userinput, 2);
1.178.2.2! foxr     2460: 
        !          2461:    Debug("Command received: $command, encoded = $wasenc");
        !          2462: 
1.178.2.1  foxr     2463:    
                   2464: # ------------------------------------------------------------- Normal commands
                   2465: 
                   2466:    # 
                   2467:    #   If the command is in the hash, then execute it via the hash dispatch:
                   2468:    #
                   2469:    if(defined $Dispatcher{$command}) {
                   2470: 
                   2471:       my $DispatchInfo = $Dispatcher{$command};
                   2472:       my $Handler      = $$DispatchInfo[0];
                   2473:       my $NeedEncode   = $$DispatchInfo[1];
                   2474:       my $ClientTypes  = $$DispatchInfo[2];
1.178.2.2! foxr     2475:       Debug("Matched dispatch hash: mustencode: $NeedEncode ClientType $ClientTypes");
1.178.2.1  foxr     2476:       
                   2477:       #  Validate the request:
                   2478:       
                   2479:       my $ok = 1;
1.178.2.2! foxr     2480:       my $requesterprivs = 0;
        !          2481:       if(isClient()) {
        !          2482: 	$requesterprivs |= $CLIENT_OK;
1.178.2.1  foxr     2483:       }
1.178.2.2! foxr     2484:       if(isManager()) {
        !          2485: 	$requesterprivs |= $MANAGER_OK;
1.178.2.1  foxr     2486:       }
1.178.2.2! foxr     2487:       if($NeedEncode && (!$wasenc)) {
        !          2488: 	Debug("Must encode but wasn't: $NeedEncode $wasenc");
1.178.2.1  foxr     2489:          $ok = 0;
                   2490:       }
1.178.2.2! foxr     2491:       if(($ClientTypes & $requesterprivs) == 0) {
        !          2492: 	Debug("Client not privileged to do this operation");
        !          2493: 	$ok = 0;
        !          2494:       }
        !          2495: 
1.178.2.1  foxr     2496:       if($ok) {
1.178.2.2! foxr     2497: 	Debug("Dispatching to handler $command $tail");
1.178.2.1  foxr     2498:          $KeepGoing = &$Handler($command, $tail, $client);
1.178.2.2! foxr     2499:       } else {
        !          2500: 	Debug("Refusing to dispatch because ok is false");
        !          2501: 	Failure($client, "refused", $userinput);
1.178.2.1  foxr     2502:       }
1.161     foxr     2503: 
                   2504: 
                   2505: 
                   2506: 
1.134     albertel 2507: 
1.178.2.1  foxr     2508: # ---------------------------------------------------------------------- tmpput
                   2509:    } elsif ($userinput =~ /^tmpput/) {
                   2510:       if(isClient) {
                   2511:          my ($cmd,$what)=split(/:/,$userinput);
                   2512:          my $store;
                   2513:          $tmpsnum++;
                   2514:          my $id=$$.'_'.$clientip.'_'.$tmpsnum;
                   2515:          $id=~s/\W/\_/g;
                   2516:          $what=~s/\n//g;
                   2517:          my $execdir=$perlvar{'lonDaemons'};
                   2518:          if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
                   2519:             print $store $what;
                   2520:             close $store;
                   2521:             Reply($client, "$id\n", $userinput);
                   2522:          }
                   2523:          else {
                   2524:             Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   2525:                            "while attempting tmpput\n", $userinput);
                   2526:          }
                   2527:       } else {
                   2528:          Failure($client, "refused\n", $userinput);
                   2529: 	    
                   2530:       }
                   2531: 	
                   2532: # ---------------------------------------------------------------------- tmpget
                   2533:    } elsif ($userinput =~ /^tmpget/) {
                   2534:       if(isClient) {
                   2535:          my ($cmd,$id)=split(/:/,$userinput);
                   2536:          chomp($id);
                   2537:          $id=~s/\W/\_/g;
                   2538:          my $store;
                   2539:          my $execdir=$perlvar{'lonDaemons'};
                   2540:          if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   2541:             my $reply=<$store>;
                   2542:             Reply( $client, "$reply\n", $userinput);
                   2543:             close $store;
                   2544:          }
                   2545:          else {
                   2546:             Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   2547:                                "while attempting tmpget\n", $userinput);
                   2548:          }
                   2549:       } else {
                   2550:          Failure($client, "refused\n", $userinput);
                   2551: 	    
                   2552:       }
                   2553: # ---------------------------------------------------------------------- tmpdel
                   2554:    } elsif ($userinput =~ /^tmpdel/) {
                   2555:       if(isClient) {
                   2556:          my ($cmd,$id)=split(/:/,$userinput);
                   2557:          chomp($id);
                   2558:          $id=~s/\W/\_/g;
                   2559:          my $execdir=$perlvar{'lonDaemons'};
                   2560:          if (unlink("$execdir/tmp/$id.tmp")) {
                   2561:             Reply($client, "ok\n", $userinput);
                   2562:          } else {
                   2563:             Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   2564:                                  "while attempting tmpdel\n", $userinput);
                   2565:          }
                   2566:       } else {
                   2567:          Failure($client, "refused\n", $userinput);
                   2568:       }
                   2569: # -------------------------------------------------------------------------- ls
                   2570:    } elsif ($userinput =~ /^ls/) {
                   2571:       if(isClient) {
                   2572:          my ($cmd,$ulsdir)=split(/:/,$userinput);
                   2573:          my $ulsout='';
                   2574:          my $ulsfn;
                   2575:          if (-e $ulsdir) {
                   2576:             if(-d $ulsdir) {
                   2577:                if (opendir(LSDIR,$ulsdir)) {
                   2578:                   while ($ulsfn=readdir(LSDIR)) {
                   2579:                      my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   2580:                      $ulsout.=$ulsfn.'&'.
                   2581:                      join('&',@ulsstats).':';
                   2582:                   }
                   2583:                   closedir(LSDIR);
                   2584:                }
                   2585:             } else {
                   2586:                my @ulsstats=stat($ulsdir);
                   2587:                $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   2588:             }
                   2589:          } else {
                   2590:             $ulsout='no_such_dir';
                   2591:          }
                   2592:          if ($ulsout eq '') { $ulsout='empty'; }
                   2593:          Reply($client, "$ulsout\n", $userinput);
                   2594:       } else {
                   2595:          Failure($client, "refused\n", $userinput);
                   2596: 	    
                   2597:       }
                   2598: # ----------------------------------------------------------------- setannounce
                   2599:    } elsif ($userinput =~ /^setannounce/) {
                   2600:       if (isClient) {
                   2601:          my ($cmd,$announcement)=split(/:/,$userinput);
                   2602:          chomp($announcement);
                   2603:          $announcement=&unescape($announcement);
                   2604:          if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   2605:                                              '/announcement.txt')) {
                   2606:             print $store $announcement;
                   2607:             close $store;
                   2608:             Reply($client, "ok\n", $userinput);
                   2609:          } else {
                   2610:             Failure($client, "error: ".($!+0)."\n", $userinput);
                   2611:          }
                   2612:       } else {
                   2613:          Failure($client, "refused\n", $userinput);
                   2614: 	    
                   2615:       }
                   2616: # ------------------------------------------------------------------ Hanging up
                   2617:    } elsif (($userinput =~ /^exit/) ||
                   2618: 	         ($userinput =~ /^init/)) { # no restrictions.
                   2619:       &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   2620:       Reply($client, "bye\n", $userinput);
                   2621:       $client->shutdown(2);        # shutdown the socket forcibly.
                   2622:       $client->close();
                   2623:       $KeepGoing = 0;		# Flag to exit the program.
1.97      foxr     2624: 
1.178.2.1  foxr     2625: # ---------------------------------- set current host/domain
                   2626:    } elsif ($userinput =~ /^sethost:/) {
                   2627:       if (isClient) {
                   2628:          Reply($client, &sethost($userinput)."\n", $userinput);
                   2629:       } else {
                   2630:          Failure($client, "refused\n", $userinput);
                   2631:       }
                   2632: #---------------------------------- request file (?) version.
                   2633:     } elsif ($userinput =~/^version:/) {
                   2634: 	if (isClient) {
                   2635: 	    Reply($client, &version($userinput)."\n", $userinput);
                   2636: 	} else {
                   2637: 	    Reply( $client, "refused\n", $userinput);
                   2638: 	}
                   2639: # ------------------------------------------------------------- unknown command
1.97      foxr     2640: 
1.178.2.1  foxr     2641:    } else {
                   2642: 	# unknown command
                   2643:       Failure($client, "unknown_cmd\n", $userinput);
                   2644:    }
1.97      foxr     2645: 
1.178.2.1  foxr     2646:     return $KeepGoing;
                   2647: }
1.97      foxr     2648: 
1.96      foxr     2649: 
                   2650: #
1.140     foxr     2651: #   GetCertificate: Given a transaction that requires a certificate,
                   2652: #   this function will extract the certificate from the transaction
                   2653: #   request.  Note that at this point, the only concept of a certificate
                   2654: #   is the hostname to which we are connected.
                   2655: #
                   2656: #   Parameter:
                   2657: #      request   - The request sent by our client (this parameterization may
                   2658: #                  need to change when we really use a certificate granting
                   2659: #                  authority.
                   2660: #
                   2661: sub GetCertificate {
                   2662:     my $request = shift;
                   2663: 
                   2664:     return $clientip;
                   2665: }
1.161     foxr     2666: 
                   2667: 
                   2668: 
1.156     foxr     2669: #
                   2670: #   ReadManagerTable: Reads in the current manager table. For now this is
                   2671: #                     done on each manager authentication because:
                   2672: #                     - These authentications are not frequent
                   2673: #                     - This allows dynamic changes to the manager table
                   2674: #                       without the need to signal to the lond.
                   2675: #
                   2676: 
                   2677: sub ReadManagerTable {
                   2678: 
                   2679:     #   Clean out the old table first..
                   2680: 
1.166     foxr     2681:    foreach my $key (keys %managers) {
                   2682:       delete $managers{$key};
                   2683:    }
                   2684: 
                   2685:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                   2686:    if (!open (MANAGERS, $tablename)) {
                   2687:       logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                   2688:       return;
                   2689:    }
                   2690:    while(my $host = <MANAGERS>) {
                   2691:       chomp($host);
                   2692:       if ($host =~ "^#") {                  # Comment line.
                   2693:          logthis('<font color="green"> Skipping line: '. "$host</font>\n");
                   2694:          next;
                   2695:       }
                   2696:       if (!defined $hostip{$host}) { # This is a non cluster member
1.161     foxr     2697: 	    #  The entry is of the form:
                   2698: 	    #    cluname:hostname
                   2699: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                   2700: 	    #            the host key.
                   2701: 	    #  hostname- The dns name of the host.
                   2702: 	    #
1.166     foxr     2703:           my($cluname, $dnsname) = split(/:/, $host);
                   2704:           
                   2705:           my $ip = gethostbyname($dnsname);
                   2706:           if(defined($ip)) {                 # bad names don't deserve entry.
                   2707:             my $hostip = inet_ntoa($ip);
                   2708:             $managers{$hostip} = $cluname;
                   2709:             logthis('<font color="green"> registering manager '.
                   2710:                     "$dnsname as $cluname with $hostip </font>\n");
                   2711:          }
                   2712:       } else {
                   2713:          logthis('<font color="green"> existing host'." $host</font>\n");
                   2714:          $managers{$hostip{$host}} = $host;  # Use info from cluster tab if clumemeber
                   2715:       }
                   2716:    }
1.156     foxr     2717: }
1.140     foxr     2718: 
                   2719: #
                   2720: #  ValidManager: Determines if a given certificate represents a valid manager.
                   2721: #                in this primitive implementation, the 'certificate' is
                   2722: #                just the connecting loncapa client name.  This is checked
                   2723: #                against a valid client list in the configuration.
                   2724: #
                   2725: #                  
                   2726: sub ValidManager {
                   2727:     my $certificate = shift; 
                   2728: 
1.163     foxr     2729:     return isManager;
1.140     foxr     2730: }
                   2731: #
1.143     foxr     2732: #  CopyFile:  Called as part of the process of installing a 
                   2733: #             new configuration file.  This function copies an existing
                   2734: #             file to a backup file.
                   2735: # Parameters:
                   2736: #     oldfile  - Name of the file to backup.
                   2737: #     newfile  - Name of the backup file.
                   2738: # Return:
                   2739: #     0   - Failure (errno has failure reason).
                   2740: #     1   - Success.
                   2741: #
                   2742: sub CopyFile {
                   2743:     my $oldfile = shift;
                   2744:     my $newfile = shift;
                   2745: 
                   2746:     #  The file must exist:
                   2747: 
                   2748:     if(-e $oldfile) {
                   2749: 
                   2750: 	 # Read the old file.
                   2751: 
                   2752: 	my $oldfh = IO::File->new("< $oldfile");
                   2753: 	if(!$oldfh) {
                   2754: 	    return 0;
                   2755: 	}
                   2756: 	my @contents = <$oldfh>;  # Suck in the entire file.
                   2757: 
                   2758: 	# write the backup file:
                   2759: 
                   2760: 	my $newfh = IO::File->new("> $newfile");
                   2761: 	if(!(defined $newfh)){
                   2762: 	    return 0;
                   2763: 	}
                   2764: 	my $lines = scalar @contents;
                   2765: 	for (my $i =0; $i < $lines; $i++) {
                   2766: 	    print $newfh ($contents[$i]);
                   2767: 	}
                   2768: 
                   2769: 	$oldfh->close;
                   2770: 	$newfh->close;
                   2771: 
                   2772: 	chmod(0660, $newfile);
                   2773: 
                   2774: 	return 1;
                   2775: 	    
                   2776:     } else {
                   2777: 	return 0;
                   2778:     }
                   2779: }
1.157     foxr     2780: #
                   2781: #  Host files are passed out with externally visible host IPs.
                   2782: #  If, for example, we are behind a fire-wall or NAT host, our 
                   2783: #  internally visible IP may be different than the externally
                   2784: #  visible IP.  Therefore, we always adjust the contents of the
                   2785: #  host file so that the entry for ME is the IP that we believe
                   2786: #  we have.  At present, this is defined as the entry that
                   2787: #  DNS has for us.  If by some chance we are not able to get a
                   2788: #  DNS translation for us, then we assume that the host.tab file
                   2789: #  is correct.  
                   2790: #    BUGBUGBUG - in the future, we really should see if we can
                   2791: #       easily query the interface(s) instead.
                   2792: # Parameter(s):
                   2793: #     contents    - The contents of the host.tab to check.
                   2794: # Returns:
                   2795: #     newcontents - The adjusted contents.
                   2796: #
                   2797: #
                   2798: sub AdjustHostContents {
                   2799:     my $contents  = shift;
                   2800:     my $adjusted;
                   2801:     my $me        = $perlvar{'lonHostID'};
                   2802: 
1.166     foxr     2803:  foreach my $line (split(/\n/,$contents)) {
1.157     foxr     2804: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
                   2805: 	    chomp($line);
                   2806: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                   2807: 	    if ($id eq $me) {
1.166     foxr     2808:           my $ip = gethostbyname($name);
                   2809:           my $ipnew = inet_ntoa($ip);
                   2810:          $ip = $ipnew;
1.157     foxr     2811: 		#  Reconstruct the host line and append to adjusted:
                   2812: 		
1.166     foxr     2813: 		   my $newline = "$id:$domain:$role:$name:$ip";
                   2814: 		   if($maxcon ne "") { # Not all hosts have loncnew tuning params
                   2815: 		     $newline .= ":$maxcon:$idleto:$mincon";
                   2816: 		   }
                   2817: 		   $adjusted .= $newline."\n";
1.157     foxr     2818: 		
1.166     foxr     2819:       } else {		# Not me, pass unmodified.
                   2820: 		   $adjusted .= $line."\n";
                   2821:       }
1.157     foxr     2822: 	} else {                  # Blank or comment never re-written.
                   2823: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                   2824: 	}
1.166     foxr     2825:  }
                   2826:  return $adjusted;
1.157     foxr     2827: }
1.143     foxr     2828: #
                   2829: #   InstallFile: Called to install an administrative file:
                   2830: #       - The file is created with <name>.tmp
                   2831: #       - The <name>.tmp file is then mv'd to <name>
                   2832: #   This lugubrious procedure is done to ensure that we are never without
                   2833: #   a valid, even if dated, version of the file regardless of who crashes
                   2834: #   and when the crash occurs.
                   2835: #
                   2836: #  Parameters:
                   2837: #       Name of the file
                   2838: #       File Contents.
                   2839: #  Return:
                   2840: #      nonzero - success.
                   2841: #      0       - failure and $! has an errno.
                   2842: #
                   2843: sub InstallFile {
                   2844:     my $Filename = shift;
                   2845:     my $Contents = shift;
                   2846:     my $TempFile = $Filename.".tmp";
                   2847: 
                   2848:     #  Open the file for write:
                   2849: 
                   2850:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                   2851:     if(!(defined $fh)) {
                   2852: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                   2853: 	return 0;
                   2854:     }
                   2855:     #  write the contents of the file:
                   2856: 
                   2857:     print $fh ($Contents); 
                   2858:     $fh->close;			# In case we ever have a filesystem w. locking
                   2859: 
                   2860:     chmod(0660, $TempFile);
                   2861: 
                   2862:     # Now we can move install the file in position.
                   2863:     
                   2864:     move($TempFile, $Filename);
                   2865: 
                   2866:     return 1;
                   2867: }
1.169     foxr     2868: #
                   2869: #   ConfigFileFromSelector: converts a configuration file selector
                   2870: #                 (one of host or domain at this point) into a 
                   2871: #                 configuration file pathname.
                   2872: #
                   2873: #  Parameters:
                   2874: #      selector  - Configuration file selector.
                   2875: #  Returns:
                   2876: #      Full path to the file or undef if the selector is invalid.
                   2877: #
                   2878: sub ConfigFileFromSelector {
                   2879:     my $selector   = shift;
                   2880:     my $tablefile;
                   2881: 
                   2882:     my $tabledir = $perlvar{'lonTabDir'}.'/';
                   2883:     if ($selector eq "hosts") {
                   2884: 	$tablefile = $tabledir."hosts.tab";
                   2885:     } elsif ($selector eq "domain") {
                   2886: 	$tablefile = $tabledir."domain.tab";
                   2887:     } else {
                   2888: 	return undef;
                   2889:     }
                   2890:     return $tablefile;
1.143     foxr     2891: 
1.169     foxr     2892: }
1.143     foxr     2893: #
1.141     foxr     2894: #   PushFile:  Called to do an administrative push of a file.
                   2895: #              - Ensure the file being pushed is one we support.
                   2896: #              - Backup the old file to <filename.saved>
                   2897: #              - Separate the contents of the new file out from the
                   2898: #                rest of the request.
                   2899: #              - Write the new file.
                   2900: #  Parameter:
                   2901: #     Request - The entire user request.  This consists of a : separated
                   2902: #               string pushfile:tablename:contents.
                   2903: #     NOTE:  The contents may have :'s in it as well making things a bit
                   2904: #            more interesting... but not much.
                   2905: #  Returns:
                   2906: #     String to send to client ("ok" or "refused" if bad file).
                   2907: #
                   2908: sub PushFile {
                   2909:     my $request = shift;    
                   2910:     my ($command, $filename, $contents) = split(":", $request, 3);
                   2911:     
                   2912:     #  At this point in time, pushes for only the following tables are
                   2913:     #  supported:
                   2914:     #   hosts.tab  ($filename eq host).
                   2915:     #   domain.tab ($filename eq domain).
                   2916:     # Construct the destination filename or reject the request.
                   2917:     #
                   2918:     # lonManage is supposed to ensure this, however this session could be
                   2919:     # part of some elaborate spoof that managed somehow to authenticate.
                   2920:     #
                   2921: 
1.169     foxr     2922: 
                   2923:     my $tablefile = ConfigFileFromSelector($filename);
                   2924:     if(! (defined $tablefile)) {
1.141     foxr     2925: 	return "refused";
                   2926:     }
                   2927:     #
                   2928:     # >copy< the old table to the backup table
                   2929:     #        don't rename in case system crashes/reboots etc. in the time
                   2930:     #        window between a rename and write.
                   2931:     #
                   2932:     my $backupfile = $tablefile;
                   2933:     $backupfile    =~ s/\.tab$/.old/;
1.143     foxr     2934:     if(!CopyFile($tablefile, $backupfile)) {
                   2935: 	&logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
                   2936: 	return "error:$!";
                   2937:     }
1.141     foxr     2938:     &logthis('<font color="green"> Pushfile: backed up '
                   2939: 	    .$tablefile." to $backupfile</font>");
                   2940:     
1.157     foxr     2941:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                   2942:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                   2943:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                   2944:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                   2945:     #  that possibilty.
                   2946: 
                   2947:     if($filename eq "host") {
                   2948: 	$contents = AdjustHostContents($contents);
                   2949:     }
                   2950: 
1.141     foxr     2951:     #  Install the new file:
                   2952: 
1.143     foxr     2953:     if(!InstallFile($tablefile, $contents)) {
                   2954: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr     2955: 	 .$tablefile." $! </font>");
1.143     foxr     2956: 	return "error:$!";
                   2957:     }
                   2958:     else {
                   2959: 	&logthis('<font color="green"> Installed new '.$tablefile
                   2960: 		 ."</font>");
                   2961: 
                   2962:     }
                   2963: 
1.141     foxr     2964: 
                   2965:     #  Indicate success:
                   2966:  
                   2967:     return "ok";
                   2968: 
                   2969: }
1.145     foxr     2970: 
                   2971: #
                   2972: #  Called to re-init either lonc or lond.
                   2973: #
                   2974: #  Parameters:
                   2975: #    request   - The full request by the client.  This is of the form
                   2976: #                reinit:<process>  
                   2977: #                where <process> is allowed to be either of 
                   2978: #                lonc or lond
                   2979: #
                   2980: #  Returns:
                   2981: #     The string to be sent back to the client either:
                   2982: #   ok         - Everything worked just fine.
                   2983: #   error:why  - There was a failure and why describes the reason.
                   2984: #
                   2985: #
                   2986: sub ReinitProcess {
                   2987:     my $request = shift;
                   2988: 
1.146     foxr     2989: 
                   2990:     # separate the request (reinit) from the process identifier and
                   2991:     # validate it producing the name of the .pid file for the process.
                   2992:     #
                   2993:     #
                   2994:     my ($junk, $process) = split(":", $request);
1.147     foxr     2995:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr     2996:     if($process eq 'lonc') {
                   2997: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr     2998: 	if (!open(PIDFILE, "< $processpidfile")) {
                   2999: 	    return "error:Open failed for $processpidfile";
                   3000: 	}
                   3001: 	my $loncpid = <PIDFILE>;
                   3002: 	close(PIDFILE);
                   3003: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                   3004: 		."</font>");
                   3005: 	kill("USR2", $loncpid);
1.146     foxr     3006:     } elsif ($process eq 'lond') {
1.147     foxr     3007: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                   3008: 	&UpdateHosts;			# Lond is us!!
1.146     foxr     3009:     } else {
                   3010: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                   3011: 		 ."</font>");
                   3012: 	return "error:Invalid process identifier $process";
                   3013:     }
1.145     foxr     3014:     return 'ok';
                   3015: }
1.168     foxr     3016: #   Validate a line in a configuration file edit script:
                   3017: #   Validation includes:
                   3018: #     - Ensuring the command is valid.
                   3019: #     - Ensuring the command has sufficient parameters
                   3020: #   Parameters:
                   3021: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr     3022: #
1.168     foxr     3023: #   Return:
                   3024: #      0     - Invalid scriptline.
                   3025: #      1     - Valid scriptline
                   3026: #  NOTE:
                   3027: #     Only the command syntax is checked, not the executability of the
                   3028: #     command.
                   3029: #
                   3030: sub isValidEditCommand {
                   3031:     my $scriptline = shift;
                   3032: 
                   3033:     #   Line elements are pipe separated:
                   3034: 
                   3035:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   3036:     &logthis('<font color="green"> isValideditCommand checking: '.
                   3037: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   3038:     
                   3039:     if ($command eq "delete") {
                   3040: 	#
                   3041: 	#   key with no newline.
                   3042: 	#
                   3043: 	if( ($key eq "") || ($newline ne "")) {
                   3044: 	    return 0;		# Must have key but no newline.
                   3045: 	} else {
                   3046: 	    return 1;		# Valid syntax.
                   3047: 	}
1.169     foxr     3048:     } elsif ($command eq "replace") {
1.168     foxr     3049: 	#
                   3050: 	#   key and newline:
                   3051: 	#
                   3052: 	if (($key eq "") || ($newline eq "")) {
                   3053: 	    return 0;
                   3054: 	} else {
                   3055: 	    return 1;
                   3056: 	}
1.169     foxr     3057:     } elsif ($command eq "append") {
                   3058: 	if (($key ne "") && ($newline eq "")) {
                   3059: 	    return 1;
                   3060: 	} else {
                   3061: 	    return 0;
                   3062: 	}
1.168     foxr     3063:     } else {
                   3064: 	return 0;		# Invalid command.
                   3065:     }
                   3066:     return 0;			# Should not get here!!!
                   3067: }
1.169     foxr     3068: #
                   3069: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   3070: #               file.  It is the caller's responsiblity to validate the
                   3071: #               edit line.
                   3072: #   Parameters:
                   3073: #      $directive - A single edit directive to apply.  
                   3074: #                   Edit directives are of the form:
                   3075: #                  append|newline      - Appends a new line to the file.
                   3076: #                  replace|key|newline - Replaces the line with key value 'key'
                   3077: #                  delete|key          - Deletes the line with key value 'key'.
                   3078: #      $editor   - A config file editor object that contains the
                   3079: #                  file being edited.
                   3080: #
                   3081: sub ApplyEdit {
                   3082:     my $directive   = shift;
                   3083:     my $editor      = shift;
                   3084: 
                   3085:     # Break the directive down into its command and its parameters
                   3086:     # (at most two at this point.  The meaning of the parameters, if in fact
                   3087:     #  they exist depends on the command).
                   3088: 
                   3089:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   3090: 
                   3091:     if($command eq "append") {
                   3092: 	$editor->Append($p1);	          # p1 - key p2 null.
                   3093:     } elsif ($command eq "replace") {
                   3094: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   3095:     } elsif ($command eq "delete") {
                   3096: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   3097:     } else {			          # Should not get here!!!
                   3098: 	die "Invalid command given to ApplyEdit $command"
                   3099:     }
                   3100: }
                   3101: #
                   3102: # AdjustOurHost:
                   3103: #           Adjusts a host file stored in a configuration file editor object
                   3104: #           for the true IP address of this host. This is necessary for hosts
                   3105: #           that live behind a firewall.
                   3106: #           Those hosts have a publicly distributed IP of the firewall, but
                   3107: #           internally must use their actual IP.  We assume that a given
                   3108: #           host only has a single IP interface for now.
                   3109: # Formal Parameters:
                   3110: #     editor   - The configuration file editor to adjust.  This
                   3111: #                editor is assumed to contain a hosts.tab file.
                   3112: # Strategy:
                   3113: #    - Figure out our hostname.
                   3114: #    - Lookup the entry for this host.
                   3115: #    - Modify the line to contain our IP
                   3116: #    - Do a replace for this host.
                   3117: sub AdjustOurHost {
                   3118:     my $editor        = shift;
                   3119: 
                   3120:     # figure out who I am.
                   3121: 
                   3122:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   3123: 
                   3124:     #  Get my host file entry.
                   3125: 
                   3126:     my $ConfigLine    = $editor->Find($myHostName);
                   3127:     if(! (defined $ConfigLine)) {
                   3128: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   3129:     }
                   3130:     # figure out my IP:
                   3131:     #   Use the config line to get my hostname.
                   3132:     #   Use gethostbyname to translate that into an IP address.
                   3133:     #
                   3134:     my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
                   3135:     my $BinaryIp = gethostbyname($name);
                   3136:     my $ip       = inet_ntoa($ip);
                   3137:     #
                   3138:     #  Reassemble the config line from the elements in the list.
                   3139:     #  Note that if the loncnew items were not present before, they will
                   3140:     #  be now even if they would be empty
                   3141:     #
                   3142:     my $newConfigLine = $id;
                   3143:     foreach my $item ($domain, $role, $name, $ip, $maxcon, $idleto, $mincon) {
                   3144: 	$newConfigLine .= ":".$item;
                   3145:     }
                   3146:     #  Replace the line:
                   3147: 
                   3148:     $editor->ReplaceLine($id, $newConfigLine);
                   3149:     
                   3150: }
                   3151: #
                   3152: #   ReplaceConfigFile:
                   3153: #              Replaces a configuration file with the contents of a
                   3154: #              configuration file editor object.
                   3155: #              This is done by:
                   3156: #              - Copying the target file to <filename>.old
                   3157: #              - Writing the new file to <filename>.tmp
                   3158: #              - Moving <filename.tmp>  -> <filename>
                   3159: #              This laborious process ensures that the system is never without
                   3160: #              a configuration file that's at least valid (even if the contents
                   3161: #              may be dated).
                   3162: #   Parameters:
                   3163: #        filename   - Name of the file to modify... this is a full path.
                   3164: #        editor     - Editor containing the file.
                   3165: #
                   3166: sub ReplaceConfigFile {
                   3167:     my $filename  = shift;
                   3168:     my $editor    = shift;
1.168     foxr     3169: 
1.169     foxr     3170:     CopyFile ($filename, $filename.".old");
                   3171: 
                   3172:     my $contents  = $editor->Get(); # Get the contents of the file.
                   3173: 
                   3174:     InstallFile($filename, $contents);
                   3175: }
1.168     foxr     3176: #   
                   3177: #
                   3178: #   Called to edit a configuration table  file
1.167     foxr     3179: #   Parameters:
                   3180: #      request           - The entire command/request sent by lonc or lonManage
                   3181: #   Return:
                   3182: #      The reply to send to the client.
1.168     foxr     3183: #
1.167     foxr     3184: sub EditFile {
                   3185:     my $request = shift;
                   3186: 
                   3187:     #  Split the command into it's pieces:  edit:filetype:script
                   3188: 
1.168     foxr     3189:     my ($request, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     3190: 
                   3191:     #  Check the pre-coditions for success:
                   3192: 
                   3193:     if($request != "edit") {	# Something is amiss afoot alack.
                   3194: 	return "error:edit request detected, but request != 'edit'\n";
                   3195:     }
                   3196:     if( ($filetype ne "hosts")  &&
                   3197: 	($filetype ne "domain")) {
                   3198: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   3199:     }
                   3200: 
                   3201:     #   Split the edit script and check it's validity.
1.168     foxr     3202: 
                   3203:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   3204:     my $linecount   = scalar(@scriptlines);
                   3205:     for(my $i = 0; $i < $linecount; $i++) {
                   3206: 	chomp($scriptlines[$i]);
                   3207: 	if(!isValidEditCommand($scriptlines[$i])) {
                   3208: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   3209: 	}
                   3210:     }
1.145     foxr     3211: 
1.167     foxr     3212:     #   Execute the edit operation.
1.169     foxr     3213:     #   - Create a config file editor for the appropriate file and 
                   3214:     #   - execute each command in the script:
                   3215:     #
                   3216:     my $configfile = ConfigFileFromSelector($filetype);
                   3217:     if (!(defined $configfile)) {
                   3218: 	return "refused\n";
                   3219:     }
                   3220:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     3221: 
1.169     foxr     3222:     for (my $i = 0; $i < $linecount; $i++) {
                   3223: 	ApplyEdit($scriptlines[$i], $editor);
                   3224:     }
                   3225:     # If the file is the host file, ensure that our host is
                   3226:     # adjusted to have our ip:
                   3227:     #
                   3228:     if($filetype eq "host") {
                   3229: 	AdjustOurHost($editor);
                   3230:     }
                   3231:     #  Finally replace the current file with our file.
                   3232:     #
                   3233:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     3234: 
                   3235:     return "ok\n";
                   3236: }
1.141     foxr     3237: #
1.96      foxr     3238: #  Convert an error return code from lcpasswd to a string value.
                   3239: #
                   3240: sub lcpasswdstrerror {
                   3241:     my $ErrorCode = shift;
1.97      foxr     3242:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     3243: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   3244:     } else {
1.98      foxr     3245: 	return $passwderrors[$ErrorCode];
1.96      foxr     3246:     }
                   3247: }
                   3248: 
1.97      foxr     3249: #
                   3250: # Convert an error return code from lcuseradd to a string value:
                   3251: #
                   3252: sub lcuseraddstrerror {
                   3253:     my $ErrorCode = shift;
                   3254:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
                   3255: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
                   3256:     } else {
1.98      foxr     3257: 	return $adderrors[$ErrorCode];
1.97      foxr     3258:     }
                   3259: }
                   3260: 
1.23      harris41 3261: # grabs exception and records it to log before exiting
                   3262: sub catchexception {
1.27      albertel 3263:     my ($error)=@_;
1.25      www      3264:     $SIG{'QUIT'}='DEFAULT';
                   3265:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 3266:     &status("Catching exception");
1.23      harris41 3267:     &logthis("<font color=red>CRITICAL: "
1.134     albertel 3268:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27      albertel 3269:      ."a crash with this error msg->[$error]</font>");
1.57      www      3270:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 3271:     if ($client) { print $client "error: $error\n"; }
1.59      www      3272:     $server->close();
1.27      albertel 3273:     die($error);
1.23      harris41 3274: }
                   3275: 
1.63      www      3276: sub timeout {
1.165     albertel 3277:     &status("Handling Timeout");
1.63      www      3278:     &logthis("<font color=ref>CRITICAL: TIME OUT ".$$."</font>");
                   3279:     &catchexception('Timeout');
                   3280: }
1.22      harris41 3281: # -------------------------------- Set signal handlers to record abnormal exits
                   3282: 
                   3283: $SIG{'QUIT'}=\&catchexception;
                   3284: $SIG{__DIE__}=\&catchexception;
                   3285: 
1.81      matthew  3286: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 3287: &status("Read loncapa.conf and loncapa_apache.conf");
                   3288: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     3289: %perlvar=%{$perlvarref};
1.80      harris41 3290: undef $perlvarref;
1.19      www      3291: 
1.35      harris41 3292: # ----------------------------- Make sure this process is running from user=www
                   3293: my $wwwid=getpwnam('www');
                   3294: if ($wwwid!=$<) {
1.134     albertel 3295:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   3296:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 3297:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 3298:  mailto $emailto -s '$subj' > /dev/null");
                   3299:    exit 1;
                   3300: }
                   3301: 
1.19      www      3302: # --------------------------------------------- Check if other instance running
                   3303: 
                   3304: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   3305: 
                   3306: if (-e $pidfile) {
                   3307:    my $lfh=IO::File->new("$pidfile");
                   3308:    my $pide=<$lfh>;
                   3309:    chomp($pide);
1.29      harris41 3310:    if (kill 0 => $pide) { die "already running"; }
1.19      www      3311: }
1.1       albertel 3312: 
                   3313: # ------------------------------------------------------------- Read hosts file
                   3314: 
                   3315: 
                   3316: 
                   3317: # establish SERVER socket, bind and listen.
                   3318: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   3319:                                 Type      => SOCK_STREAM,
                   3320:                                 Proto     => 'tcp',
                   3321:                                 Reuse     => 1,
                   3322:                                 Listen    => 10 )
1.29      harris41 3323:   or die "making socket: $@\n";
1.1       albertel 3324: 
                   3325: # --------------------------------------------------------- Do global variables
                   3326: 
                   3327: # global variables
                   3328: 
1.134     albertel 3329: my %children               = ();       # keys are current child process IDs
1.178.2.1  foxr     3330: my $children               = 0;        # current number of children
1.1       albertel 3331: 
                   3332: sub REAPER {                        # takes care of dead children
                   3333:     $SIG{CHLD} = \&REAPER;
1.165     albertel 3334:     &status("Handling child death");
1.178.2.1  foxr     3335:     my $pid = wait;
                   3336:     if (defined($children{$pid})) {
                   3337: 	&logthis("Child $pid died");
                   3338: 	$children --;
                   3339: 	delete $children{$pid};
                   3340:     } else {
                   3341: 	&logthis("Unknown Child $pid died");
1.176     albertel 3342:     }
1.165     albertel 3343:     &status("Finished Handling child death");
1.1       albertel 3344: }
                   3345: 
                   3346: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 3347:     &status("Killing children (INT)");
1.1       albertel 3348:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   3349:     kill 'INT' => keys %children;
1.59      www      3350:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 3351:     my $execdir=$perlvar{'lonDaemons'};
                   3352:     unlink("$execdir/logs/lond.pid");
1.9       www      3353:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
1.165     albertel 3354:     &status("Done killing children");
1.1       albertel 3355:     exit;                           # clean up with dignity
                   3356: }
                   3357: 
                   3358: sub HUPSMAN {                      # signal handler for SIGHUP
                   3359:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 3360:     &status("Killing children for restart (HUP)");
1.1       albertel 3361:     kill 'INT' => keys %children;
1.59      www      3362:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.9       www      3363:     &logthis("<font color=red>CRITICAL: Restarting</font>");
1.134     albertel 3364:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 3365:     unlink("$execdir/logs/lond.pid");
1.165     albertel 3366:     &status("Restarting self (HUP)");
1.1       albertel 3367:     exec("$execdir/lond");         # here we go again
                   3368: }
                   3369: 
1.144     foxr     3370: #
1.148     foxr     3371: #    Kill off hashes that describe the host table prior to re-reading it.
                   3372: #    Hashes affected are:
                   3373: #       %hostid, %hostdom %hostip
                   3374: #
                   3375: sub KillHostHashes {
                   3376:     foreach my $key (keys %hostid) {
                   3377: 	delete $hostid{$key};
                   3378:     }
                   3379:     foreach my $key (keys %hostdom) {
                   3380: 	delete $hostdom{$key};
                   3381:     }
                   3382:     foreach my $key (keys %hostip) {
                   3383: 	delete $hostip{$key};
                   3384:     }
                   3385: }
                   3386: #
                   3387: #   Read in the host table from file and distribute it into the various hashes:
                   3388: #
                   3389: #    - %hostid  -  Indexed by IP, the loncapa hostname.
                   3390: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
                   3391: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
                   3392: sub ReadHostTable {
                   3393: 
                   3394:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
                   3395:     
                   3396:     while (my $configline=<CONFIG>) {
1.178.2.1  foxr     3397: 	my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                   3398: 	chomp($ip); $ip=~s/\D+$//;
                   3399: 	$hostid{$ip}=$id;
                   3400: 	$hostdom{$id}=$domain;
                   3401: 	$hostip{$id}=$ip;
                   3402: 	if ($id eq $perlvar{'lonHostID'}) { $thisserver=$name; }
1.148     foxr     3403:     }
                   3404:     close(CONFIG);
                   3405: }
                   3406: #
                   3407: #  Reload the Apache daemon's state.
1.150     foxr     3408: #  This is done by invoking /home/httpd/perl/apachereload
                   3409: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     3410: #
                   3411: sub ReloadApache {
1.150     foxr     3412:     my $execdir = $perlvar{'lonDaemons'};
                   3413:     my $script  = $execdir."/apachereload";
                   3414:     system($script);
1.148     foxr     3415: }
                   3416: 
                   3417: #
1.144     foxr     3418: #   Called in response to a USR2 signal.
                   3419: #   - Reread hosts.tab
                   3420: #   - All children connected to hosts that were removed from hosts.tab
                   3421: #     are killed via SIGINT
                   3422: #   - All children connected to previously existing hosts are sent SIGUSR1
                   3423: #   - Our internal hosts hash is updated to reflect the new contents of
                   3424: #     hosts.tab causing connections from hosts added to hosts.tab to
                   3425: #     now be honored.
                   3426: #
                   3427: sub UpdateHosts {
1.165     albertel 3428:     &status("Reload hosts.tab");
1.147     foxr     3429:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     3430:     #
                   3431:     #  The %children hash has the set of IP's we currently have children
                   3432:     #  on.  These need to be matched against records in the hosts.tab
                   3433:     #  Any ip's no longer in the table get killed off they correspond to
                   3434:     #  either dropped or changed hosts.  Note that the re-read of the table
                   3435:     #  will take care of new and changed hosts as connections come into being.
                   3436: 
                   3437: 
                   3438:     KillHostHashes;
                   3439:     ReadHostTable;
                   3440: 
                   3441:     foreach my $child (keys %children) {
                   3442: 	my $childip = $children{$child};
                   3443: 	if(!$hostid{$childip}) {
1.149     foxr     3444: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   3445: 		    ." $child for ip $childip </font>");
1.148     foxr     3446: 	    kill('INT', $child);
1.149     foxr     3447: 	} else {
                   3448: 	    logthis('<font color="green"> keeping child for ip '
                   3449: 		    ." $childip (pid=$child) </font>");
1.148     foxr     3450: 	}
                   3451:     }
                   3452:     ReloadApache;
1.165     albertel 3453:     &status("Finished reloading hosts.tab");
1.144     foxr     3454: }
                   3455: 
1.148     foxr     3456: 
1.57      www      3457: sub checkchildren {
1.165     albertel 3458:     &status("Checking on the children (sending signals)");
1.57      www      3459:     &initnewstatus();
                   3460:     &logstatus();
                   3461:     &logthis('Going to check on the children');
1.134     albertel 3462:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 3463:     foreach (sort keys %children) {
1.57      www      3464: 	sleep 1;
                   3465:         unless (kill 'USR1' => $_) {
                   3466: 	    &logthis ('Child '.$_.' is dead');
                   3467:             &logstatus($$.' is dead');
                   3468:         } 
1.61      harris41 3469:     }
1.63      www      3470:     sleep 5;
1.113     albertel 3471:     $SIG{ALRM} = sub { die "timeout" };
                   3472:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 3473:     &status("Checking on the children (waiting for reports)");
1.63      www      3474:     foreach (sort keys %children) {
                   3475:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 3476:           eval {
                   3477:             alarm(300);
1.63      www      3478: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 3479: 	    kill 9 => $_;
1.131     albertel 3480: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   3481: 	    #$subj="LON: $currenthostid killed lond process $_";
                   3482: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   3483: 	    #$execdir=$perlvar{'lonDaemons'};
                   3484: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.113     albertel 3485: 	    alarm(0);
                   3486: 	  }
1.63      www      3487:         }
                   3488:     }
1.113     albertel 3489:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 3490:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 3491:     &status("Finished checking children");
1.57      www      3492: }
                   3493: 
1.1       albertel 3494: # --------------------------------------------------------------------- Logging
                   3495: 
                   3496: sub logthis {
                   3497:     my $message=shift;
                   3498:     my $execdir=$perlvar{'lonDaemons'};
                   3499:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   3500:     my $now=time;
                   3501:     my $local=localtime($now);
1.58      www      3502:     $lastlog=$local.': '.$message;
1.1       albertel 3503:     print $fh "$local ($$): $message\n";
                   3504: }
                   3505: 
1.77      foxr     3506: # ------------------------- Conditional log if $DEBUG true.
                   3507: sub Debug {
                   3508:     my $message = shift;
                   3509:     if($DEBUG) {
                   3510: 	&logthis($message);
                   3511:     }
                   3512: }
1.161     foxr     3513: 
                   3514: #
                   3515: #   Sub to do replies to client.. this gives a hook for some
                   3516: #   debug tracing too:
                   3517: #  Parameters:
                   3518: #     fd      - File open on client.
                   3519: #     reply   - Text to send to client.
                   3520: #     request - Original request from client.
                   3521: #
1.178.2.1  foxr     3522: #  Note: This increments Transactions
                   3523: #
1.161     foxr     3524: sub Reply {
1.178.2.1  foxr     3525:     alarm(120);
1.161     foxr     3526:     my $fd      = shift;
                   3527:     my $reply   = shift;
                   3528:     my $request = shift;
                   3529: 
                   3530:     print $fd $reply;
                   3531:     Debug("Request was $request  Reply was $reply");
                   3532: 
1.178.2.1  foxr     3533:     $Transactions++;
                   3534:     alarm(0);
                   3535: 
                   3536: 
                   3537: }
                   3538: #
                   3539: #    Sub to report a failure.
                   3540: #    This function:
                   3541: #     -   Increments the failure statistic counters.
                   3542: #     -   Invokes Reply to send the error message to the client.
                   3543: # Parameters:
                   3544: #    fd       - File descriptor open on the client
                   3545: #    reply    - Reply text to emit.
                   3546: #    request  - The original request message (used by Reply
                   3547: #               to debug if that's enabled.
                   3548: # Implicit outputs:
                   3549: #    $Failures- The number of failures is incremented.
                   3550: #    Reply (invoked here) sends a message to the 
                   3551: #    client:
                   3552: #
                   3553: sub Failure {
                   3554:    my $fd      = shift;
                   3555:    my $reply   = shift;
                   3556:    my $request = shift;
                   3557:    
                   3558:    $Failures++;
                   3559:    Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     3560: }
1.57      www      3561: # ------------------------------------------------------------------ Log status
                   3562: 
                   3563: sub logstatus {
1.178.2.1  foxr     3564:    &status("Doing logging");
                   3565:    my $docdir=$perlvar{'lonDocRoot'};
                   3566:    {
                   3567:       my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
                   3568:       print $fh $$."\t".$currenthostid."\t".$status."\t".$lastlog."\n";
                   3569:       $fh->close();
                   3570:    }
                   3571:    &status("Finished londstatus.txt");
                   3572:    {
                   3573:       my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
                   3574:       print $fh $status."\n".$lastlog."\n".time;
                   3575:       $fh->close();
                   3576:    }
                   3577:    ResetStatistics;
                   3578:    &status("Finished logging");
                   3579:    
1.57      www      3580: }
                   3581: 
                   3582: sub initnewstatus {
                   3583:     my $docdir=$perlvar{'lonDocRoot'};
                   3584:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
                   3585:     my $now=time;
                   3586:     my $local=localtime($now);
                   3587:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      3588:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 3589:     while (my $filename=readdir(DIR)) {
1.64      www      3590:         unlink("$docdir/lon-status/londchld/$filename");
                   3591:     }
                   3592:     closedir(DIR);
1.57      www      3593: }
                   3594: 
                   3595: # -------------------------------------------------------------- Status setting
                   3596: 
                   3597: sub status {
                   3598:     my $what=shift;
                   3599:     my $now=time;
                   3600:     my $local=localtime($now);
1.178.2.1  foxr     3601:     my $status = "lond: $what $local ";
                   3602:     if($Transactions) {
                   3603:        $status .= " Transactions: $Transactions Failed; $Failures";
                   3604:     }
                   3605:     $0=$status;
1.57      www      3606: }
1.11      www      3607: 
                   3608: # -------------------------------------------------------- Escape Special Chars
                   3609: 
                   3610: sub escape {
                   3611:     my $str=shift;
                   3612:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   3613:     return $str;
                   3614: }
                   3615: 
                   3616: # ----------------------------------------------------- Un-Escape Special Chars
                   3617: 
                   3618: sub unescape {
                   3619:     my $str=shift;
                   3620:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   3621:     return $str;
                   3622: }
                   3623: 
1.1       albertel 3624: # ----------------------------------------------------------- Send USR1 to lonc
                   3625: 
                   3626: sub reconlonc {
                   3627:     my $peerfile=shift;
                   3628:     &logthis("Trying to reconnect for $peerfile");
                   3629:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                   3630:     if (my $fh=IO::File->new("$loncfile")) {
                   3631: 	my $loncpid=<$fh>;
                   3632:         chomp($loncpid);
                   3633:         if (kill 0 => $loncpid) {
                   3634: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                   3635:             kill USR1 => $loncpid;
                   3636:         } else {
1.9       www      3637: 	    &logthis(
                   3638:               "<font color=red>CRITICAL: "
                   3639:              ."lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel 3640:         }
                   3641:     } else {
1.9       www      3642:       &logthis('<font color=red>CRITICAL: lonc not running, giving up</font>');
1.1       albertel 3643:     }
                   3644: }
                   3645: 
                   3646: # -------------------------------------------------- Non-critical communication
1.11      www      3647: 
1.1       albertel 3648: sub subreply {
                   3649:     my ($cmd,$server)=@_;
                   3650:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                   3651:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   3652:                                       Type    => SOCK_STREAM,
                   3653:                                       Timeout => 10)
                   3654:        or return "con_lost";
                   3655:     print $sclient "$cmd\n";
                   3656:     my $answer=<$sclient>;
                   3657:     chomp($answer);
                   3658:     if (!$answer) { $answer="con_lost"; }
                   3659:     return $answer;
                   3660: }
                   3661: 
                   3662: sub reply {
                   3663:   my ($cmd,$server)=@_;
                   3664:   my $answer;
1.115     albertel 3665:   if ($server ne $currenthostid) { 
1.1       albertel 3666:     $answer=subreply($cmd,$server);
                   3667:     if ($answer eq 'con_lost') {
                   3668: 	$answer=subreply("ping",$server);
                   3669:         if ($answer ne $server) {
1.115     albertel 3670: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1       albertel 3671:            &reconlonc("$perlvar{'lonSockDir'}/$server");
                   3672:         }
                   3673:         $answer=subreply($cmd,$server);
                   3674:     }
                   3675:   } else {
                   3676:     $answer='self_reply';
                   3677:   } 
                   3678:   return $answer;
                   3679: }
                   3680: 
1.13      www      3681: # -------------------------------------------------------------- Talk to lonsql
                   3682: 
1.12      harris41 3683: sub sqlreply {
                   3684:     my ($cmd)=@_;
                   3685:     my $answer=subsqlreply($cmd);
                   3686:     if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
                   3687:     return $answer;
                   3688: }
                   3689: 
                   3690: sub subsqlreply {
                   3691:     my ($cmd)=@_;
                   3692:     my $unixsock="mysqlsock";
                   3693:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   3694:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   3695:                                       Type    => SOCK_STREAM,
                   3696:                                       Timeout => 10)
                   3697:        or return "con_lost";
                   3698:     print $sclient "$cmd\n";
                   3699:     my $answer=<$sclient>;
                   3700:     chomp($answer);
                   3701:     if (!$answer) { $answer="con_lost"; }
                   3702:     return $answer;
                   3703: }
                   3704: 
1.1       albertel 3705: # -------------------------------------------- Return path to profile directory
1.11      www      3706: 
1.1       albertel 3707: sub propath {
                   3708:     my ($udom,$uname)=@_;
                   3709:     $udom=~s/\W//g;
                   3710:     $uname=~s/\W//g;
1.16      www      3711:     my $subdir=$uname.'__';
1.1       albertel 3712:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   3713:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   3714:     return $proname;
                   3715: } 
                   3716: 
                   3717: # --------------------------------------- Is this the home server of an author?
1.11      www      3718: 
1.1       albertel 3719: sub ishome {
                   3720:     my $author=shift;
                   3721:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3722:     my ($udom,$uname)=split(/\//,$author);
                   3723:     my $proname=propath($udom,$uname);
                   3724:     if (-e $proname) {
                   3725: 	return 'owner';
                   3726:     } else {
                   3727:         return 'not_owner';
                   3728:     }
                   3729: }
                   3730: 
                   3731: # ======================================================= Continue main program
                   3732: # ---------------------------------------------------- Fork once and dissociate
                   3733: 
1.134     albertel 3734: my $fpid=fork;
1.1       albertel 3735: exit if $fpid;
1.29      harris41 3736: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 3737: 
1.29      harris41 3738: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 3739: 
                   3740: # ------------------------------------------------------- Write our PID on disk
                   3741: 
1.134     albertel 3742: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 3743: open (PIDSAVE,">$execdir/logs/lond.pid");
                   3744: print PIDSAVE "$$\n";
                   3745: close(PIDSAVE);
1.9       www      3746: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
1.57      www      3747: &status('Starting');
1.1       albertel 3748: 
1.106     foxr     3749: 
1.1       albertel 3750: 
                   3751: # ----------------------------------------------------- Install signal handlers
                   3752: 
1.57      www      3753: 
1.1       albertel 3754: $SIG{CHLD} = \&REAPER;
                   3755: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   3756: $SIG{HUP}  = \&HUPSMAN;
1.57      www      3757: $SIG{USR1} = \&checkchildren;
1.144     foxr     3758: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     3759: 
1.148     foxr     3760: #  Read the host hashes:
                   3761: 
                   3762: ReadHostTable;
1.106     foxr     3763: 
1.178.2.1  foxr     3764: 
1.106     foxr     3765: # --------------------------------------------------------------
                   3766: #   Accept connections.  When a connection comes in, it is validated
                   3767: #   and if good, a child process is created to process transactions
                   3768: #   along the connection.
                   3769: 
1.1       albertel 3770: while (1) {
1.165     albertel 3771:     &status('Starting accept');
1.106     foxr     3772:     $client = $server->accept() or next;
1.165     albertel 3773:     &status('Accepted '.$client.' off to spawn');
1.106     foxr     3774:     make_new_child($client);
1.165     albertel 3775:     &status('Finished spawning');
1.1       albertel 3776: }
                   3777: 
                   3778: sub make_new_child {
                   3779:     my $pid;
                   3780:     my $sigset;
1.106     foxr     3781: 
                   3782:     $client = shift;
1.165     albertel 3783:     &status('Starting new child '.$client);
1.161     foxr     3784:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   3785: 	     ")</font>");    
1.1       albertel 3786:     # block signal for fork
                   3787:     $sigset = POSIX::SigSet->new(SIGINT);
                   3788:     sigprocmask(SIG_BLOCK, $sigset)
1.29      harris41 3789:         or die "Can't block SIGINT for fork: $!\n";
1.134     albertel 3790: 
1.29      harris41 3791:     die "fork: $!" unless defined ($pid = fork);
1.148     foxr     3792: 
                   3793:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   3794: 	                               # connection liveness.
                   3795: 
                   3796:     #
                   3797:     #  Figure out who we're talking to so we can record the peer in 
                   3798:     #  the pid hash.
                   3799:     #
                   3800:     my $caller = getpeername($client);
                   3801:     my ($port,$iaddr)=unpack_sockaddr_in($caller);
                   3802:     $clientip=inet_ntoa($iaddr);
1.1       albertel 3803:     
                   3804:     if ($pid) {
                   3805:         # Parent records the child's birth and returns.
                   3806:         sigprocmask(SIG_UNBLOCK, $sigset)
1.29      harris41 3807:             or die "Can't unblock SIGINT for fork: $!\n";
1.148     foxr     3808:         $children{$pid} = $clientip;
1.178.2.1  foxr     3809:         $children++;
1.57      www      3810:         &status('Started child '.$pid);
1.1       albertel 3811:         return;
                   3812:     } else {
                   3813:         # Child can *not* return from this subroutine.
                   3814:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
1.126     albertel 3815:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   3816:                                 #don't get intercepted
1.57      www      3817:         $SIG{USR1}= \&logstatus;
1.63      www      3818:         $SIG{ALRM}= \&timeout;
1.57      www      3819:         $lastlog='Forked ';
                   3820:         $status='Forked';
                   3821: 
1.1       albertel 3822:         # unblock signals
                   3823:         sigprocmask(SIG_UNBLOCK, $sigset)
1.29      harris41 3824:             or die "Can't unblock SIGINT for fork: $!\n";
1.13      www      3825: 
1.178.2.1  foxr     3826: 
                   3827: 	
1.91      albertel 3828:         &Authen::Krb5::init_context();
                   3829:         &Authen::Krb5::init_ets();
                   3830: 
1.161     foxr     3831: 	&status('Accepted connection');
1.1       albertel 3832: # =============================================================================
                   3833:             # do something with the connection
                   3834: # -----------------------------------------------------------------------------
1.148     foxr     3835: 	# see if we know client and check for spoof IP by challenge
                   3836: 
1.161     foxr     3837: 	ReadManagerTable;	# May also be a manager!!
                   3838: 	
                   3839: 	my $clientrec=($hostid{$clientip}     ne undef);
                   3840: 	my $ismanager=($managers{$clientip}    ne undef);
                   3841: 	$clientname  = "[unknonwn]";
                   3842: 	if($clientrec) {	# Establish client type.
                   3843: 	    $ConnectionType = "client";
                   3844: 	    $clientname = $hostid{$clientip};
                   3845: 	    if($ismanager) {
                   3846: 		$ConnectionType = "both";
                   3847: 	    }
                   3848: 	} else {
                   3849: 	    $ConnectionType = "manager";
                   3850: 	    $clientname = $managers{$clientip};
                   3851: 	}
                   3852: 	my $clientok;
                   3853: 	if ($clientrec || $ismanager) {
                   3854: 	    &status("Waiting for init from $clientip $clientname");
                   3855: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   3856: 		     $clientip.
                   3857: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   3858: 	    &status("Connecting $clientip  ($clientname))"); 
                   3859: 	    my $remotereq=<$client>;
                   3860: 	    $remotereq=~s/[^\w:]//g;
                   3861: 	    if ($remotereq =~ /^init/) {
                   3862: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   3863: 		my $challenge="$$".time;
                   3864: 		print $client "$challenge\n";
                   3865: 		&status(
                   3866: 			"Waiting for challenge reply from $clientip ($clientname)"); 
                   3867: 		$remotereq=<$client>;
                   3868: 		$remotereq=~s/\W//g;
                   3869: 		if ($challenge eq $remotereq) {
                   3870: 		    $clientok=1;
                   3871: 		    print $client "ok\n";
                   3872: 		} else {
                   3873: 		    &logthis(
                   3874: 			     "<font color=blue>WARNING: $clientip did not reply challenge</font>");
                   3875: 		    &status('No challenge reply '.$clientip);
                   3876: 		}
1.2       www      3877: 	    } else {
1.161     foxr     3878: 		&logthis(
                   3879: 			 "<font color=blue>WARNING: "
                   3880: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   3881: 		&status('No init '.$clientip);
                   3882: 	    }
                   3883: 	} else {
                   3884: 	    &logthis(
                   3885: 		     "<font color=blue>WARNING: Unknown client $clientip</font>");
                   3886: 	    &status('Hung up on '.$clientip);
                   3887: 	}
                   3888: 	if ($clientok) {
1.1       albertel 3889: # ---------------- New known client connecting, could mean machine online again
1.161     foxr     3890: 	    
                   3891: 	    foreach my $id (keys(%hostip)) {
                   3892: 		if ($hostip{$id} ne $clientip ||
                   3893: 		    $hostip{$currenthostid} eq $clientip) {
                   3894: 		    # no need to try to do recon's to myself
                   3895: 		    next;
1.115     albertel 3896: 		}
1.161     foxr     3897: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
                   3898: 	    }
                   3899: 	    &logthis("<font color=green>Established connection: $clientname</font>");
                   3900: 	    &status('Will listen to '.$clientname);
                   3901: 
1.178.2.1  foxr     3902: 	    ResetStatistics();
1.161     foxr     3903: 
1.178.2.1  foxr     3904: # ------------------------------------------------------------ Process requests
                   3905: 	    my $KeepGoing = 1;
                   3906: 	    while ((my $userinput=GetRequest) && $KeepGoing) {
                   3907: 		$KeepGoing = ProcessRequest($userinput);
1.177     foxr     3908: # -------------------------------------------------------------------- complete
1.178.2.1  foxr     3909: 
1.161     foxr     3910: 		&status('Listening to '.$clientname);
                   3911: 	    }
1.59      www      3912: # --------------------------------------------- client unknown or fishy, refuse
1.161     foxr     3913: 	} else {
                   3914: 	    print $client "refused\n";
                   3915: 	    $client->close();
                   3916: 	    &logthis("<font color=blue>WARNING: "
                   3917: 		     ."Rejected client $clientip, closing connection</font>");
                   3918: 	}
                   3919:     }             
                   3920:     
1.1       albertel 3921: # =============================================================================
1.161     foxr     3922:     
                   3923:     &logthis("<font color=red>CRITICAL: "
                   3924: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   3925:     
                   3926:     
                   3927:     # this exit is VERY important, otherwise the child will become
                   3928:     # a producer of more and more children, forking yourself into
                   3929:     # process death.
                   3930:     exit;
1.106     foxr     3931:     
1.78      foxr     3932: }
                   3933: 
                   3934: 
                   3935: #
                   3936: #   Checks to see if the input roleput request was to set
                   3937: # an author role.  If so, invokes the lchtmldir script to set
                   3938: # up a correct public_html 
                   3939: # Parameters:
                   3940: #    request   - The request sent to the rolesput subchunk.
                   3941: #                We're looking for  /domain/_au
                   3942: #    domain    - The domain in which the user is having roles doctored.
                   3943: #    user      - Name of the user for which the role is being put.
                   3944: #    authtype  - The authentication type associated with the user.
                   3945: #
                   3946: sub ManagePermissions
                   3947: {
                   3948:     my $request = shift;
                   3949:     my $domain  = shift;
                   3950:     my $user    = shift;
                   3951:     my $authtype= shift;
                   3952: 
                   3953:     # See if the request is of the form /$domain/_au
1.178.2.1  foxr     3954:     &logthis("ruequest is $request");
1.78      foxr     3955:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
                   3956: 	my $execdir = $perlvar{'lonDaemons'};
                   3957: 	my $userhome= "/home/$user" ;
1.134     albertel 3958: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.78      foxr     3959: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   3960:     }
                   3961: }
                   3962: #
                   3963: #   GetAuthType - Determines the authorization type of a user in a domain.
                   3964: 
                   3965: #     Returns the authorization type or nouser if there is no such user.
                   3966: #
                   3967: sub GetAuthType 
                   3968: {
                   3969:     my $domain = shift;
                   3970:     my $user   = shift;
                   3971: 
1.79      foxr     3972:     Debug("GetAuthType( $domain, $user ) \n");
1.78      foxr     3973:     my $proname    = &propath($domain, $user); 
                   3974:     my $passwdfile = "$proname/passwd";
                   3975:     if( -e $passwdfile ) {
                   3976: 	my $pf = IO::File->new($passwdfile);
                   3977: 	my $realpassword = <$pf>;
                   3978: 	chomp($realpassword);
1.79      foxr     3979: 	Debug("Password info = $realpassword\n");
1.78      foxr     3980: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     3981: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.78      foxr     3982: 	my $availinfo = '';
1.91      albertel 3983: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
1.78      foxr     3984: 	    $availinfo = $contentpwd;
                   3985: 	}
1.79      foxr     3986: 
1.78      foxr     3987: 	return "$authtype:$availinfo";
                   3988:     }
                   3989:     else {
1.79      foxr     3990: 	Debug("Returning nouser");
1.78      foxr     3991: 	return "nouser";
                   3992:     }
1.1       albertel 3993: }
                   3994: 
1.84      albertel 3995: sub addline {
                   3996:     my ($fname,$hostid,$ip,$newline)=@_;
                   3997:     my $contents;
                   3998:     my $found=0;
                   3999:     my $expr='^'.$hostid.':'.$ip.':';
                   4000:     $expr =~ s/\./\\\./g;
1.134     albertel 4001:     my $sh;
1.84      albertel 4002:     if ($sh=IO::File->new("$fname.subscription")) {
                   4003: 	while (my $subline=<$sh>) {
                   4004: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   4005: 	}
                   4006: 	$sh->close();
                   4007:     }
                   4008:     $sh=IO::File->new(">$fname.subscription");
                   4009:     if ($contents) { print $sh $contents; }
                   4010:     if ($newline) { print $sh $newline; }
                   4011:     $sh->close();
                   4012:     return $found;
1.86      www      4013: }
                   4014: 
                   4015: sub getchat {
1.122     www      4016:     my ($cdom,$cname,$udom,$uname)=@_;
1.87      www      4017:     my %hash;
                   4018:     my $proname=&propath($cdom,$cname);
                   4019:     my @entries=();
1.88      albertel 4020:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   4021: 	    &GDBM_READER(),0640)) {
                   4022: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   4023: 	untie %hash;
1.123     www      4024:     }
1.124     www      4025:     my @participants=();
1.134     albertel 4026:     my $cutoff=time-60;
1.123     www      4027:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124     www      4028: 	    &GDBM_WRCREAT(),0640)) {
                   4029:         $hash{$uname.':'.$udom}=time;
1.123     www      4030:         foreach (sort keys %hash) {
                   4031: 	    if ($hash{$_}>$cutoff) {
1.124     www      4032: 		$participants[$#participants+1]='active_participant:'.$_;
1.123     www      4033:             }
                   4034:         }
                   4035:         untie %hash;
1.86      www      4036:     }
1.124     www      4037:     return (@participants,@entries);
1.86      www      4038: }
                   4039: 
                   4040: sub chatadd {
1.88      albertel 4041:     my ($cdom,$cname,$newchat)=@_;
                   4042:     my %hash;
                   4043:     my $proname=&propath($cdom,$cname);
                   4044:     my @entries=();
1.142     www      4045:     my $time=time;
1.88      albertel 4046:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   4047: 	    &GDBM_WRCREAT(),0640)) {
                   4048: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   4049: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   4050: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   4051: 	my $newid=$time.'_000000';
                   4052: 	if ($thentime==$time) {
                   4053: 	    $idnum=~s/^0+//;
                   4054: 	    $idnum++;
                   4055: 	    $idnum=substr('000000'.$idnum,-6,6);
                   4056: 	    $newid=$time.'_'.$idnum;
                   4057: 	}
                   4058: 	$hash{$newid}=$newchat;
                   4059: 	my $expired=$time-3600;
                   4060: 	foreach (keys %hash) {
                   4061: 	    my ($thistime)=($_=~/(\d+)\_/);
                   4062: 	    if ($thistime<$expired) {
1.89      www      4063: 		delete $hash{$_};
1.88      albertel 4064: 	    }
                   4065: 	}
                   4066: 	untie %hash;
1.142     www      4067:     }
                   4068:     {
                   4069: 	my $hfh;
                   4070: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
                   4071: 	    print $hfh "$time:".&unescape($newchat)."\n";
                   4072: 	}
1.86      www      4073:     }
1.84      albertel 4074: }
                   4075: 
                   4076: sub unsub {
                   4077:     my ($fname,$clientip)=@_;
                   4078:     my $result;
1.161     foxr     4079:     if (unlink("$fname.$clientname")) {
1.84      albertel 4080: 	$result="ok\n";
                   4081:     } else {
                   4082: 	$result="not_subscribed\n";
                   4083:     }
                   4084:     if (-e "$fname.subscription") {
1.161     foxr     4085: 	my $found=&addline($fname,$clientname,$clientip,'');
1.84      albertel 4086: 	if ($found) { $result="ok\n"; }
                   4087:     } else {
                   4088: 	if ($result != "ok\n") { $result="not_subscribed\n"; }
                   4089:     }
                   4090:     return $result;
                   4091: }
                   4092: 
1.101     www      4093: sub currentversion {
                   4094:     my $fname=shift;
                   4095:     my $version=-1;
                   4096:     my $ulsdir='';
                   4097:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   4098:        $ulsdir=$1;
                   4099:     }
1.114     albertel 4100:     my ($fnamere1,$fnamere2);
                   4101:     # remove version if already specified
1.101     www      4102:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 4103:     # get the bits that go before and after the version number
                   4104:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   4105: 	$fnamere1=$1;
                   4106: 	$fnamere2='.'.$2;
                   4107:     }
1.101     www      4108:     if (-e $fname) { $version=1; }
                   4109:     if (-e $ulsdir) {
1.134     albertel 4110: 	if(-d $ulsdir) {
                   4111: 	    if (opendir(LSDIR,$ulsdir)) {
                   4112: 		my $ulsfn;
                   4113: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      4114: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 4115: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   4116: 		    unless (-l $thisfile) {
1.160     www      4117: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 4118: 			    if ($1>$version) { $version=$1; }
                   4119: 			}
                   4120: 		    }
                   4121: 		}
                   4122: 		closedir(LSDIR);
                   4123: 		$version++;
                   4124: 	    }
                   4125: 	}
                   4126:     }
                   4127:     return $version;
1.101     www      4128: }
                   4129: 
                   4130: sub thisversion {
                   4131:     my $fname=shift;
                   4132:     my $version=-1;
                   4133:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   4134: 	$version=$1;
                   4135:     }
                   4136:     return $version;
                   4137: }
                   4138: 
1.84      albertel 4139: sub subscribe {
                   4140:     my ($userinput,$clientip)=@_;
                   4141:     my $result;
                   4142:     my ($cmd,$fname)=split(/:/,$userinput);
                   4143:     my $ownership=&ishome($fname);
                   4144:     if ($ownership eq 'owner') {
1.101     www      4145: # explitly asking for the current version?
                   4146:         unless (-e $fname) {
                   4147:             my $currentversion=&currentversion($fname);
                   4148: 	    if (&thisversion($fname)==$currentversion) {
                   4149:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   4150: 		    my $root=$1;
                   4151:                     my $extension=$2;
                   4152:                     symlink($root.'.'.$extension,
                   4153:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      4154:                     unless ($extension=~/\.meta$/) {
                   4155:                        symlink($root.'.'.$extension.'.meta',
                   4156:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   4157: 		    }
1.101     www      4158:                 }
                   4159:             }
                   4160:         }
1.84      albertel 4161: 	if (-e $fname) {
                   4162: 	    if (-d $fname) {
                   4163: 		$result="directory\n";
                   4164: 	    } else {
1.161     foxr     4165: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 4166: 		my $now=time;
1.161     foxr     4167: 		my $found=&addline($fname,$clientname,$clientip,
                   4168: 				   "$clientname:$clientip:$now\n");
1.84      albertel 4169: 		if ($found) { $result="$fname\n"; }
                   4170: 		# if they were subscribed to only meta data, delete that
                   4171:                 # subscription, when you subscribe to a file you also get
                   4172:                 # the metadata
                   4173: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   4174: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
                   4175: 		$fname="http://$thisserver/".$fname;
                   4176: 		$result="$fname\n";
                   4177: 	    }
                   4178: 	} else {
                   4179: 	    $result="not_found\n";
                   4180: 	}
                   4181:     } else {
                   4182: 	$result="rejected\n";
                   4183:     }
                   4184:     return $result;
                   4185: }
1.91      albertel 4186: 
                   4187: sub make_passwd_file {
1.98      foxr     4188:     my ($uname, $umode,$npass,$passfilename)=@_;
1.91      albertel 4189:     my $result="ok\n";
                   4190:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   4191: 	{
                   4192: 	    my $pf = IO::File->new(">$passfilename");
                   4193: 	    print $pf "$umode:$npass\n";
                   4194: 	}
                   4195:     } elsif ($umode eq 'internal') {
                   4196: 	my $salt=time;
                   4197: 	$salt=substr($salt,6,2);
                   4198: 	my $ncpass=crypt($npass,$salt);
                   4199: 	{
                   4200: 	    &Debug("Creating internal auth");
                   4201: 	    my $pf = IO::File->new(">$passfilename");
                   4202: 	    print $pf "internal:$ncpass\n"; 
                   4203: 	}
                   4204:     } elsif ($umode eq 'localauth') {
                   4205: 	{
                   4206: 	    my $pf = IO::File->new(">$passfilename");
                   4207: 	    print $pf "localauth:$npass\n";
                   4208: 	}
                   4209:     } elsif ($umode eq 'unix') {
                   4210: 	{
                   4211: 	    my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
                   4212: 	    {
                   4213: 		&Debug("Executing external: ".$execpath);
1.98      foxr     4214: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  4215: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 4216: 		print $se "$uname\n";
                   4217: 		print $se "$npass\n";
                   4218: 		print $se "$npass\n";
1.97      foxr     4219: 	    }
                   4220: 	    my $useraddok = $?;
                   4221: 	    if($useraddok > 0) {
                   4222: 		&logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
1.91      albertel 4223: 	    }
                   4224: 	    my $pf = IO::File->new(">$passfilename");
                   4225: 	    print $pf "unix:\n";
                   4226: 	}
                   4227:     } elsif ($umode eq 'none') {
                   4228: 	{
                   4229: 	    my $pf = IO::File->new(">$passfilename");
                   4230: 	    print $pf "none:\n";
                   4231: 	}
                   4232:     } else {
                   4233: 	$result="auth_mode_error\n";
                   4234:     }
                   4235:     return $result;
1.121     albertel 4236: }
                   4237: 
                   4238: sub sethost {
                   4239:     my ($remotereq) = @_;
                   4240:     my (undef,$hostid)=split(/:/,$remotereq);
                   4241:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
                   4242:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
                   4243: 	$currenthostid=$hostid;
                   4244: 	$currentdomainid=$hostdom{$hostid};
                   4245: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
                   4246:     } else {
                   4247: 	&logthis("Requested host id $hostid not an alias of ".
                   4248: 		 $perlvar{'lonHostID'}." refusing connection");
                   4249: 	return 'unable_to_set';
                   4250:     }
                   4251:     return 'ok';
                   4252: }
                   4253: 
                   4254: sub version {
                   4255:     my ($userinput)=@_;
                   4256:     $remoteVERSION=(split(/:/,$userinput))[1];
                   4257:     return "version:$VERSION";
1.127     albertel 4258: }
1.178.2.1  foxr     4259: ############## >>>>>>>>>>>>>>>>>>>>>>>>>> FUTUREWORK <<<<<<<<<<<<<<<<<<<<<<<<<<<<
1.128     albertel 4260: #There is a copy of this in lonnet.pm
1.178.2.1  foxr     4261: #   Can we hoist these lil' things out into common places?
                   4262: #
1.127     albertel 4263: sub userload {
                   4264:     my $numusers=0;
                   4265:     {
                   4266: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   4267: 	my $filename;
                   4268: 	my $curtime=time;
                   4269: 	while ($filename=readdir(LONIDS)) {
                   4270: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.138     albertel 4271: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159     albertel 4272: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.127     albertel 4273: 	}
                   4274: 	closedir(LONIDS);
                   4275:     }
                   4276:     my $userloadpercent=0;
                   4277:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   4278:     if ($maxuserload) {
1.129     albertel 4279: 	$userloadpercent=100*$numusers/$maxuserload;
1.127     albertel 4280:     }
1.130     albertel 4281:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127     albertel 4282:     return $userloadpercent;
1.91      albertel 4283: }
                   4284: 
1.61      harris41 4285: # ----------------------------------- POD (plain old documentation, CPAN style)
                   4286: 
                   4287: =head1 NAME
                   4288: 
                   4289: lond - "LON Daemon" Server (port "LOND" 5663)
                   4290: 
                   4291: =head1 SYNOPSIS
                   4292: 
1.74      harris41 4293: Usage: B<lond>
                   4294: 
                   4295: Should only be run as user=www.  This is a command-line script which
                   4296: is invoked by B<loncron>.  There is no expectation that a typical user
                   4297: will manually start B<lond> from the command-line.  (In other words,
                   4298: DO NOT START B<lond> YOURSELF.)
1.61      harris41 4299: 
                   4300: =head1 DESCRIPTION
                   4301: 
1.74      harris41 4302: There are two characteristics associated with the running of B<lond>,
                   4303: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   4304: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   4305: subscriptions, etc).  These are described in two large
                   4306: sections below.
                   4307: 
                   4308: B<PROCESS MANAGEMENT>
                   4309: 
1.61      harris41 4310: Preforker - server who forks first. Runs as a daemon. HUPs.
                   4311: Uses IDEA encryption
                   4312: 
1.74      harris41 4313: B<lond> forks off children processes that correspond to the other servers
                   4314: in the network.  Management of these processes can be done at the
                   4315: parent process level or the child process level.
                   4316: 
                   4317: B<logs/lond.log> is the location of log messages.
                   4318: 
                   4319: The process management is now explained in terms of linux shell commands,
                   4320: subroutines internal to this code, and signal assignments:
                   4321: 
                   4322: =over 4
                   4323: 
                   4324: =item *
                   4325: 
                   4326: PID is stored in B<logs/lond.pid>
                   4327: 
                   4328: This is the process id number of the parent B<lond> process.
                   4329: 
                   4330: =item *
                   4331: 
                   4332: SIGTERM and SIGINT
                   4333: 
                   4334: Parent signal assignment:
                   4335:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   4336: 
                   4337: Child signal assignment:
                   4338:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   4339: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   4340:  to restart a new child.)
                   4341: 
                   4342: Command-line invocations:
                   4343:  B<kill> B<-s> SIGTERM I<PID>
                   4344:  B<kill> B<-s> SIGINT I<PID>
                   4345: 
                   4346: Subroutine B<HUNTSMAN>:
                   4347:  This is only invoked for the B<lond> parent I<PID>.
                   4348: This kills all the children, and then the parent.
                   4349: The B<lonc.pid> file is cleared.
                   4350: 
                   4351: =item *
                   4352: 
                   4353: SIGHUP
                   4354: 
                   4355: Current bug:
                   4356:  This signal can only be processed the first time
                   4357: on the parent process.  Subsequent SIGHUP signals
                   4358: have no effect.
                   4359: 
                   4360: Parent signal assignment:
                   4361:  $SIG{HUP}  = \&HUPSMAN;
                   4362: 
                   4363: Child signal assignment:
                   4364:  none (nothing happens)
                   4365: 
                   4366: Command-line invocations:
                   4367:  B<kill> B<-s> SIGHUP I<PID>
                   4368: 
                   4369: Subroutine B<HUPSMAN>:
                   4370:  This is only invoked for the B<lond> parent I<PID>,
                   4371: This kills all the children, and then the parent.
                   4372: The B<lond.pid> file is cleared.
                   4373: 
                   4374: =item *
                   4375: 
                   4376: SIGUSR1
                   4377: 
                   4378: Parent signal assignment:
                   4379:  $SIG{USR1} = \&USRMAN;
                   4380: 
                   4381: Child signal assignment:
                   4382:  $SIG{USR1}= \&logstatus;
                   4383: 
                   4384: Command-line invocations:
                   4385:  B<kill> B<-s> SIGUSR1 I<PID>
                   4386: 
                   4387: Subroutine B<USRMAN>:
                   4388:  When invoked for the B<lond> parent I<PID>,
                   4389: SIGUSR1 is sent to all the children, and the status of
                   4390: each connection is logged.
1.144     foxr     4391: 
                   4392: =item *
                   4393: 
                   4394: SIGUSR2
                   4395: 
                   4396: Parent Signal assignment:
                   4397:     $SIG{USR2} = \&UpdateHosts
                   4398: 
                   4399: Child signal assignment:
                   4400:     NONE
                   4401: 
1.74      harris41 4402: 
                   4403: =item *
                   4404: 
                   4405: SIGCHLD
                   4406: 
                   4407: Parent signal assignment:
                   4408:  $SIG{CHLD} = \&REAPER;
                   4409: 
                   4410: Child signal assignment:
                   4411:  none
                   4412: 
                   4413: Command-line invocations:
                   4414:  B<kill> B<-s> SIGCHLD I<PID>
                   4415: 
                   4416: Subroutine B<REAPER>:
                   4417:  This is only invoked for the B<lond> parent I<PID>.
                   4418: Information pertaining to the child is removed.
                   4419: The socket port is cleaned up.
                   4420: 
                   4421: =back
                   4422: 
                   4423: B<SERVER-SIDE ACTIVITIES>
                   4424: 
                   4425: Server-side information can be accepted in an encrypted or non-encrypted
                   4426: method.
                   4427: 
                   4428: =over 4
                   4429: 
                   4430: =item ping
                   4431: 
                   4432: Query a client in the hosts.tab table; "Are you there?"
                   4433: 
                   4434: =item pong
                   4435: 
                   4436: Respond to a ping query.
                   4437: 
                   4438: =item ekey
                   4439: 
                   4440: Read in encrypted key, make cipher.  Respond with a buildkey.
                   4441: 
                   4442: =item load
                   4443: 
                   4444: Respond with CPU load based on a computation upon /proc/loadavg.
                   4445: 
                   4446: =item currentauth
                   4447: 
                   4448: Reply with current authentication information (only over an
                   4449: encrypted channel).
                   4450: 
                   4451: =item auth
                   4452: 
                   4453: Only over an encrypted channel, reply as to whether a user's
                   4454: authentication information can be validated.
                   4455: 
                   4456: =item passwd
                   4457: 
                   4458: Allow for a password to be set.
                   4459: 
                   4460: =item makeuser
                   4461: 
                   4462: Make a user.
                   4463: 
                   4464: =item passwd
                   4465: 
                   4466: Allow for authentication mechanism and password to be changed.
                   4467: 
                   4468: =item home
1.61      harris41 4469: 
1.74      harris41 4470: Respond to a question "are you the home for a given user?"
                   4471: 
                   4472: =item update
                   4473: 
                   4474: Update contents of a subscribed resource.
                   4475: 
                   4476: =item unsubscribe
                   4477: 
                   4478: The server is unsubscribing from a resource.
                   4479: 
                   4480: =item subscribe
                   4481: 
                   4482: The server is subscribing to a resource.
                   4483: 
                   4484: =item log
                   4485: 
                   4486: Place in B<logs/lond.log>
                   4487: 
                   4488: =item put
                   4489: 
                   4490: stores hash in namespace
                   4491: 
                   4492: =item rolesput
                   4493: 
                   4494: put a role into a user's environment
                   4495: 
                   4496: =item get
                   4497: 
                   4498: returns hash with keys from array
                   4499: reference filled in from namespace
                   4500: 
                   4501: =item eget
                   4502: 
                   4503: returns hash with keys from array
                   4504: reference filled in from namesp (encrypts the return communication)
                   4505: 
                   4506: =item rolesget
                   4507: 
                   4508: get a role from a user's environment
                   4509: 
                   4510: =item del
                   4511: 
                   4512: deletes keys out of array from namespace
                   4513: 
                   4514: =item keys
                   4515: 
                   4516: returns namespace keys
                   4517: 
                   4518: =item dump
                   4519: 
                   4520: dumps the complete (or key matching regexp) namespace into a hash
                   4521: 
                   4522: =item store
                   4523: 
                   4524: stores hash permanently
                   4525: for this url; hashref needs to be given and should be a \%hashname; the
                   4526: remaining args aren't required and if they aren't passed or are '' they will
                   4527: be derived from the ENV
                   4528: 
                   4529: =item restore
                   4530: 
                   4531: returns a hash for a given url
                   4532: 
                   4533: =item querysend
                   4534: 
                   4535: Tells client about the lonsql process that has been launched in response
                   4536: to a sent query.
                   4537: 
                   4538: =item queryreply
                   4539: 
                   4540: Accept information from lonsql and make appropriate storage in temporary
                   4541: file space.
                   4542: 
                   4543: =item idput
                   4544: 
                   4545: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   4546: for each student, defined perhaps by the institutional Registrar.)
                   4547: 
                   4548: =item idget
                   4549: 
                   4550: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   4551: for each student, defined perhaps by the institutional Registrar.)
                   4552: 
                   4553: =item tmpput
                   4554: 
                   4555: Accept and store information in temporary space.
                   4556: 
                   4557: =item tmpget
                   4558: 
                   4559: Send along temporarily stored information.
                   4560: 
                   4561: =item ls
                   4562: 
                   4563: List part of a user's directory.
                   4564: 
1.135     foxr     4565: =item pushtable
                   4566: 
                   4567: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   4568: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   4569: must be restored manually in case of a problem with the new table file.
                   4570: pushtable requires that the request be encrypted and validated via
                   4571: ValidateManager.  The form of the command is:
                   4572: enc:pushtable tablename <tablecontents> \n
                   4573: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   4574: cleartext newline.
                   4575: 
1.74      harris41 4576: =item Hanging up (exit or init)
                   4577: 
                   4578: What to do when a client tells the server that they (the client)
                   4579: are leaving the network.
                   4580: 
                   4581: =item unknown command
                   4582: 
                   4583: If B<lond> is sent an unknown command (not in the list above),
                   4584: it replys to the client "unknown_cmd".
1.135     foxr     4585: 
1.74      harris41 4586: 
                   4587: =item UNKNOWN CLIENT
                   4588: 
                   4589: If the anti-spoofing algorithm cannot verify the client,
                   4590: the client is rejected (with a "refused" message sent
                   4591: to the client, and the connection is closed.
                   4592: 
                   4593: =back
1.61      harris41 4594: 
                   4595: =head1 PREREQUISITES
                   4596: 
                   4597: IO::Socket
                   4598: IO::File
                   4599: Apache::File
                   4600: Symbol
                   4601: POSIX
                   4602: Crypt::IDEA
                   4603: LWP::UserAgent()
                   4604: GDBM_File
                   4605: Authen::Krb4
1.91      albertel 4606: Authen::Krb5
1.61      harris41 4607: 
                   4608: =head1 COREQUISITES
                   4609: 
                   4610: =head1 OSNAMES
                   4611: 
                   4612: linux
                   4613: 
                   4614: =head1 SCRIPT CATEGORIES
                   4615: 
                   4616: Server/Process
                   4617: 
                   4618: =cut

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