Annotation of loncom/lond, revision 1.178.2.18

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

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