Annotation of loncom/lond, revision 1.178.2.11

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

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