Annotation of loncom/lond, revision 1.178.2.20

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

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