Annotation of loncom/lond, revision 1.178.2.23

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

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