Annotation of loncom/lond, revision 1.288

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.288   ! albertel    5: # $Id: lond,v 1.287 2005/06/27 10:27:02 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     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.193     raeburn    48: use localenroll;
1.265     albertel   49: use localstudentphoto;
1.143     foxr       50: use File::Copy;
1.169     foxr       51: use LONCAPA::ConfigFileEdit;
1.200     matthew    52: use LONCAPA::lonlocal;
                     53: use LONCAPA::lonssl;
1.221     albertel   54: use Fcntl qw(:flock);
1.1       albertel   55: 
1.239     foxr       56: my $DEBUG = 0;		       # Non zero to enable debug log entries.
1.77      foxr       57: 
1.57      www        58: my $status='';
                     59: my $lastlog='';
                     60: 
1.288   ! albertel   61: my $VERSION='$Revision: 1.287 $'; #' stupid emacs
1.121     albertel   62: my $remoteVERSION;
1.214     foxr       63: my $currenthostid="default";
1.115     albertel   64: my $currentdomainid;
1.134     albertel   65: 
                     66: my $client;
1.200     matthew    67: my $clientip;			# IP address of client.
                     68: my $clientname;			# LonCAPA name of client.
1.140     foxr       69: 
1.134     albertel   70: my $server;
1.200     matthew    71: my $thisserver;			# DNS of us.
                     72: 
                     73: my $keymode;
1.198     foxr       74: 
1.207     foxr       75: my $cipher;			# Cipher key negotiated with client
                     76: my $tmpsnum = 0;		# Id of tmpputs.
                     77: 
1.178     foxr       78: # 
                     79: #   Connection type is:
                     80: #      client                   - All client actions are allowed
                     81: #      manager                  - only management functions allowed.
                     82: #      both                     - Both management and client actions are allowed
                     83: #
1.161     foxr       84: 
1.178     foxr       85: my $ConnectionType;
1.161     foxr       86: 
1.200     matthew    87: my %hostid;			# ID's for hosts in cluster by ip.
                     88: my %hostdom;			# LonCAPA domain for hosts in cluster.
                     89: my %hostip;			# IPs for hosts in cluster.
                     90: my %hostdns;			# ID's of hosts looked up by DNS name.
1.161     foxr       91: 
1.178     foxr       92: my %managers;			# Ip -> manager names
1.161     foxr       93: 
1.178     foxr       94: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel   95: 
1.178     foxr       96: #
1.207     foxr       97: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                     98: #    Each element of the hash contains a reference to an array that contains:
                     99: #          A reference to a sub that executes the request corresponding to the keyword.
                    100: #          A flag that is true if the request must be encoded to be acceptable.
                    101: #          A mask with bits as follows:
                    102: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    103: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    104: #
                    105: my $CLIENT_OK  = 1;
                    106: my $MANAGER_OK = 2;
                    107: my %Dispatcher;
                    108: 
                    109: 
                    110: #
1.178     foxr      111: #  The array below are password error strings."
                    112: #
                    113: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    114: my @passwderrors = ("ok",
1.287     foxr      115: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
                    116: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
                    117: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
                    118: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
                    119: 		   "pwchange_failure - lcpasswd User does not exist.",
                    120: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
                    121: 		   "pwchange_failure - lcpasswd Unable to su to root.",
                    122: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
                    123: 		   "pwchange_failure - lcpasswd Username has invalid characters",
                    124: 		   "pwchange_failure - lcpasswd Invalid characters in password",
                    125: 		   "pwchange_failure - lcpasswd User already exists", 
                    126:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
                    127: 		   "pwchange_failure - lcpasswd Password mismatch",
                    128: 		   "pwchange_failure - lcpasswd Error filename is invalid");
1.97      foxr      129: 
                    130: 
1.178     foxr      131: #  The array below are lcuseradd error strings.:
1.97      foxr      132: 
1.178     foxr      133: my $lastadderror = 13;
                    134: my @adderrors    = ("ok",
                    135: 		    "User ID mismatch, lcuseradd must run as user www",
                    136: 		    "lcuseradd Incorrect number of command line parameters must be 3",
                    137: 		    "lcuseradd Incorrect number of stdinput lines, must be 3",
                    138: 		    "lcuseradd Too many other simultaneous pwd changes in progress",
                    139: 		    "lcuseradd User does not exist",
                    140: 		    "lcuseradd Unable to make www member of users's group",
                    141: 		    "lcuseradd Unable to su to root",
                    142: 		    "lcuseradd Unable to set password",
                    143: 		    "lcuseradd Usrname has invalid characters",
                    144: 		    "lcuseradd Password has an invalid character",
                    145: 		    "lcuseradd User already exists",
                    146: 		    "lcuseradd Could not add user.",
                    147: 		    "lcuseradd Password mismatch");
1.97      foxr      148: 
1.96      foxr      149: 
1.207     foxr      150: 
                    151: #
                    152: #   Statistics that are maintained and dislayed in the status line.
                    153: #
1.212     foxr      154: my $Transactions = 0;		# Number of attempted transactions.
                    155: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      156: 
                    157: #   ResetStatistics: 
                    158: #      Resets the statistics counters:
                    159: #
                    160: sub ResetStatistics {
                    161:     $Transactions = 0;
                    162:     $Failures     = 0;
                    163: }
                    164: 
1.200     matthew   165: #------------------------------------------------------------------------
                    166: #
                    167: #   LocalConnection
                    168: #     Completes the formation of a locally authenticated connection.
                    169: #     This function will ensure that the 'remote' client is really the
                    170: #     local host.  If not, the connection is closed, and the function fails.
                    171: #     If so, initcmd is parsed for the name of a file containing the
                    172: #     IDEA session key.  The fie is opened, read, deleted and the session
                    173: #     key returned to the caller.
                    174: #
                    175: # Parameters:
                    176: #   $Socket      - Socket open on client.
                    177: #   $initcmd     - The full text of the init command.
                    178: #
                    179: # Implicit inputs:
                    180: #    $thisserver - Our DNS name.
                    181: #
                    182: # Returns:
                    183: #     IDEA session key on success.
                    184: #     undef on failure.
                    185: #
                    186: sub LocalConnection {
                    187:     my ($Socket, $initcmd) = @_;
1.277     albertel  188:     Debug("Attempting local connection: $initcmd client: $clientip me: $thisserver");
                    189:     if($clientip ne "127.0.0.1") {
1.200     matthew   190: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.277     albertel  191: 		 ."$clientip ne $thisserver </font>");
1.200     matthew   192: 	close $Socket;
                    193: 	return undef;
1.224     foxr      194:     }  else {
1.200     matthew   195: 	chomp($initcmd);	# Get rid of \n in filename.
                    196: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    197: 	Debug(" Init command: $init $type $name ");
                    198: 
                    199: 	# Require that $init = init, and $type = local:  Otherwise
                    200: 	# the caller is insane:
                    201: 
                    202: 	if(($init ne "init") && ($type ne "local")) {
                    203: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    204: 		     ."init = $init, and type = $type </font>");
                    205: 	    close($Socket);;
                    206: 	    return undef;
                    207: 		
                    208: 	}
                    209: 	#  Now get the key filename:
                    210: 
                    211: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    212: 	return $IDEAKey;
                    213:     }
                    214: }
                    215: #------------------------------------------------------------------------------
                    216: #
                    217: #  SSLConnection
                    218: #   Completes the formation of an ssh authenticated connection. The
                    219: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    220: #   certificate exchange are successful, the IDEA key is generated and sent
                    221: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    222: #   the caller after the SSL tunnel is torn down.
                    223: #
                    224: # Parameters:
                    225: #   Name              Type             Purpose
                    226: #   $Socket          IO::Socket::INET  Plaintext socket.
                    227: #
                    228: # Returns:
                    229: #    IDEA key on success.
                    230: #    undef on failure.
                    231: #
                    232: sub SSLConnection {
                    233:     my $Socket   = shift;
                    234: 
                    235:     Debug("SSLConnection: ");
                    236:     my $KeyFile         = lonssl::KeyFile();
                    237:     if(!$KeyFile) {
                    238: 	my $err = lonssl::LastError();
                    239: 	&logthis("<font color=\"red\"> CRITICAL"
                    240: 		 ."Can't get key file $err </font>");
                    241: 	return undef;
                    242:     }
                    243:     my ($CACertificate,
                    244: 	$Certificate) = lonssl::CertificateFile();
                    245: 
                    246: 
                    247:     # If any of the key, certificate or certificate authority 
                    248:     # certificate filenames are not defined, this can't work.
                    249: 
                    250:     if((!$Certificate) || (!$CACertificate)) {
                    251: 	my $err = lonssl::LastError();
                    252: 	&logthis("<font color=\"red\"> CRITICAL"
                    253: 		 ."Can't get certificates: $err </font>");
                    254: 
                    255: 	return undef;
                    256:     }
                    257:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    258: 
                    259:     # Indicate to our peer that we can procede with
                    260:     # a transition to ssl authentication:
                    261: 
                    262:     print $Socket "ok:ssl\n";
                    263: 
                    264:     Debug("Approving promotion -> ssl");
                    265:     #  And do so:
                    266: 
                    267:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    268: 						$CACertificate,
                    269: 						$Certificate,
                    270: 						$KeyFile);
                    271:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    272: 	my $err = lonssl::LastError();
                    273: 	&logthis("<font color=\"red\"> CRITICAL "
                    274: 		 ."SSL Socket promotion failed: $err </font>");
                    275: 	return undef;
                    276:     }
                    277:     Debug("SSL Promotion successful");
                    278: 
                    279:     # 
                    280:     #  The only thing we'll use the socket for is to send the IDEA key
                    281:     #  to the peer:
                    282: 
                    283:     my $Key = lonlocal::CreateCipherKey();
                    284:     print $SSLSocket "$Key\n";
                    285: 
                    286:     lonssl::Close($SSLSocket); 
                    287: 
                    288:     Debug("Key exchange complete: $Key");
                    289: 
                    290:     return $Key;
                    291: }
                    292: #
                    293: #     InsecureConnection: 
                    294: #        If insecure connections are allowd,
                    295: #        exchange a challenge with the client to 'validate' the
                    296: #        client (not really, but that's the protocol):
                    297: #        We produce a challenge string that's sent to the client.
                    298: #        The client must then echo the challenge verbatim to us.
                    299: #
                    300: #  Parameter:
                    301: #      Socket      - Socket open on the client.
                    302: #  Returns:
                    303: #      1           - success.
                    304: #      0           - failure (e.g.mismatch or insecure not allowed).
                    305: #
                    306: sub InsecureConnection {
                    307:     my $Socket  =  shift;
                    308: 
                    309:     #   Don't even start if insecure connections are not allowed.
                    310: 
                    311:     if(! $perlvar{londAllowInsecure}) {	# Insecure connections not allowed.
                    312: 	return 0;
                    313:     }
                    314: 
                    315:     #   Fabricate a challenge string and send it..
                    316: 
                    317:     my $challenge = "$$".time;	# pid + time.
                    318:     print $Socket "$challenge\n";
                    319:     &status("Waiting for challenge reply");
                    320: 
                    321:     my $answer = <$Socket>;
                    322:     $answer    =~s/\W//g;
                    323:     if($challenge eq $answer) {
                    324: 	return 1;
1.224     foxr      325:     } else {
1.200     matthew   326: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    327: 	&status("No challenge reqply");
                    328: 	return 0;
                    329:     }
                    330:     
                    331: 
                    332: }
1.251     foxr      333: #
                    334: #   Safely execute a command (as long as it's not a shel command and doesn
                    335: #   not require/rely on shell escapes.   The function operates by doing a
                    336: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    337: #
                    338: # Formal Parameters:
                    339: #     $line                    - A line of text to be executed as a command.
                    340: # Returns:
                    341: #     The output from that command.  If the output is multiline the caller
                    342: #     must know how to split up the output.
                    343: #
                    344: #
                    345: sub execute_command {
                    346:     my ($line)    = @_;
                    347:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    348:     my $output    = "";
                    349: 
                    350:     my $pid = open(CHILD, "-|");
                    351:     
                    352:     if($pid) {			# Parent process
                    353: 	Debug("In parent process for execute_command");
                    354: 	my @data = <CHILD>;	# Read the child's outupt...
                    355: 	close CHILD;
                    356: 	foreach my $output_line (@data) {
                    357: 	    Debug("Adding $output_line");
                    358: 	    $output .= $output_line; # Presumably has a \n on it.
                    359: 	}
                    360: 
                    361:     } else {			# Child process
                    362: 	close (STDERR);
                    363: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    364: 	exec(@words);		# won't return.
                    365:     }
                    366:     return $output;
                    367: }
                    368: 
1.200     matthew   369: 
1.140     foxr      370: #   GetCertificate: Given a transaction that requires a certificate,
                    371: #   this function will extract the certificate from the transaction
                    372: #   request.  Note that at this point, the only concept of a certificate
                    373: #   is the hostname to which we are connected.
                    374: #
                    375: #   Parameter:
                    376: #      request   - The request sent by our client (this parameterization may
                    377: #                  need to change when we really use a certificate granting
                    378: #                  authority.
                    379: #
                    380: sub GetCertificate {
                    381:     my $request = shift;
                    382: 
                    383:     return $clientip;
                    384: }
1.161     foxr      385: 
1.178     foxr      386: #
                    387: #   Return true if client is a manager.
                    388: #
                    389: sub isManager {
                    390:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    391: }
                    392: #
                    393: #   Return tru if client can do client functions
                    394: #
                    395: sub isClient {
                    396:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    397: }
1.161     foxr      398: 
                    399: 
1.156     foxr      400: #
                    401: #   ReadManagerTable: Reads in the current manager table. For now this is
                    402: #                     done on each manager authentication because:
                    403: #                     - These authentications are not frequent
                    404: #                     - This allows dynamic changes to the manager table
                    405: #                       without the need to signal to the lond.
                    406: #
                    407: sub ReadManagerTable {
                    408: 
                    409:     #   Clean out the old table first..
                    410: 
1.166     foxr      411:    foreach my $key (keys %managers) {
                    412:       delete $managers{$key};
                    413:    }
                    414: 
                    415:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    416:    if (!open (MANAGERS, $tablename)) {
                    417:       logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    418:       return;
                    419:    }
                    420:    while(my $host = <MANAGERS>) {
                    421:       chomp($host);
                    422:       if ($host =~ "^#") {                  # Comment line.
                    423:          next;
                    424:       }
                    425:       if (!defined $hostip{$host}) { # This is a non cluster member
1.161     foxr      426: 	    #  The entry is of the form:
                    427: 	    #    cluname:hostname
                    428: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    429: 	    #            the host key.
                    430: 	    #  hostname- The dns name of the host.
                    431: 	    #
1.166     foxr      432:           my($cluname, $dnsname) = split(/:/, $host);
                    433:           
                    434:           my $ip = gethostbyname($dnsname);
                    435:           if(defined($ip)) {                 # bad names don't deserve entry.
                    436:             my $hostip = inet_ntoa($ip);
                    437:             $managers{$hostip} = $cluname;
                    438:             logthis('<font color="green"> registering manager '.
                    439:                     "$dnsname as $cluname with $hostip </font>\n");
                    440:          }
                    441:       } else {
                    442:          logthis('<font color="green"> existing host'." $host</font>\n");
                    443:          $managers{$hostip{$host}} = $host;  # Use info from cluster tab if clumemeber
                    444:       }
                    445:    }
1.156     foxr      446: }
1.140     foxr      447: 
                    448: #
                    449: #  ValidManager: Determines if a given certificate represents a valid manager.
                    450: #                in this primitive implementation, the 'certificate' is
                    451: #                just the connecting loncapa client name.  This is checked
                    452: #                against a valid client list in the configuration.
                    453: #
                    454: #                  
                    455: sub ValidManager {
                    456:     my $certificate = shift; 
                    457: 
1.163     foxr      458:     return isManager;
1.140     foxr      459: }
                    460: #
1.143     foxr      461: #  CopyFile:  Called as part of the process of installing a 
                    462: #             new configuration file.  This function copies an existing
                    463: #             file to a backup file.
                    464: # Parameters:
                    465: #     oldfile  - Name of the file to backup.
                    466: #     newfile  - Name of the backup file.
                    467: # Return:
                    468: #     0   - Failure (errno has failure reason).
                    469: #     1   - Success.
                    470: #
                    471: sub CopyFile {
1.192     foxr      472: 
                    473:     my ($oldfile, $newfile) = @_;
1.143     foxr      474: 
1.281     matthew   475:     if (! copy($oldfile,$newfile)) {
                    476:         return 0;
1.143     foxr      477:     }
1.281     matthew   478:     chmod(0660, $newfile);
                    479:     return 1;
1.143     foxr      480: }
1.157     foxr      481: #
                    482: #  Host files are passed out with externally visible host IPs.
                    483: #  If, for example, we are behind a fire-wall or NAT host, our 
                    484: #  internally visible IP may be different than the externally
                    485: #  visible IP.  Therefore, we always adjust the contents of the
                    486: #  host file so that the entry for ME is the IP that we believe
                    487: #  we have.  At present, this is defined as the entry that
                    488: #  DNS has for us.  If by some chance we are not able to get a
                    489: #  DNS translation for us, then we assume that the host.tab file
                    490: #  is correct.  
                    491: #    BUGBUGBUG - in the future, we really should see if we can
                    492: #       easily query the interface(s) instead.
                    493: # Parameter(s):
                    494: #     contents    - The contents of the host.tab to check.
                    495: # Returns:
                    496: #     newcontents - The adjusted contents.
                    497: #
                    498: #
                    499: sub AdjustHostContents {
                    500:     my $contents  = shift;
                    501:     my $adjusted;
                    502:     my $me        = $perlvar{'lonHostID'};
                    503: 
1.166     foxr      504:  foreach my $line (split(/\n/,$contents)) {
1.157     foxr      505: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
                    506: 	    chomp($line);
                    507: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    508: 	    if ($id eq $me) {
1.166     foxr      509:           my $ip = gethostbyname($name);
                    510:           my $ipnew = inet_ntoa($ip);
                    511:          $ip = $ipnew;
1.157     foxr      512: 		#  Reconstruct the host line and append to adjusted:
                    513: 		
1.166     foxr      514: 		   my $newline = "$id:$domain:$role:$name:$ip";
                    515: 		   if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    516: 		     $newline .= ":$maxcon:$idleto:$mincon";
                    517: 		   }
                    518: 		   $adjusted .= $newline."\n";
1.157     foxr      519: 		
1.166     foxr      520:       } else {		# Not me, pass unmodified.
                    521: 		   $adjusted .= $line."\n";
                    522:       }
1.157     foxr      523: 	} else {                  # Blank or comment never re-written.
                    524: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    525: 	}
1.166     foxr      526:  }
                    527:  return $adjusted;
1.157     foxr      528: }
1.143     foxr      529: #
                    530: #   InstallFile: Called to install an administrative file:
                    531: #       - The file is created with <name>.tmp
                    532: #       - The <name>.tmp file is then mv'd to <name>
                    533: #   This lugubrious procedure is done to ensure that we are never without
                    534: #   a valid, even if dated, version of the file regardless of who crashes
                    535: #   and when the crash occurs.
                    536: #
                    537: #  Parameters:
                    538: #       Name of the file
                    539: #       File Contents.
                    540: #  Return:
                    541: #      nonzero - success.
                    542: #      0       - failure and $! has an errno.
                    543: #
                    544: sub InstallFile {
1.192     foxr      545: 
                    546:     my ($Filename, $Contents) = @_;
1.143     foxr      547:     my $TempFile = $Filename.".tmp";
                    548: 
                    549:     #  Open the file for write:
                    550: 
                    551:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    552:     if(!(defined $fh)) {
                    553: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    554: 	return 0;
                    555:     }
                    556:     #  write the contents of the file:
                    557: 
                    558:     print $fh ($Contents); 
                    559:     $fh->close;			# In case we ever have a filesystem w. locking
                    560: 
                    561:     chmod(0660, $TempFile);
                    562: 
                    563:     # Now we can move install the file in position.
                    564:     
                    565:     move($TempFile, $Filename);
                    566: 
                    567:     return 1;
                    568: }
1.200     matthew   569: 
                    570: 
1.169     foxr      571: #
                    572: #   ConfigFileFromSelector: converts a configuration file selector
                    573: #                 (one of host or domain at this point) into a 
                    574: #                 configuration file pathname.
                    575: #
                    576: #  Parameters:
                    577: #      selector  - Configuration file selector.
                    578: #  Returns:
                    579: #      Full path to the file or undef if the selector is invalid.
                    580: #
                    581: sub ConfigFileFromSelector {
                    582:     my $selector   = shift;
                    583:     my $tablefile;
                    584: 
                    585:     my $tabledir = $perlvar{'lonTabDir'}.'/';
                    586:     if ($selector eq "hosts") {
                    587: 	$tablefile = $tabledir."hosts.tab";
                    588:     } elsif ($selector eq "domain") {
                    589: 	$tablefile = $tabledir."domain.tab";
                    590:     } else {
                    591: 	return undef;
                    592:     }
                    593:     return $tablefile;
1.143     foxr      594: 
1.169     foxr      595: }
1.143     foxr      596: #
1.141     foxr      597: #   PushFile:  Called to do an administrative push of a file.
                    598: #              - Ensure the file being pushed is one we support.
                    599: #              - Backup the old file to <filename.saved>
                    600: #              - Separate the contents of the new file out from the
                    601: #                rest of the request.
                    602: #              - Write the new file.
                    603: #  Parameter:
                    604: #     Request - The entire user request.  This consists of a : separated
                    605: #               string pushfile:tablename:contents.
                    606: #     NOTE:  The contents may have :'s in it as well making things a bit
                    607: #            more interesting... but not much.
                    608: #  Returns:
                    609: #     String to send to client ("ok" or "refused" if bad file).
                    610: #
                    611: sub PushFile {
                    612:     my $request = shift;    
                    613:     my ($command, $filename, $contents) = split(":", $request, 3);
                    614:     
                    615:     #  At this point in time, pushes for only the following tables are
                    616:     #  supported:
                    617:     #   hosts.tab  ($filename eq host).
                    618:     #   domain.tab ($filename eq domain).
                    619:     # Construct the destination filename or reject the request.
                    620:     #
                    621:     # lonManage is supposed to ensure this, however this session could be
                    622:     # part of some elaborate spoof that managed somehow to authenticate.
                    623:     #
                    624: 
1.169     foxr      625: 
                    626:     my $tablefile = ConfigFileFromSelector($filename);
                    627:     if(! (defined $tablefile)) {
1.141     foxr      628: 	return "refused";
                    629:     }
                    630:     #
                    631:     # >copy< the old table to the backup table
                    632:     #        don't rename in case system crashes/reboots etc. in the time
                    633:     #        window between a rename and write.
                    634:     #
                    635:     my $backupfile = $tablefile;
                    636:     $backupfile    =~ s/\.tab$/.old/;
1.143     foxr      637:     if(!CopyFile($tablefile, $backupfile)) {
                    638: 	&logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
                    639: 	return "error:$!";
                    640:     }
1.141     foxr      641:     &logthis('<font color="green"> Pushfile: backed up '
                    642: 	    .$tablefile." to $backupfile</font>");
                    643:     
1.157     foxr      644:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    645:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    646:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    647:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    648:     #  that possibilty.
                    649: 
                    650:     if($filename eq "host") {
                    651: 	$contents = AdjustHostContents($contents);
                    652:     }
                    653: 
1.141     foxr      654:     #  Install the new file:
                    655: 
1.143     foxr      656:     if(!InstallFile($tablefile, $contents)) {
                    657: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      658: 	 .$tablefile." $! </font>");
1.143     foxr      659: 	return "error:$!";
1.224     foxr      660:     } else {
1.143     foxr      661: 	&logthis('<font color="green"> Installed new '.$tablefile
                    662: 		 ."</font>");
                    663: 
                    664:     }
                    665: 
1.141     foxr      666: 
                    667:     #  Indicate success:
                    668:  
                    669:     return "ok";
                    670: 
                    671: }
1.145     foxr      672: 
                    673: #
                    674: #  Called to re-init either lonc or lond.
                    675: #
                    676: #  Parameters:
                    677: #    request   - The full request by the client.  This is of the form
                    678: #                reinit:<process>  
                    679: #                where <process> is allowed to be either of 
                    680: #                lonc or lond
                    681: #
                    682: #  Returns:
                    683: #     The string to be sent back to the client either:
                    684: #   ok         - Everything worked just fine.
                    685: #   error:why  - There was a failure and why describes the reason.
                    686: #
                    687: #
                    688: sub ReinitProcess {
                    689:     my $request = shift;
                    690: 
1.146     foxr      691: 
                    692:     # separate the request (reinit) from the process identifier and
                    693:     # validate it producing the name of the .pid file for the process.
                    694:     #
                    695:     #
                    696:     my ($junk, $process) = split(":", $request);
1.147     foxr      697:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      698:     if($process eq 'lonc') {
                    699: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      700: 	if (!open(PIDFILE, "< $processpidfile")) {
                    701: 	    return "error:Open failed for $processpidfile";
                    702: 	}
                    703: 	my $loncpid = <PIDFILE>;
                    704: 	close(PIDFILE);
                    705: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    706: 		."</font>");
                    707: 	kill("USR2", $loncpid);
1.146     foxr      708:     } elsif ($process eq 'lond') {
1.147     foxr      709: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    710: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      711:     } else {
                    712: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    713: 		 ."</font>");
                    714: 	return "error:Invalid process identifier $process";
                    715:     }
1.145     foxr      716:     return 'ok';
                    717: }
1.168     foxr      718: #   Validate a line in a configuration file edit script:
                    719: #   Validation includes:
                    720: #     - Ensuring the command is valid.
                    721: #     - Ensuring the command has sufficient parameters
                    722: #   Parameters:
                    723: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      724: #
1.168     foxr      725: #   Return:
                    726: #      0     - Invalid scriptline.
                    727: #      1     - Valid scriptline
                    728: #  NOTE:
                    729: #     Only the command syntax is checked, not the executability of the
                    730: #     command.
                    731: #
                    732: sub isValidEditCommand {
                    733:     my $scriptline = shift;
                    734: 
                    735:     #   Line elements are pipe separated:
                    736: 
                    737:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                    738:     &logthis('<font color="green"> isValideditCommand checking: '.
                    739: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                    740:     
                    741:     if ($command eq "delete") {
                    742: 	#
                    743: 	#   key with no newline.
                    744: 	#
                    745: 	if( ($key eq "") || ($newline ne "")) {
                    746: 	    return 0;		# Must have key but no newline.
                    747: 	} else {
                    748: 	    return 1;		# Valid syntax.
                    749: 	}
1.169     foxr      750:     } elsif ($command eq "replace") {
1.168     foxr      751: 	#
                    752: 	#   key and newline:
                    753: 	#
                    754: 	if (($key eq "") || ($newline eq "")) {
                    755: 	    return 0;
                    756: 	} else {
                    757: 	    return 1;
                    758: 	}
1.169     foxr      759:     } elsif ($command eq "append") {
                    760: 	if (($key ne "") && ($newline eq "")) {
                    761: 	    return 1;
                    762: 	} else {
                    763: 	    return 0;
                    764: 	}
1.168     foxr      765:     } else {
                    766: 	return 0;		# Invalid command.
                    767:     }
                    768:     return 0;			# Should not get here!!!
                    769: }
1.169     foxr      770: #
                    771: #   ApplyEdit - Applies an edit command to a line in a configuration 
                    772: #               file.  It is the caller's responsiblity to validate the
                    773: #               edit line.
                    774: #   Parameters:
                    775: #      $directive - A single edit directive to apply.  
                    776: #                   Edit directives are of the form:
                    777: #                  append|newline      - Appends a new line to the file.
                    778: #                  replace|key|newline - Replaces the line with key value 'key'
                    779: #                  delete|key          - Deletes the line with key value 'key'.
                    780: #      $editor   - A config file editor object that contains the
                    781: #                  file being edited.
                    782: #
                    783: sub ApplyEdit {
1.192     foxr      784: 
                    785:     my ($directive, $editor) = @_;
1.169     foxr      786: 
                    787:     # Break the directive down into its command and its parameters
                    788:     # (at most two at this point.  The meaning of the parameters, if in fact
                    789:     #  they exist depends on the command).
                    790: 
                    791:     my ($command, $p1, $p2) = split(/\|/, $directive);
                    792: 
                    793:     if($command eq "append") {
                    794: 	$editor->Append($p1);	          # p1 - key p2 null.
                    795:     } elsif ($command eq "replace") {
                    796: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                    797:     } elsif ($command eq "delete") {
                    798: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                    799:     } else {			          # Should not get here!!!
                    800: 	die "Invalid command given to ApplyEdit $command"
                    801:     }
                    802: }
                    803: #
                    804: # AdjustOurHost:
                    805: #           Adjusts a host file stored in a configuration file editor object
                    806: #           for the true IP address of this host. This is necessary for hosts
                    807: #           that live behind a firewall.
                    808: #           Those hosts have a publicly distributed IP of the firewall, but
                    809: #           internally must use their actual IP.  We assume that a given
                    810: #           host only has a single IP interface for now.
                    811: # Formal Parameters:
                    812: #     editor   - The configuration file editor to adjust.  This
                    813: #                editor is assumed to contain a hosts.tab file.
                    814: # Strategy:
                    815: #    - Figure out our hostname.
                    816: #    - Lookup the entry for this host.
                    817: #    - Modify the line to contain our IP
                    818: #    - Do a replace for this host.
                    819: sub AdjustOurHost {
                    820:     my $editor        = shift;
                    821: 
                    822:     # figure out who I am.
                    823: 
                    824:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                    825: 
                    826:     #  Get my host file entry.
                    827: 
                    828:     my $ConfigLine    = $editor->Find($myHostName);
                    829:     if(! (defined $ConfigLine)) {
                    830: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                    831:     }
                    832:     # figure out my IP:
                    833:     #   Use the config line to get my hostname.
                    834:     #   Use gethostbyname to translate that into an IP address.
                    835:     #
                    836:     my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
                    837:     my $BinaryIp = gethostbyname($name);
                    838:     my $ip       = inet_ntoa($ip);
                    839:     #
                    840:     #  Reassemble the config line from the elements in the list.
                    841:     #  Note that if the loncnew items were not present before, they will
                    842:     #  be now even if they would be empty
                    843:     #
                    844:     my $newConfigLine = $id;
                    845:     foreach my $item ($domain, $role, $name, $ip, $maxcon, $idleto, $mincon) {
                    846: 	$newConfigLine .= ":".$item;
                    847:     }
                    848:     #  Replace the line:
                    849: 
                    850:     $editor->ReplaceLine($id, $newConfigLine);
                    851:     
                    852: }
                    853: #
                    854: #   ReplaceConfigFile:
                    855: #              Replaces a configuration file with the contents of a
                    856: #              configuration file editor object.
                    857: #              This is done by:
                    858: #              - Copying the target file to <filename>.old
                    859: #              - Writing the new file to <filename>.tmp
                    860: #              - Moving <filename.tmp>  -> <filename>
                    861: #              This laborious process ensures that the system is never without
                    862: #              a configuration file that's at least valid (even if the contents
                    863: #              may be dated).
                    864: #   Parameters:
                    865: #        filename   - Name of the file to modify... this is a full path.
                    866: #        editor     - Editor containing the file.
                    867: #
                    868: sub ReplaceConfigFile {
1.192     foxr      869:     
                    870:     my ($filename, $editor) = @_;
1.168     foxr      871: 
1.169     foxr      872:     CopyFile ($filename, $filename.".old");
                    873: 
                    874:     my $contents  = $editor->Get(); # Get the contents of the file.
                    875: 
                    876:     InstallFile($filename, $contents);
                    877: }
1.168     foxr      878: #   
                    879: #
                    880: #   Called to edit a configuration table  file
1.167     foxr      881: #   Parameters:
                    882: #      request           - The entire command/request sent by lonc or lonManage
                    883: #   Return:
                    884: #      The reply to send to the client.
1.168     foxr      885: #
1.167     foxr      886: sub EditFile {
                    887:     my $request = shift;
                    888: 
                    889:     #  Split the command into it's pieces:  edit:filetype:script
                    890: 
1.168     foxr      891:     my ($request, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr      892: 
                    893:     #  Check the pre-coditions for success:
                    894: 
                    895:     if($request != "edit") {	# Something is amiss afoot alack.
                    896: 	return "error:edit request detected, but request != 'edit'\n";
                    897:     }
                    898:     if( ($filetype ne "hosts")  &&
                    899: 	($filetype ne "domain")) {
                    900: 	return "error:edit requested with invalid file specifier: $filetype \n";
                    901:     }
                    902: 
                    903:     #   Split the edit script and check it's validity.
1.168     foxr      904: 
                    905:     my @scriptlines = split(/\n/, $script);  # one line per element.
                    906:     my $linecount   = scalar(@scriptlines);
                    907:     for(my $i = 0; $i < $linecount; $i++) {
                    908: 	chomp($scriptlines[$i]);
                    909: 	if(!isValidEditCommand($scriptlines[$i])) {
                    910: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                    911: 	}
                    912:     }
1.145     foxr      913: 
1.167     foxr      914:     #   Execute the edit operation.
1.169     foxr      915:     #   - Create a config file editor for the appropriate file and 
                    916:     #   - execute each command in the script:
                    917:     #
                    918:     my $configfile = ConfigFileFromSelector($filetype);
                    919:     if (!(defined $configfile)) {
                    920: 	return "refused\n";
                    921:     }
                    922:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr      923: 
1.169     foxr      924:     for (my $i = 0; $i < $linecount; $i++) {
                    925: 	ApplyEdit($scriptlines[$i], $editor);
                    926:     }
                    927:     # If the file is the host file, ensure that our host is
                    928:     # adjusted to have our ip:
                    929:     #
                    930:     if($filetype eq "host") {
                    931: 	AdjustOurHost($editor);
                    932:     }
                    933:     #  Finally replace the current file with our file.
                    934:     #
                    935:     ReplaceConfigFile($configfile, $editor);
1.167     foxr      936: 
                    937:     return "ok\n";
                    938: }
1.207     foxr      939: 
                    940: #---------------------------------------------------------------
                    941: #
                    942: # Manipulation of hash based databases (factoring out common code
                    943: # for later use as we refactor.
                    944: #
                    945: #  Ties a domain level resource file to a hash.
                    946: #  If requested a history entry is created in the associated hist file.
                    947: #
                    948: #  Parameters:
                    949: #     domain    - Name of the domain in which the resource file lives.
                    950: #     namespace - Name of the hash within that domain.
                    951: #     how       - How to tie the hash (e.g. GDBM_WRCREAT()).
                    952: #     loghead   - Optional parameter, if present a log entry is created
                    953: #                 in the associated history file and this is the first part
                    954: #                  of that entry.
                    955: #     logtail   - Goes along with loghead,  The actual logentry is of the
                    956: #                 form $loghead:<timestamp>:logtail.
                    957: # Returns:
                    958: #    Reference to a hash bound to the db file or alternatively undef
                    959: #    if the tie failed.
                    960: #
1.209     albertel  961: sub tie_domain_hash {
1.210     albertel  962:     my ($domain,$namespace,$how,$loghead,$logtail) = @_;
1.207     foxr      963:     
                    964:     # Filter out any whitespace in the domain name:
                    965:     
                    966:     $domain =~ s/\W//g;
                    967:     
                    968:     # We have enough to go on to tie the hash:
                    969:     
                    970:     my $user_top_dir   = $perlvar{'lonUsersDir'};
                    971:     my $domain_dir     = $user_top_dir."/$domain";
                    972:     my $resource_file  = $domain_dir."/$namespace.db";
                    973:     my %hash;
                    974:     if(tie(%hash, 'GDBM_File', $resource_file, $how, 0640)) {
1.211     albertel  975: 	if (defined($loghead)) {	# Need to log the operation.
1.210     albertel  976: 	    my $logFh = IO::File->new(">>$domain_dir/$namespace.hist");
1.207     foxr      977: 	    if($logFh) {
                    978: 		my $timestamp = time;
                    979: 		print $logFh "$loghead:$timestamp:$logtail\n";
                    980: 	    }
1.210     albertel  981: 	    $logFh->close;
1.207     foxr      982: 	}
                    983: 	return \%hash;		# Return the tied hash.
1.210     albertel  984:     } else {
1.207     foxr      985: 	return undef;		# Tie failed.
                    986:     }
                    987: }
                    988: 
                    989: #
                    990: #   Ties a user's resource file to a hash.  
                    991: #   If necessary, an appropriate history
                    992: #   log file entry is made as well.
                    993: #   This sub factors out common code from the subs that manipulate
                    994: #   the various gdbm files that keep keyword value pairs.
                    995: # Parameters:
                    996: #   domain       - Name of the domain the user is in.
                    997: #   user         - Name of the 'current user'.
                    998: #   namespace    - Namespace representing the file to tie.
                    999: #   how          - What the tie is done to (e.g. GDBM_WRCREAT().
                   1000: #   loghead      - Optional first part of log entry if there may be a
                   1001: #                  history file.
                   1002: #   what         - Optional tail of log entry if there may be a history
                   1003: #                  file.
                   1004: # Returns:
                   1005: #   hash to which the database is tied.  It's up to the caller to untie.
                   1006: #   undef if the has could not be tied.
                   1007: #
1.210     albertel 1008: sub tie_user_hash {
                   1009:     my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
1.207     foxr     1010: 
                   1011:     $namespace=~s/\//\_/g;	# / -> _
                   1012:     $namespace=~s/\W//g;		# whitespace eliminated.
                   1013:     my $proname     = propath($domain, $user);
                   1014:    
                   1015:     #  Tie the database.
                   1016:     
                   1017:     my %hash;
                   1018:     if(tie(%hash, 'GDBM_File', "$proname/$namespace.db",
                   1019: 	   $how, 0640)) {
1.209     albertel 1020: 	# If this is a namespace for which a history is kept,
                   1021: 	# make the history log entry:    
1.252     albertel 1022: 	if (($namespace !~/^nohist\_/) && (defined($loghead))) {
1.209     albertel 1023: 	    my $args = scalar @_;
                   1024: 	    Debug(" Opening history: $namespace $args");
                   1025: 	    my $hfh = IO::File->new(">>$proname/$namespace.hist"); 
                   1026: 	    if($hfh) {
                   1027: 		my $now = time;
                   1028: 		print $hfh "$loghead:$now:$what\n";
                   1029: 	    }
1.210     albertel 1030: 	    $hfh->close;
1.209     albertel 1031: 	}
1.207     foxr     1032: 	return \%hash;
1.209     albertel 1033:     } else {
1.207     foxr     1034: 	return undef;
                   1035:     }
                   1036:     
                   1037: }
1.214     foxr     1038: 
1.255     foxr     1039: #   read_profile
                   1040: #
                   1041: #   Returns a set of specific entries from a user's profile file.
                   1042: #   this is a utility function that is used by both get_profile_entry and
                   1043: #   get_profile_entry_encrypted.
                   1044: #
                   1045: # Parameters:
                   1046: #    udom       - Domain in which the user exists.
                   1047: #    uname      - User's account name (loncapa account)
                   1048: #    namespace  - The profile namespace to open.
                   1049: #    what       - A set of & separated queries.
                   1050: # Returns:
                   1051: #    If all ok: - The string that needs to be shipped back to the user.
                   1052: #    If failure - A string that starts with error: followed by the failure
                   1053: #                 reason.. note that this probabyl gets shipped back to the
                   1054: #                 user as well.
                   1055: #
                   1056: sub read_profile {
                   1057:     my ($udom, $uname, $namespace, $what) = @_;
                   1058:     
                   1059:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1060: 				 &GDBM_READER());
                   1061:     if ($hashref) {
                   1062:         my @queries=split(/\&/,$what);
                   1063:         my $qresult='';
                   1064: 	
                   1065: 	for (my $i=0;$i<=$#queries;$i++) {
                   1066: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1067: 	}
                   1068: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
                   1069: 	if (untie %$hashref) {
                   1070: 	    return $qresult;
                   1071: 	} else {
                   1072: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1073: 	}
                   1074:     } else {
                   1075: 	if ($!+0 == 2) {
                   1076: 	    return "error:No such file or GDBM reported bad block error";
                   1077: 	} else {
                   1078: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1079: 	}
                   1080:     }
                   1081: 
                   1082: }
1.214     foxr     1083: #--------------------- Request Handlers --------------------------------------------
                   1084: #
1.215     foxr     1085: #   By convention each request handler registers itself prior to the sub 
                   1086: #   declaration:
1.214     foxr     1087: #
                   1088: 
1.216     foxr     1089: #++
                   1090: #
1.214     foxr     1091: #  Handles ping requests.
                   1092: #  Parameters:
                   1093: #      $cmd    - the actual keyword that invoked us.
                   1094: #      $tail   - the tail of the request that invoked us.
                   1095: #      $replyfd- File descriptor connected to the client
                   1096: #  Implicit Inputs:
                   1097: #      $currenthostid - Global variable that carries the name of the host we are
                   1098: #                       known as.
                   1099: #  Returns:
                   1100: #      1       - Ok to continue processing.
                   1101: #      0       - Program should exit.
                   1102: #  Side effects:
                   1103: #      Reply information is sent to the client.
                   1104: sub ping_handler {
                   1105:     my ($cmd, $tail, $client) = @_;
                   1106:     Debug("$cmd $tail $client .. $currenthostid:");
                   1107:    
                   1108:     Reply( $client,"$currenthostid\n","$cmd:$tail");
                   1109:    
                   1110:     return 1;
                   1111: }
                   1112: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1113: 
1.216     foxr     1114: #++
1.215     foxr     1115: #
                   1116: # Handles pong requests.  Pong replies with our current host id, and
                   1117: #                         the results of a ping sent to us via our lonc.
                   1118: #
                   1119: # Parameters:
                   1120: #      $cmd    - the actual keyword that invoked us.
                   1121: #      $tail   - the tail of the request that invoked us.
                   1122: #      $replyfd- File descriptor connected to the client
                   1123: #  Implicit Inputs:
                   1124: #      $currenthostid - Global variable that carries the name of the host we are
                   1125: #                       connected to.
                   1126: #  Returns:
                   1127: #      1       - Ok to continue processing.
                   1128: #      0       - Program should exit.
                   1129: #  Side effects:
                   1130: #      Reply information is sent to the client.
                   1131: sub pong_handler {
                   1132:     my ($cmd, $tail, $replyfd) = @_;
                   1133: 
                   1134:     my $reply=&reply("ping",$clientname);
                   1135:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1136:     return 1;
                   1137: }
                   1138: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1139: 
1.216     foxr     1140: #++
                   1141: #      Called to establish an encrypted session key with the remote client.
                   1142: #      Note that with secure lond, in most cases this function is never
                   1143: #      invoked.  Instead, the secure session key is established either
                   1144: #      via a local file that's locked down tight and only lives for a short
                   1145: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1146: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1147: #      by this sub.  This sub is only used in the old-style insecure
                   1148: #      key negotiation.
                   1149: # Parameters:
                   1150: #      $cmd    - the actual keyword that invoked us.
                   1151: #      $tail   - the tail of the request that invoked us.
                   1152: #      $replyfd- File descriptor connected to the client
                   1153: #  Implicit Inputs:
                   1154: #      $currenthostid - Global variable that carries the name of the host
                   1155: #                       known as.
                   1156: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
                   1157: #  Returns:
                   1158: #      1       - Ok to continue processing.
                   1159: #      0       - Program should exit.
                   1160: #  Implicit Outputs:
                   1161: #      Reply information is sent to the client.
                   1162: #      $cipher is set with a reference to a new IDEA encryption object.
                   1163: #
                   1164: sub establish_key_handler {
                   1165:     my ($cmd, $tail, $replyfd) = @_;
                   1166: 
                   1167:     my $buildkey=time.$$.int(rand 100000);
                   1168:     $buildkey=~tr/1-6/A-F/;
                   1169:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1170:     my $key=$currenthostid.$clientname;
                   1171:     $key=~tr/a-z/A-Z/;
                   1172:     $key=~tr/G-P/0-9/;
                   1173:     $key=~tr/Q-Z/0-9/;
                   1174:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1175:     $key=substr($key,0,32);
                   1176:     my $cipherkey=pack("H32",$key);
                   1177:     $cipher=new IDEA $cipherkey;
                   1178:     &Reply($replyfd, "$buildkey\n", "$cmd:$tail"); 
                   1179:    
                   1180:     return 1;
                   1181: 
                   1182: }
                   1183: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1184: 
1.217     foxr     1185: #     Handler for the load command.  Returns the current system load average
                   1186: #     to the requestor.
                   1187: #
                   1188: # Parameters:
                   1189: #      $cmd    - the actual keyword that invoked us.
                   1190: #      $tail   - the tail of the request that invoked us.
                   1191: #      $replyfd- File descriptor connected to the client
                   1192: #  Implicit Inputs:
                   1193: #      $currenthostid - Global variable that carries the name of the host
                   1194: #                       known as.
                   1195: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
                   1196: #  Returns:
                   1197: #      1       - Ok to continue processing.
                   1198: #      0       - Program should exit.
                   1199: #  Side effects:
                   1200: #      Reply information is sent to the client.
                   1201: sub load_handler {
                   1202:     my ($cmd, $tail, $replyfd) = @_;
                   1203: 
                   1204:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1205:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1206: 
                   1207:     my $loadavg;
                   1208:     my $loadfile=IO::File->new('/proc/loadavg');
                   1209:    
                   1210:     $loadavg=<$loadfile>;
                   1211:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1212:    
                   1213:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1214: 
                   1215:     &Reply( $replyfd, "$loadpercent\n", "$cmd:$tail");
                   1216:    
                   1217:     return 1;
                   1218: }
1.263     albertel 1219: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1220: 
                   1221: #
                   1222: #   Process the userload request.  This sub returns to the client the current
                   1223: #  user load average.  It can be invoked either by clients or managers.
                   1224: #
                   1225: # Parameters:
                   1226: #      $cmd    - the actual keyword that invoked us.
                   1227: #      $tail   - the tail of the request that invoked us.
                   1228: #      $replyfd- File descriptor connected to the client
                   1229: #  Implicit Inputs:
                   1230: #      $currenthostid - Global variable that carries the name of the host
                   1231: #                       known as.
                   1232: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
                   1233: #  Returns:
                   1234: #      1       - Ok to continue processing.
                   1235: #      0       - Program should exit
                   1236: # Implicit inputs:
                   1237: #     whatever the userload() function requires.
                   1238: #  Implicit outputs:
                   1239: #     the reply is written to the client.
                   1240: #
                   1241: sub user_load_handler {
                   1242:     my ($cmd, $tail, $replyfd) = @_;
                   1243: 
                   1244:     my $userloadpercent=&userload();
                   1245:     &Reply($replyfd, "$userloadpercent\n", "$cmd:$tail");
                   1246:     
                   1247:     return 1;
                   1248: }
1.263     albertel 1249: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1250: 
1.218     foxr     1251: #   Process a request for the authorization type of a user:
                   1252: #   (userauth).
                   1253: #
                   1254: # Parameters:
                   1255: #      $cmd    - the actual keyword that invoked us.
                   1256: #      $tail   - the tail of the request that invoked us.
                   1257: #      $replyfd- File descriptor connected to the client
                   1258: #  Returns:
                   1259: #      1       - Ok to continue processing.
                   1260: #      0       - Program should exit
                   1261: # Implicit outputs:
                   1262: #    The user authorization type is written to the client.
                   1263: #
                   1264: sub user_authorization_type {
                   1265:     my ($cmd, $tail, $replyfd) = @_;
                   1266:    
                   1267:     my $userinput = "$cmd:$tail";
                   1268:    
                   1269:     #  Pull the domain and username out of the command tail.
1.222     foxr     1270:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1271:    
                   1272:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1273:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1274:     if($result eq "nouser") {
                   1275: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1276:     } else {
                   1277: 	#
1.222     foxr     1278: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1279: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1280: 	# password for internals e.g.
                   1281: 	#
                   1282: 	my ($type,$otherinfo) = split(/:/,$result);
                   1283: 	if($type =~ /^krb/) {
                   1284: 	    $type = $result;
1.269     raeburn  1285: 	} else {
                   1286:             $type .= ':';
                   1287:         }
                   1288: 	&Reply( $replyfd, "$type\n", $userinput);
1.218     foxr     1289:     }
                   1290:   
                   1291:     return 1;
                   1292: }
                   1293: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1294: 
                   1295: #   Process a request by a manager to push a hosts or domain table 
                   1296: #   to us.  We pick apart the command and pass it on to the subs
                   1297: #   that already exist to do this.
                   1298: #
                   1299: # Parameters:
                   1300: #      $cmd    - the actual keyword that invoked us.
                   1301: #      $tail   - the tail of the request that invoked us.
                   1302: #      $client - File descriptor connected to the client
                   1303: #  Returns:
                   1304: #      1       - Ok to continue processing.
                   1305: #      0       - Program should exit
                   1306: # Implicit Output:
                   1307: #    a reply is written to the client.
                   1308: sub push_file_handler {
                   1309:     my ($cmd, $tail, $client) = @_;
                   1310: 
                   1311:     my $userinput = "$cmd:$tail";
                   1312: 
                   1313:     # At this time we only know that the IP of our partner is a valid manager
                   1314:     # the code below is a hook to do further authentication (e.g. to resolve
                   1315:     # spoofing).
                   1316: 
                   1317:     my $cert = &GetCertificate($userinput);
                   1318:     if(&ValidManager($cert)) { 
                   1319: 
                   1320: 	# Now presumably we have the bona fides of both the peer host and the
                   1321: 	# process making the request.
                   1322:       
                   1323: 	my $reply = &PushFile($userinput);
                   1324: 	&Reply($client, "$reply\n", $userinput);
                   1325: 
                   1326:     } else {
                   1327: 	&Failure( $client, "refused\n", $userinput);
                   1328:     } 
1.219     foxr     1329:     return 1;
1.218     foxr     1330: }
                   1331: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1332: 
1.243     banghart 1333: #
                   1334: #   du  - list the disk usuage of a directory recursively. 
                   1335: #    
                   1336: #   note: stolen code from the ls file handler
                   1337: #   under construction by Rick Banghart 
                   1338: #    .
                   1339: # Parameters:
                   1340: #    $cmd        - The command that dispatched us (du).
                   1341: #    $ududir     - The directory path to list... I'm not sure what this
                   1342: #                  is relative as things like ls:. return e.g.
                   1343: #                  no_such_dir.
                   1344: #    $client     - Socket open on the client.
                   1345: # Returns:
                   1346: #     1 - indicating that the daemon should not disconnect.
                   1347: # Side Effects:
                   1348: #   The reply is written to  $client.
                   1349: #
                   1350: sub du_handler {
                   1351:     my ($cmd, $ududir, $client) = @_;
1.251     foxr     1352:     my ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
                   1353:     my $userinput = "$cmd:$ududir";
                   1354: 
1.245     albertel 1355:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1356: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1357: 	return 1;
                   1358:     }
1.249     foxr     1359:     #  Since $ududir could have some nasties in it,
                   1360:     #  we will require that ududir is a valid
                   1361:     #  directory.  Just in case someone tries to
                   1362:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1363:     #  etc.
                   1364:     #
                   1365:     if (-d $ududir) {
                   1366: 	#  And as Shakespeare would say to make
1.251     foxr     1367: 	#  assurance double sure, 
                   1368: 	# use execute_command to ensure that the command is not executed in
                   1369: 	# a shell that can screw us up.
                   1370: 
                   1371: 	my $duout = execute_command("du -ks $ududir");
1.249     foxr     1372: 	$duout=~s/[^\d]//g; #preserve only the numbers
                   1373: 	&Reply($client,"$duout\n","$cmd:$ududir");
                   1374:     } else {
1.251     foxr     1375: 
                   1376: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
                   1377: 
1.249     foxr     1378:     }
1.243     banghart 1379:     return 1;
                   1380: }
                   1381: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1382: 
1.239     foxr     1383: #
1.280     matthew  1384: # The ls_handler routine should be considered obosolete and is retained
                   1385: # for communication with legacy servers.  Please see the ls2_handler.
                   1386: #
1.239     foxr     1387: #   ls  - list the contents of a directory.  For each file in the
                   1388: #    selected directory the filename followed by the full output of
                   1389: #    the stat function is returned.  The returned info for each
                   1390: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1391: # Parameters:
                   1392: #    $cmd        - The command that dispatched us (ls).
                   1393: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1394: #                  is relative as things like ls:. return e.g.
                   1395: #                  no_such_dir.
                   1396: #    $client     - Socket open on the client.
                   1397: # Returns:
                   1398: #     1 - indicating that the daemon should not disconnect.
                   1399: # Side Effects:
                   1400: #   The reply is written to  $client.
                   1401: #
                   1402: sub ls_handler {
1.280     matthew  1403:     # obsoleted by ls2_handler
1.239     foxr     1404:     my ($cmd, $ulsdir, $client) = @_;
                   1405: 
                   1406:     my $userinput = "$cmd:$ulsdir";
                   1407: 
                   1408:     my $obs;
                   1409:     my $rights;
                   1410:     my $ulsout='';
                   1411:     my $ulsfn;
                   1412:     if (-e $ulsdir) {
                   1413: 	if(-d $ulsdir) {
                   1414: 	    if (opendir(LSDIR,$ulsdir)) {
                   1415: 		while ($ulsfn=readdir(LSDIR)) {
                   1416: 		    undef $obs, $rights; 
                   1417: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1418: 		    #We do some obsolete checking here
                   1419: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1420: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1421: 			my @obsolete=<FILE>;
                   1422: 			foreach my $obsolete (@obsolete) {
                   1423: 			    if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; } 
                   1424: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1425: 			}
                   1426: 		    }
                   1427: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1428: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1429: 		    else { $ulsout.="&0"; }
                   1430: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1431: 		    else { $ulsout.="&0:"; }
                   1432: 		}
                   1433: 		closedir(LSDIR);
                   1434: 	    }
                   1435: 	} else {
                   1436: 	    my @ulsstats=stat($ulsdir);
                   1437: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1438: 	}
                   1439:     } else {
                   1440: 	$ulsout='no_such_dir';
                   1441:     }
                   1442:     if ($ulsout eq '') { $ulsout='empty'; }
1.249     foxr     1443:     &Reply($client, "$ulsout\n", $userinput); # This supports debug logging.
1.239     foxr     1444:     
                   1445:     return 1;
                   1446: 
                   1447: }
                   1448: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1449: 
1.280     matthew  1450: #
                   1451: # Please also see the ls_handler, which this routine obosolets.
                   1452: # ls2_handler differs from ls_handler in that it escapes its return 
                   1453: # values before concatenating them together with ':'s.
                   1454: #
                   1455: #   ls2  - list the contents of a directory.  For each file in the
                   1456: #    selected directory the filename followed by the full output of
                   1457: #    the stat function is returned.  The returned info for each
                   1458: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1459: # Parameters:
                   1460: #    $cmd        - The command that dispatched us (ls).
                   1461: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1462: #                  is relative as things like ls:. return e.g.
                   1463: #                  no_such_dir.
                   1464: #    $client     - Socket open on the client.
                   1465: # Returns:
                   1466: #     1 - indicating that the daemon should not disconnect.
                   1467: # Side Effects:
                   1468: #   The reply is written to  $client.
                   1469: #
                   1470: sub ls2_handler {
                   1471:     my ($cmd, $ulsdir, $client) = @_;
                   1472: 
                   1473:     my $userinput = "$cmd:$ulsdir";
                   1474: 
                   1475:     my $obs;
                   1476:     my $rights;
                   1477:     my $ulsout='';
                   1478:     my $ulsfn;
                   1479:     if (-e $ulsdir) {
                   1480:         if(-d $ulsdir) {
                   1481:             if (opendir(LSDIR,$ulsdir)) {
                   1482:                 while ($ulsfn=readdir(LSDIR)) {
                   1483:                     undef $obs, $rights; 
                   1484:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1485:                     #We do some obsolete checking here
                   1486:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1487:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1488:                         my @obsolete=<FILE>;
                   1489:                         foreach my $obsolete (@obsolete) {
                   1490:                             if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; } 
                   1491:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1492:                                 $rights = 1;
                   1493:                             }
                   1494:                         }
                   1495:                     }
                   1496:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1497:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1498:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1499:                     $ulsout.= &escape($tmp).':';
                   1500:                 }
                   1501:                 closedir(LSDIR);
                   1502:             }
                   1503:         } else {
                   1504:             my @ulsstats=stat($ulsdir);
                   1505:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1506:         }
                   1507:     } else {
                   1508:         $ulsout='no_such_dir';
                   1509:    }
                   1510:    if ($ulsout eq '') { $ulsout='empty'; }
                   1511:    &Reply($client, "$ulsout\n", $userinput); # This supports debug logging.
                   1512:    return 1;
                   1513: }
                   1514: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
                   1515: 
1.218     foxr     1516: #   Process a reinit request.  Reinit requests that either
                   1517: #   lonc or lond be reinitialized so that an updated 
                   1518: #   host.tab or domain.tab can be processed.
                   1519: #
                   1520: # Parameters:
                   1521: #      $cmd    - the actual keyword that invoked us.
                   1522: #      $tail   - the tail of the request that invoked us.
                   1523: #      $client - File descriptor connected to the client
                   1524: #  Returns:
                   1525: #      1       - Ok to continue processing.
                   1526: #      0       - Program should exit
                   1527: #  Implicit output:
                   1528: #     a reply is sent to the client.
                   1529: #
                   1530: sub reinit_process_handler {
                   1531:     my ($cmd, $tail, $client) = @_;
                   1532:    
                   1533:     my $userinput = "$cmd:$tail";
                   1534:    
                   1535:     my $cert = &GetCertificate($userinput);
                   1536:     if(&ValidManager($cert)) {
                   1537: 	chomp($userinput);
                   1538: 	my $reply = &ReinitProcess($userinput);
                   1539: 	&Reply( $client,  "$reply\n", $userinput);
                   1540:     } else {
                   1541: 	&Failure( $client, "refused\n", $userinput);
                   1542:     }
                   1543:     return 1;
                   1544: }
                   1545: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   1546: 
                   1547: #  Process the editing script for a table edit operation.
                   1548: #  the editing operation must be encrypted and requested by
                   1549: #  a manager host.
                   1550: #
                   1551: # Parameters:
                   1552: #      $cmd    - the actual keyword that invoked us.
                   1553: #      $tail   - the tail of the request that invoked us.
                   1554: #      $client - File descriptor connected to the client
                   1555: #  Returns:
                   1556: #      1       - Ok to continue processing.
                   1557: #      0       - Program should exit
                   1558: #  Implicit output:
                   1559: #     a reply is sent to the client.
                   1560: #
                   1561: sub edit_table_handler {
                   1562:     my ($command, $tail, $client) = @_;
                   1563:    
                   1564:     my $userinput = "$command:$tail";
                   1565: 
                   1566:     my $cert = &GetCertificate($userinput);
                   1567:     if(&ValidManager($cert)) {
                   1568: 	my($filetype, $script) = split(/:/, $tail);
                   1569: 	if (($filetype eq "hosts") || 
                   1570: 	    ($filetype eq "domain")) {
                   1571: 	    if($script ne "") {
                   1572: 		&Reply($client,              # BUGBUG - EditFile
                   1573: 		      &EditFile($userinput), #   could fail.
                   1574: 		      $userinput);
                   1575: 	    } else {
                   1576: 		&Failure($client,"refused\n",$userinput);
                   1577: 	    }
                   1578: 	} else {
                   1579: 	    &Failure($client,"refused\n",$userinput);
                   1580: 	}
                   1581:     } else {
                   1582: 	&Failure($client,"refused\n",$userinput);
                   1583:     }
                   1584:     return 1;
                   1585: }
1.263     albertel 1586: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     1587: 
1.220     foxr     1588: #
                   1589: #   Authenticate a user against the LonCAPA authentication
                   1590: #   database.  Note that there are several authentication
                   1591: #   possibilities:
                   1592: #   - unix     - The user can be authenticated against the unix
                   1593: #                password file.
                   1594: #   - internal - The user can be authenticated against a purely 
                   1595: #                internal per user password file.
                   1596: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   1597: #                ticket granting authority.
                   1598: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   1599: #                mechanism that is per system.
                   1600: #
                   1601: # Parameters:
                   1602: #    $cmd      - The command that got us here.
                   1603: #    $tail     - Tail of the command (remaining parameters).
                   1604: #    $client   - File descriptor connected to client.
                   1605: # Returns
                   1606: #     0        - Requested to exit, caller should shut down.
                   1607: #     1        - Continue processing.
                   1608: # Implicit inputs:
                   1609: #    The authentication systems describe above have their own forms of implicit
                   1610: #    input into the authentication process that are described above.
                   1611: #
                   1612: sub authenticate_handler {
                   1613:     my ($cmd, $tail, $client) = @_;
                   1614: 
                   1615:     
                   1616:     #  Regenerate the full input line 
                   1617:     
                   1618:     my $userinput  = $cmd.":".$tail;
                   1619:     
                   1620:     #  udom    - User's domain.
                   1621:     #  uname   - Username.
                   1622:     #  upass   - User's password.
                   1623:     
                   1624:     my ($udom,$uname,$upass)=split(/:/,$tail);
                   1625:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass");
                   1626:     chomp($upass);
                   1627:     $upass=&unescape($upass);
                   1628: 
                   1629:     my $pwdcorrect = &validate_user($udom, $uname, $upass);
                   1630:     if($pwdcorrect) {
                   1631: 	&Reply( $client, "authorized\n", $userinput);
                   1632: 	#
                   1633: 	#  Bad credentials: Failed to authorize
                   1634: 	#
                   1635:     } else {
                   1636: 	&Failure( $client, "non_authorized\n", $userinput);
                   1637:     }
                   1638: 
                   1639:     return 1;
                   1640: }
1.263     albertel 1641: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     1642: 
1.222     foxr     1643: #
                   1644: #   Change a user's password.  Note that this function is complicated by
                   1645: #   the fact that a user may be authenticated in more than one way:
                   1646: #   At present, we are not able to change the password for all types of
                   1647: #   authentication methods.  Only for:
                   1648: #      unix    - unix password or shadow passoword style authentication.
                   1649: #      local   - Locally written authentication mechanism.
                   1650: #   For now, kerb4 and kerb5 password changes are not supported and result
                   1651: #   in an error.
                   1652: # FUTURE WORK:
                   1653: #    Support kerberos passwd changes?
                   1654: # Parameters:
                   1655: #    $cmd      - The command that got us here.
                   1656: #    $tail     - Tail of the command (remaining parameters).
                   1657: #    $client   - File descriptor connected to client.
                   1658: # Returns
                   1659: #     0        - Requested to exit, caller should shut down.
                   1660: #     1        - Continue processing.
                   1661: # Implicit inputs:
                   1662: #    The authentication systems describe above have their own forms of implicit
                   1663: #    input into the authentication process that are described above.
                   1664: sub change_password_handler {
                   1665:     my ($cmd, $tail, $client) = @_;
                   1666: 
                   1667:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   1668: 
                   1669:     #
                   1670:     #  udom  - user's domain.
                   1671:     #  uname - Username.
                   1672:     #  upass - Current password.
                   1673:     #  npass - New password.
                   1674:    
                   1675:     my ($udom,$uname,$upass,$npass)=split(/:/,$tail);
                   1676: 
                   1677:     $upass=&unescape($upass);
                   1678:     $npass=&unescape($npass);
                   1679:     &Debug("Trying to change password for $uname");
                   1680: 
                   1681:     # First require that the user can be authenticated with their
                   1682:     # old password:
                   1683: 
                   1684:     my $validated = &validate_user($udom, $uname, $upass);
                   1685:     if($validated) {
                   1686: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   1687: 	
                   1688: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   1689: 	if ($howpwd eq 'internal') {
                   1690: 	    &Debug("internal auth");
                   1691: 	    my $salt=time;
                   1692: 	    $salt=substr($salt,6,2);
                   1693: 	    my $ncpass=crypt($npass,$salt);
                   1694: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
                   1695: 		&logthis("Result of password change for "
                   1696: 			 ."$uname: pwchange_success");
                   1697: 		&Reply($client, "ok\n", $userinput);
                   1698: 	    } else {
                   1699: 		&logthis("Unable to open $uname passwd "               
                   1700: 			 ."to change password");
                   1701: 		&Failure( $client, "non_authorized\n",$userinput);
                   1702: 	    }
                   1703: 	} elsif ($howpwd eq 'unix') {
1.287     foxr     1704: 	    my $result = &change_unix_password($uname, $npass);
1.222     foxr     1705: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     1706: 		     $result);
1.222     foxr     1707: 	    &Reply($client, "$result\n", $userinput);
                   1708: 	} else {
                   1709: 	    # this just means that the current password mode is not
                   1710: 	    # one we know how to change (e.g the kerberos auth modes or
                   1711: 	    # locally written auth handler).
                   1712: 	    #
                   1713: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   1714: 	}  
                   1715: 	
1.224     foxr     1716:     } else {
1.222     foxr     1717: 	&Failure( $client, "non_authorized\n", $userinput);
                   1718:     }
                   1719: 
                   1720:     return 1;
                   1721: }
1.263     albertel 1722: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     1723: 
1.225     foxr     1724: #
                   1725: #   Create a new user.  User in this case means a lon-capa user.
                   1726: #   The user must either already exist in some authentication realm
                   1727: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   1728: #   this loncapa system is created.
                   1729: #
                   1730: # Parameters:
                   1731: #    $cmd      - The command that got us here.
                   1732: #    $tail     - Tail of the command (remaining parameters).
                   1733: #    $client   - File descriptor connected to client.
                   1734: # Returns
                   1735: #     0        - Requested to exit, caller should shut down.
                   1736: #     1        - Continue processing.
                   1737: # Implicit inputs:
                   1738: #    The authentication systems describe above have their own forms of implicit
                   1739: #    input into the authentication process that are described above.
                   1740: sub add_user_handler {
                   1741: 
                   1742:     my ($cmd, $tail, $client) = @_;
                   1743: 
                   1744: 
                   1745:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   1746:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   1747: 
                   1748:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   1749: 
                   1750: 
                   1751:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   1752: 	
                   1753: 	my $oldumask=umask(0077);
                   1754: 	chomp($npass);
                   1755: 	$npass=&unescape($npass);
                   1756: 	my $passfilename  = &password_path($udom, $uname);
                   1757: 	&Debug("Password file created will be:".$passfilename);
                   1758: 	if (-e $passfilename) {
                   1759: 	    &Failure( $client, "already_exists\n", $userinput);
                   1760: 	} else {
                   1761: 	    my $fperror='';
1.264     albertel 1762: 	    if (!&mkpath($passfilename)) {
                   1763: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   1764: 		    ."makeuser";
1.225     foxr     1765: 	    }
                   1766: 	    unless ($fperror) {
                   1767: 		my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
                   1768: 		&Reply($client, $result, $userinput);     #BUGBUG - could be fail
                   1769: 	    } else {
                   1770: 		&Failure($client, "$fperror\n", $userinput);
                   1771: 	    }
                   1772: 	}
                   1773: 	umask($oldumask);
                   1774:     }  else {
                   1775: 	&Failure($client, "not_right_domain\n",
                   1776: 		$userinput);	# Even if we are multihomed.
                   1777:     
                   1778:     }
                   1779:     return 1;
                   1780: 
                   1781: }
                   1782: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   1783: 
                   1784: #
                   1785: #   Change the authentication method of a user.  Note that this may
                   1786: #   also implicitly change the user's password if, for example, the user is
                   1787: #   joining an existing authentication realm.  Known authentication realms at
                   1788: #   this time are:
                   1789: #    internal   - Purely internal password file (only loncapa knows this user)
                   1790: #    local      - Institutionally written authentication module.
                   1791: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   1792: #    kerb4      - kerberos version 4
                   1793: #    kerb5      - kerberos version 5
                   1794: #
                   1795: # Parameters:
                   1796: #    $cmd      - The command that got us here.
                   1797: #    $tail     - Tail of the command (remaining parameters).
                   1798: #    $client   - File descriptor connected to client.
                   1799: # Returns
                   1800: #     0        - Requested to exit, caller should shut down.
                   1801: #     1        - Continue processing.
                   1802: # Implicit inputs:
                   1803: #    The authentication systems describe above have their own forms of implicit
                   1804: #    input into the authentication process that are described above.
1.287     foxr     1805: # NOTE:
                   1806: #   This is also used to change the authentication credential values (e.g. passwd).
                   1807: #   
1.225     foxr     1808: #
                   1809: sub change_authentication_handler {
                   1810: 
                   1811:     my ($cmd, $tail, $client) = @_;
                   1812:    
                   1813:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   1814: 
                   1815:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   1816:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   1817:     if ($udom ne $currentdomainid) {
                   1818: 	&Failure( $client, "not_right_domain\n", $client);
                   1819:     } else {
                   1820: 	
                   1821: 	chomp($npass);
                   1822: 	
                   1823: 	$npass=&unescape($npass);
1.261     foxr     1824: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     1825: 	my $passfilename = &password_path($udom, $uname);
                   1826: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     1827: 	    # If just changing the unix passwd. need to arrange to run
                   1828: 	    # passwd since otherwise make_passwd_file will run
                   1829: 	    # lcuseradd which fails if an account already exists
                   1830: 	    # (to prevent an unscrupulous LONCAPA admin from stealing
                   1831: 	    # an existing account by overwriting it as a LonCAPA account).
                   1832: 
                   1833: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   1834: 		my $result = &change_unix_password($uname, $npass);
                   1835: 		&logthis("Result of password change for $uname: ".$result);
                   1836: 		if ($result eq "ok") {
                   1837: 		    &Reply($client, "$result\n")
1.288   ! albertel 1838: 		} else {
1.287     foxr     1839: 		    &Failure($client, "$result\n");
                   1840: 		}
1.288   ! albertel 1841: 	    } else {
1.287     foxr     1842: 		my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
                   1843: 		#
                   1844: 		#  If the current auth mode is internal, and the old auth mode was
                   1845: 		#  unix, or krb*,  and the user is an author for this domain,
                   1846: 		#  re-run manage_permissions for that role in order to be able
                   1847: 		#  to take ownership of the construction space back to www:www
                   1848: 		#
                   1849: 		
                   1850: 		
                   1851: 		if( (($oldauth =~ /^unix/) && ($umode eq "internal")) ||
                   1852: 		    (($oldauth =~ /^internal/) && ($umode eq "unix")) ) { 
                   1853: 		    if(&is_author($udom, $uname)) {
                   1854: 			&Debug(" Need to manage author permissions...");
                   1855: 			&manage_permissions("/$udom/_au", $udom, $uname, "$umode:");
                   1856: 		    }
1.261     foxr     1857: 		}
1.287     foxr     1858: 		&Reply($client, $result, $userinput);
1.261     foxr     1859: 	    }
                   1860: 	       
                   1861: 
1.225     foxr     1862: 	} else {	       
1.251     foxr     1863: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     1864: 	}
                   1865:     }
                   1866:     return 1;
                   1867: }
                   1868: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   1869: 
                   1870: #
                   1871: #   Determines if this is the home server for a user.  The home server
                   1872: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   1873: #   to do is determine if this file exists.
                   1874: #
                   1875: # Parameters:
                   1876: #    $cmd      - The command that got us here.
                   1877: #    $tail     - Tail of the command (remaining parameters).
                   1878: #    $client   - File descriptor connected to client.
                   1879: # Returns
                   1880: #     0        - Requested to exit, caller should shut down.
                   1881: #     1        - Continue processing.
                   1882: # Implicit inputs:
                   1883: #    The authentication systems describe above have their own forms of implicit
                   1884: #    input into the authentication process that are described above.
                   1885: #
                   1886: sub is_home_handler {
                   1887:     my ($cmd, $tail, $client) = @_;
                   1888:    
                   1889:     my $userinput  = "$cmd:$tail";
                   1890:    
                   1891:     my ($udom,$uname)=split(/:/,$tail);
                   1892:     chomp($uname);
                   1893:     my $passfile = &password_filename($udom, $uname);
                   1894:     if($passfile) {
                   1895: 	&Reply( $client, "found\n", $userinput);
                   1896:     } else {
                   1897: 	&Failure($client, "not_found\n", $userinput);
                   1898:     }
                   1899:     return 1;
                   1900: }
                   1901: &register_handler("home", \&is_home_handler, 0,1,0);
                   1902: 
                   1903: #
                   1904: #   Process an update request for a resource?? I think what's going on here is
                   1905: #   that a resource has been modified that we hold a subscription to.
                   1906: #   If the resource is not local, then we must update, or at least invalidate our
                   1907: #   cached copy of the resource. 
                   1908: #   FUTURE WORK:
                   1909: #      I need to look at this logic carefully.  My druthers would be to follow
                   1910: #      typical caching logic, and simple invalidate the cache, drop any subscription
                   1911: #      an let the next fetch start the ball rolling again... however that may
                   1912: #      actually be more difficult than it looks given the complex web of
                   1913: #      proxy servers.
                   1914: # Parameters:
                   1915: #    $cmd      - The command that got us here.
                   1916: #    $tail     - Tail of the command (remaining parameters).
                   1917: #    $client   - File descriptor connected to client.
                   1918: # Returns
                   1919: #     0        - Requested to exit, caller should shut down.
                   1920: #     1        - Continue processing.
                   1921: # Implicit inputs:
                   1922: #    The authentication systems describe above have their own forms of implicit
                   1923: #    input into the authentication process that are described above.
                   1924: #
                   1925: sub update_resource_handler {
                   1926: 
                   1927:     my ($cmd, $tail, $client) = @_;
                   1928:    
                   1929:     my $userinput = "$cmd:$tail";
                   1930:    
                   1931:     my $fname= $tail;		# This allows interactive testing
                   1932: 
                   1933: 
                   1934:     my $ownership=ishome($fname);
                   1935:     if ($ownership eq 'not_owner') {
                   1936: 	if (-e $fname) {
                   1937: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   1938: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   1939: 	    my $now=time;
                   1940: 	    my $since=$now-$atime;
                   1941: 	    if ($since>$perlvar{'lonExpire'}) {
                   1942: 		my $reply=&reply("unsub:$fname","$clientname");
                   1943: 		unlink("$fname");
                   1944: 	    } else {
                   1945: 		my $transname="$fname.in.transfer";
                   1946: 		my $remoteurl=&reply("sub:$fname","$clientname");
                   1947: 		my $response;
                   1948: 		alarm(120);
                   1949: 		{
                   1950: 		    my $ua=new LWP::UserAgent;
                   1951: 		    my $request=new HTTP::Request('GET',"$remoteurl");
                   1952: 		    $response=$ua->request($request,$transname);
                   1953: 		}
                   1954: 		alarm(0);
                   1955: 		if ($response->is_error()) {
                   1956: 		    unlink($transname);
                   1957: 		    my $message=$response->status_line;
                   1958: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   1959: 		} else {
                   1960: 		    if ($remoteurl!~/\.meta$/) {
                   1961: 			alarm(120);
                   1962: 			{
                   1963: 			    my $ua=new LWP::UserAgent;
                   1964: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1965: 			    my $mresponse=$ua->request($mrequest,$fname.'.meta');
                   1966: 			    if ($mresponse->is_error()) {
                   1967: 				unlink($fname.'.meta');
                   1968: 			    }
                   1969: 			}
                   1970: 			alarm(0);
                   1971: 		    }
                   1972: 		    rename($transname,$fname);
                   1973: 		}
                   1974: 	    }
                   1975: 	    &Reply( $client, "ok\n", $userinput);
                   1976: 	} else {
                   1977: 	    &Failure($client, "not_found\n", $userinput);
                   1978: 	}
                   1979:     } else {
                   1980: 	&Failure($client, "rejected\n", $userinput);
                   1981:     }
                   1982:     return 1;
                   1983: }
                   1984: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   1985: 
                   1986: #
1.226     foxr     1987: #   Fetch a user file from a remote server to the user's home directory
                   1988: #   userfiles subdir.
1.225     foxr     1989: # Parameters:
                   1990: #    $cmd      - The command that got us here.
                   1991: #    $tail     - Tail of the command (remaining parameters).
                   1992: #    $client   - File descriptor connected to client.
                   1993: # Returns
                   1994: #     0        - Requested to exit, caller should shut down.
                   1995: #     1        - Continue processing.
                   1996: #
                   1997: sub fetch_user_file_handler {
                   1998: 
                   1999:     my ($cmd, $tail, $client) = @_;
                   2000: 
                   2001:     my $userinput = "$cmd:$tail";
                   2002:     my $fname           = $tail;
1.232     foxr     2003:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2004:     my $udir=&propath($udom,$uname).'/userfiles';
                   2005:     unless (-e $udir) {
                   2006: 	mkdir($udir,0770); 
                   2007:     }
1.232     foxr     2008:     Debug("fetch user file for $fname");
1.225     foxr     2009:     if (-e $udir) {
                   2010: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2011: 
                   2012: 	# IF necessary, create the path right down to the file.
                   2013: 	# Note that any regular files in the way of this path are
                   2014: 	# wiped out to deal with some earlier folly of mine.
                   2015: 
1.267     raeburn  2016: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2017: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2018: 	}
                   2019: 
1.225     foxr     2020: 	my $destname=$udir.'/'.$ufile;
                   2021: 	my $transname=$udir.'/'.$ufile.'.in.transit';
                   2022: 	my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
                   2023: 	my $response;
1.232     foxr     2024: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.225     foxr     2025: 	alarm(120);
                   2026: 	{
                   2027: 	    my $ua=new LWP::UserAgent;
                   2028: 	    my $request=new HTTP::Request('GET',"$remoteurl");
                   2029: 	    $response=$ua->request($request,$transname);
                   2030: 	}
                   2031: 	alarm(0);
                   2032: 	if ($response->is_error()) {
                   2033: 	    unlink($transname);
                   2034: 	    my $message=$response->status_line;
                   2035: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2036: 	    &Failure($client, "failed\n", $userinput);
                   2037: 	} else {
1.232     foxr     2038: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2039: 	    if (!rename($transname,$destname)) {
                   2040: 		&logthis("Unable to move $transname to $destname");
                   2041: 		unlink($transname);
                   2042: 		&Failure($client, "failed\n", $userinput);
                   2043: 	    } else {
                   2044: 		&Reply($client, "ok\n", $userinput);
                   2045: 	    }
                   2046: 	}   
                   2047:     } else {
                   2048: 	&Failure($client, "not_home\n", $userinput);
                   2049:     }
                   2050:     return 1;
                   2051: }
                   2052: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2053: 
1.226     foxr     2054: #
                   2055: #   Remove a file from a user's home directory userfiles subdirectory.
                   2056: # Parameters:
                   2057: #    cmd   - the Lond request keyword that got us here.
                   2058: #    tail  - the part of the command past the keyword.
                   2059: #    client- File descriptor connected with the client.
                   2060: #
                   2061: # Returns:
                   2062: #    1    - Continue processing.
                   2063: sub remove_user_file_handler {
                   2064:     my ($cmd, $tail, $client) = @_;
                   2065: 
                   2066:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2067: 
                   2068:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2069:     if ($ufile =~m|/\.\./|) {
                   2070: 	# any files paths with /../ in them refuse 
                   2071: 	# to deal with
                   2072: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2073:     } else {
                   2074: 	my $udir = &propath($udom,$uname);
                   2075: 	if (-e $udir) {
                   2076: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2077: 	    if (-e $file) {
1.253     foxr     2078: 		#
                   2079: 		#   If the file is a regular file unlink is fine...
                   2080: 		#   However it's possible the client wants a dir.
                   2081: 		#   removed, in which case rmdir is more approprate:
                   2082: 		#
1.240     banghart 2083: 	        if (-f $file){
1.241     albertel 2084: 		    unlink($file);
                   2085: 		} elsif(-d $file) {
                   2086: 		    rmdir($file);
1.240     banghart 2087: 		}
1.226     foxr     2088: 		if (-e $file) {
1.253     foxr     2089: 		    #  File is still there after we deleted it ?!?
                   2090: 
1.226     foxr     2091: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2092: 		} else {
                   2093: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2094: 		}
                   2095: 	    } else {
                   2096: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2097: 	    }
                   2098: 	} else {
                   2099: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2100: 	}
                   2101:     }
                   2102:     return 1;
                   2103: }
                   2104: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2105: 
1.236     albertel 2106: #
                   2107: #   make a directory in a user's home directory userfiles subdirectory.
                   2108: # Parameters:
                   2109: #    cmd   - the Lond request keyword that got us here.
                   2110: #    tail  - the part of the command past the keyword.
                   2111: #    client- File descriptor connected with the client.
                   2112: #
                   2113: # Returns:
                   2114: #    1    - Continue processing.
                   2115: sub mkdir_user_file_handler {
                   2116:     my ($cmd, $tail, $client) = @_;
                   2117: 
                   2118:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2119:     $dir=&unescape($dir);
                   2120:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2121:     if ($ufile =~m|/\.\./|) {
                   2122: 	# any files paths with /../ in them refuse 
                   2123: 	# to deal with
                   2124: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2125:     } else {
                   2126: 	my $udir = &propath($udom,$uname);
                   2127: 	if (-e $udir) {
1.264     albertel 2128: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2129: 	    if (!&mkpath($newdir)) {
                   2130: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2131: 	    }
1.264     albertel 2132: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2133: 	} else {
                   2134: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2135: 	}
                   2136:     }
                   2137:     return 1;
                   2138: }
                   2139: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2140: 
1.237     albertel 2141: #
                   2142: #   rename a file in a user's home directory userfiles subdirectory.
                   2143: # Parameters:
                   2144: #    cmd   - the Lond request keyword that got us here.
                   2145: #    tail  - the part of the command past the keyword.
                   2146: #    client- File descriptor connected with the client.
                   2147: #
                   2148: # Returns:
                   2149: #    1    - Continue processing.
                   2150: sub rename_user_file_handler {
                   2151:     my ($cmd, $tail, $client) = @_;
                   2152: 
                   2153:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2154:     $old=&unescape($old);
                   2155:     $new=&unescape($new);
                   2156:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2157: 	# any files paths with /../ in them refuse to deal with
                   2158: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2159:     } else {
                   2160: 	my $udir = &propath($udom,$uname);
                   2161: 	if (-e $udir) {
                   2162: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2163: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2164: 	    if (-e $newfile) {
                   2165: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2166: 	    } elsif (! -e $oldfile) {
                   2167: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2168: 	    } else {
                   2169: 		if (!rename($oldfile,$newfile)) {
                   2170: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2171: 		} else {
                   2172: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2173: 		}
                   2174: 	    }
                   2175: 	} else {
                   2176: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2177: 	}
                   2178:     }
                   2179:     return 1;
                   2180: }
                   2181: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2182: 
1.227     foxr     2183: #
1.263     albertel 2184: #  Authenticate access to a user file by checking that the token the user's 
                   2185: #  passed also exists in their session file
1.227     foxr     2186: #
                   2187: # Parameters:
                   2188: #   cmd      - The request keyword that dispatched to tus.
                   2189: #   tail     - The tail of the request (colon separated parameters).
                   2190: #   client   - Filehandle open on the client.
                   2191: # Return:
                   2192: #    1.
                   2193: sub token_auth_user_file_handler {
                   2194:     my ($cmd, $tail, $client) = @_;
                   2195: 
                   2196:     my ($fname, $session) = split(/:/, $tail);
                   2197:     
                   2198:     chomp($session);
1.251     foxr     2199:     my $reply="non_auth\n";
1.227     foxr     2200:     if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
                   2201: 	     $session.'.id')) {
                   2202: 	while (my $line=<ENVIN>) {
1.251     foxr     2203: 	    if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply="ok\n"; }
1.227     foxr     2204: 	}
                   2205: 	close(ENVIN);
1.251     foxr     2206: 	&Reply($client, $reply, "$cmd:$tail");
1.227     foxr     2207:     } else {
                   2208: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2209:     }
                   2210:     return 1;
                   2211: 
                   2212: }
                   2213: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2214: 
                   2215: #
                   2216: #   Unsubscribe from a resource.
                   2217: #
                   2218: # Parameters:
                   2219: #    $cmd      - The command that got us here.
                   2220: #    $tail     - Tail of the command (remaining parameters).
                   2221: #    $client   - File descriptor connected to client.
                   2222: # Returns
                   2223: #     0        - Requested to exit, caller should shut down.
                   2224: #     1        - Continue processing.
                   2225: #
                   2226: sub unsubscribe_handler {
                   2227:     my ($cmd, $tail, $client) = @_;
                   2228: 
                   2229:     my $userinput= "$cmd:$tail";
                   2230:     
                   2231:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   2232: 
                   2233:     &Debug("Unsubscribing $fname");
                   2234:     if (-e $fname) {
                   2235: 	&Debug("Exists");
                   2236: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   2237:     } else {
                   2238: 	&Failure($client, "not_found\n", $userinput);
                   2239:     }
                   2240:     return 1;
                   2241: }
                   2242: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 2243: 
1.230     foxr     2244: #   Subscribe to a resource
                   2245: #
                   2246: # Parameters:
                   2247: #    $cmd      - The command that got us here.
                   2248: #    $tail     - Tail of the command (remaining parameters).
                   2249: #    $client   - File descriptor connected to client.
                   2250: # Returns
                   2251: #     0        - Requested to exit, caller should shut down.
                   2252: #     1        - Continue processing.
                   2253: #
                   2254: sub subscribe_handler {
                   2255:     my ($cmd, $tail, $client)= @_;
                   2256: 
                   2257:     my $userinput  = "$cmd:$tail";
                   2258: 
                   2259:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   2260: 
                   2261:     return 1;
                   2262: }
                   2263: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   2264: 
                   2265: #
                   2266: #   Determine the version of a resource (?) Or is it return
                   2267: #   the top version of the resource?  Not yet clear from the
                   2268: #   code in currentversion.
                   2269: #
                   2270: # Parameters:
                   2271: #    $cmd      - The command that got us here.
                   2272: #    $tail     - Tail of the command (remaining parameters).
                   2273: #    $client   - File descriptor connected to client.
                   2274: # Returns
                   2275: #     0        - Requested to exit, caller should shut down.
                   2276: #     1        - Continue processing.
                   2277: #
                   2278: sub current_version_handler {
                   2279:     my ($cmd, $tail, $client) = @_;
                   2280: 
                   2281:     my $userinput= "$cmd:$tail";
                   2282:    
                   2283:     my $fname   = $tail;
                   2284:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   2285:     return 1;
                   2286: 
                   2287: }
                   2288: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   2289: 
                   2290: #  Make an entry in a user's activity log.
                   2291: #
                   2292: # Parameters:
                   2293: #    $cmd      - The command that got us here.
                   2294: #    $tail     - Tail of the command (remaining parameters).
                   2295: #    $client   - File descriptor connected to client.
                   2296: # Returns
                   2297: #     0        - Requested to exit, caller should shut down.
                   2298: #     1        - Continue processing.
                   2299: #
                   2300: sub activity_log_handler {
                   2301:     my ($cmd, $tail, $client) = @_;
                   2302: 
                   2303: 
                   2304:     my $userinput= "$cmd:$tail";
                   2305: 
                   2306:     my ($udom,$uname,$what)=split(/:/,$tail);
                   2307:     chomp($what);
                   2308:     my $proname=&propath($udom,$uname);
                   2309:     my $now=time;
                   2310:     my $hfh;
                   2311:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   2312: 	print $hfh "$now:$clientname:$what\n";
                   2313: 	&Reply( $client, "ok\n", $userinput); 
                   2314:     } else {
                   2315: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   2316: 		 ."while attempting log\n", 
                   2317: 		 $userinput);
                   2318:     }
                   2319: 
                   2320:     return 1;
                   2321: }
1.263     albertel 2322: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     2323: 
                   2324: #
                   2325: #   Put a namespace entry in a user profile hash.
                   2326: #   My druthers would be for this to be an encrypted interaction too.
                   2327: #   anything that might be an inadvertent covert channel about either
                   2328: #   user authentication or user personal information....
                   2329: #
                   2330: # Parameters:
                   2331: #    $cmd      - The command that got us here.
                   2332: #    $tail     - Tail of the command (remaining parameters).
                   2333: #    $client   - File descriptor connected to client.
                   2334: # Returns
                   2335: #     0        - Requested to exit, caller should shut down.
                   2336: #     1        - Continue processing.
                   2337: #
                   2338: sub put_user_profile_entry {
                   2339:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     2340: 
1.230     foxr     2341:     my $userinput = "$cmd:$tail";
                   2342:     
1.242     raeburn  2343:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     2344:     if ($namespace ne 'roles') {
                   2345: 	chomp($what);
                   2346: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2347: 				  &GDBM_WRCREAT(),"P",$what);
                   2348: 	if($hashref) {
                   2349: 	    my @pairs=split(/\&/,$what);
                   2350: 	    foreach my $pair (@pairs) {
                   2351: 		my ($key,$value)=split(/=/,$pair);
                   2352: 		$hashref->{$key}=$value;
                   2353: 	    }
                   2354: 	    if (untie(%$hashref)) {
                   2355: 		&Reply( $client, "ok\n", $userinput);
                   2356: 	    } else {
                   2357: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2358: 			"while attempting put\n", 
                   2359: 			$userinput);
                   2360: 	    }
                   2361: 	} else {
                   2362: 	    &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
                   2363: 		     "while attempting put\n", $userinput);
                   2364: 	}
                   2365:     } else {
                   2366:         &Failure( $client, "refused\n", $userinput);
                   2367:     }
                   2368:     
                   2369:     return 1;
                   2370: }
                   2371: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   2372: 
1.283     albertel 2373: #   Put a piece of new data in hash, returns error if entry already exists
                   2374: # Parameters:
                   2375: #    $cmd      - The command that got us here.
                   2376: #    $tail     - Tail of the command (remaining parameters).
                   2377: #    $client   - File descriptor connected to client.
                   2378: # Returns
                   2379: #     0        - Requested to exit, caller should shut down.
                   2380: #     1        - Continue processing.
                   2381: #
                   2382: sub newput_user_profile_entry {
                   2383:     my ($cmd, $tail, $client)  = @_;
                   2384: 
                   2385:     my $userinput = "$cmd:$tail";
                   2386: 
                   2387:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   2388:     if ($namespace eq 'roles') {
                   2389:         &Failure( $client, "refused\n", $userinput);
                   2390: 	return 1;
                   2391:     }
                   2392: 
                   2393:     chomp($what);
                   2394: 
                   2395:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2396: 				 &GDBM_WRCREAT(),"N",$what);
                   2397:     if(!$hashref) {
                   2398: 	&Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
                   2399: 		  "while attempting put\n", $userinput);
                   2400: 	return 1;
                   2401:     }
                   2402: 
                   2403:     my @pairs=split(/\&/,$what);
                   2404:     foreach my $pair (@pairs) {
                   2405: 	my ($key,$value)=split(/=/,$pair);
                   2406: 	if (exists($hashref->{$key})) {
                   2407: 	    &Failure($client, "key_exists: ".$key."\n",$userinput);
                   2408: 	    return 1;
                   2409: 	}
                   2410:     }
                   2411: 
                   2412:     foreach my $pair (@pairs) {
                   2413: 	my ($key,$value)=split(/=/,$pair);
                   2414: 	$hashref->{$key}=$value;
                   2415:     }
                   2416: 
                   2417:     if (untie(%$hashref)) {
                   2418: 	&Reply( $client, "ok\n", $userinput);
                   2419:     } else {
                   2420: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2421: 		 "while attempting put\n", 
                   2422: 		 $userinput);
                   2423:     }
                   2424:     return 1;
                   2425: }
                   2426: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   2427: 
1.230     foxr     2428: # 
                   2429: #   Increment a profile entry in the user history file.
                   2430: #   The history contains keyword value pairs.  In this case,
                   2431: #   The value itself is a pair of numbers.  The first, the current value
                   2432: #   the second an increment that this function applies to the current
                   2433: #   value.
                   2434: #
                   2435: # Parameters:
                   2436: #    $cmd      - The command that got us here.
                   2437: #    $tail     - Tail of the command (remaining parameters).
                   2438: #    $client   - File descriptor connected to client.
                   2439: # Returns
                   2440: #     0        - Requested to exit, caller should shut down.
                   2441: #     1        - Continue processing.
                   2442: #
                   2443: sub increment_user_value_handler {
                   2444:     my ($cmd, $tail, $client) = @_;
                   2445:     
                   2446:     my $userinput   = "$cmd:$tail";
                   2447:     
                   2448:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   2449:     if ($namespace ne 'roles') {
                   2450:         chomp($what);
                   2451: 	my $hashref = &tie_user_hash($udom, $uname,
                   2452: 				     $namespace, &GDBM_WRCREAT(),
                   2453: 				     "P",$what);
                   2454: 	if ($hashref) {
                   2455: 	    my @pairs=split(/\&/,$what);
                   2456: 	    foreach my $pair (@pairs) {
                   2457: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  2458:                 $value = &unescape($value);
1.230     foxr     2459: 		# We could check that we have a number...
                   2460: 		if (! defined($value) || $value eq '') {
                   2461: 		    $value = 1;
                   2462: 		}
                   2463: 		$hashref->{$key}+=$value;
1.284     raeburn  2464:                 if ($namespace eq 'nohist_resourcetracker') {
                   2465:                     if ($hashref->{$key} < 0) {
                   2466:                         $hashref->{$key} = 0;
                   2467:                     }
                   2468:                 }
1.230     foxr     2469: 	    }
                   2470: 	    if (untie(%$hashref)) {
                   2471: 		&Reply( $client, "ok\n", $userinput);
                   2472: 	    } else {
                   2473: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2474: 			 "while attempting inc\n", $userinput);
                   2475: 	    }
                   2476: 	} else {
                   2477: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2478: 		     "while attempting inc\n", $userinput);
                   2479: 	}
                   2480:     } else {
                   2481: 	&Failure($client, "refused\n", $userinput);
                   2482:     }
                   2483:     
                   2484:     return 1;
                   2485: }
                   2486: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   2487: 
                   2488: #
                   2489: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   2490: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   2491: #   for a person grants the permissions packaged with that role
                   2492: #   to that user when the role is selected.
                   2493: #
                   2494: # Parameters:
                   2495: #    $cmd       - The command string (rolesput).
                   2496: #    $tail      - The remainder of the request line.  For rolesput this
                   2497: #                 consists of a colon separated list that contains:
                   2498: #                 The domain and user that is granting the role (logged).
                   2499: #                 The domain and user that is getting the role.
                   2500: #                 The roles being granted as a set of & separated pairs.
                   2501: #                 each pair a key value pair.
                   2502: #    $client    - File descriptor connected to the client.
                   2503: # Returns:
                   2504: #     0         - If the daemon should exit
                   2505: #     1         - To continue processing.
                   2506: #
                   2507: #
                   2508: sub roles_put_handler {
                   2509:     my ($cmd, $tail, $client) = @_;
                   2510: 
                   2511:     my $userinput  = "$cmd:$tail";
                   2512: 
                   2513:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   2514:     
                   2515: 
                   2516:     my $namespace='roles';
                   2517:     chomp($what);
                   2518:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2519: 				 &GDBM_WRCREAT(), "P",
                   2520: 				 "$exedom:$exeuser:$what");
                   2521:     #
                   2522:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   2523:     #  handle is open for the minimal amount of time.  Since the flush
                   2524:     #  is done on close this improves the chances the log will be an un-
                   2525:     #  corrupted ordered thing.
                   2526:     if ($hashref) {
1.261     foxr     2527: 	my $pass_entry = &get_auth_type($udom, $uname);
                   2528: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   2529: 	$auth_type = $auth_type.":";
1.230     foxr     2530: 	my @pairs=split(/\&/,$what);
                   2531: 	foreach my $pair (@pairs) {
                   2532: 	    my ($key,$value)=split(/=/,$pair);
                   2533: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     2534: 			       $auth_type);
1.230     foxr     2535: 	    $hashref->{$key}=$value;
                   2536: 	}
                   2537: 	if (untie($hashref)) {
                   2538: 	    &Reply($client, "ok\n", $userinput);
                   2539: 	} else {
                   2540: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2541: 		     "while attempting rolesput\n", $userinput);
                   2542: 	}
                   2543:     } else {
                   2544: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2545: 		 "while attempting rolesput\n", $userinput);
                   2546:     }
                   2547:     return 1;
                   2548: }
                   2549: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   2550: 
                   2551: #
1.231     foxr     2552: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   2553: #  a permissions package associated with the role from the user's profile.
                   2554: #
                   2555: # Parameters:
                   2556: #     $cmd                 - The command (rolesdel)
                   2557: #     $tail                - The remainder of the request line. This consists
                   2558: #                             of:
                   2559: #                             The domain and user requesting the change (logged)
                   2560: #                             The domain and user being changed.
                   2561: #                             The roles being revoked.  These are shipped to us
                   2562: #                             as a bunch of & separated role name keywords.
                   2563: #     $client              - The file handle open on the client.
                   2564: # Returns:
                   2565: #     1                    - Continue processing
                   2566: #     0                    - Exit.
                   2567: #
                   2568: sub roles_delete_handler {
                   2569:     my ($cmd, $tail, $client)  = @_;
                   2570: 
                   2571:     my $userinput    = "$cmd:$tail";
                   2572:    
                   2573:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   2574:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   2575: 	   "what = ".$what);
                   2576:     my $namespace='roles';
                   2577:     chomp($what);
                   2578:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2579: 				 &GDBM_WRCREAT(), "D",
                   2580: 				 "$exedom:$exeuser:$what");
                   2581:     
                   2582:     if ($hashref) {
                   2583: 	my @rolekeys=split(/\&/,$what);
                   2584: 	
                   2585: 	foreach my $key (@rolekeys) {
                   2586: 	    delete $hashref->{$key};
                   2587: 	}
                   2588: 	if (untie(%$hashref)) {
                   2589: 	    &Reply($client, "ok\n", $userinput);
                   2590: 	} else {
                   2591: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2592: 		     "while attempting rolesdel\n", $userinput);
                   2593: 	}
                   2594:     } else {
                   2595:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2596: 		 "while attempting rolesdel\n", $userinput);
                   2597:     }
                   2598:     
                   2599:     return 1;
                   2600: }
                   2601: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   2602: 
                   2603: # Unencrypted get from a user's profile database.  See 
                   2604: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   2605: # This function retrieves a keyed item from a specific named database in the
                   2606: # user's directory.
                   2607: #
                   2608: # Parameters:
                   2609: #   $cmd             - Command request keyword (get).
                   2610: #   $tail            - Tail of the command.  This is a colon separated list
                   2611: #                      consisting of the domain and username that uniquely
                   2612: #                      identifies the profile,
                   2613: #                      The 'namespace' which selects the gdbm file to 
                   2614: #                      do the lookup in, 
                   2615: #                      & separated list of keys to lookup.  Note that
                   2616: #                      the values are returned as an & separated list too.
                   2617: #   $client          - File descriptor open on the client.
                   2618: # Returns:
                   2619: #   1       - Continue processing.
                   2620: #   0       - Exit.
                   2621: #
                   2622: sub get_profile_entry {
                   2623:     my ($cmd, $tail, $client) = @_;
                   2624: 
                   2625:     my $userinput= "$cmd:$tail";
                   2626:    
                   2627:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2628:     chomp($what);
1.255     foxr     2629: 
                   2630:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   2631:     my ($first) = split(/:/,$replystring);
                   2632:     if($first ne "error") {
                   2633: 	&Reply($client, "$replystring\n", $userinput);
1.231     foxr     2634:     } else {
1.255     foxr     2635: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     2636:     }
                   2637:     return 1;
1.255     foxr     2638: 
                   2639: 
1.231     foxr     2640: }
                   2641: &register_handler("get", \&get_profile_entry, 0,1,0);
                   2642: 
                   2643: #
                   2644: #  Process the encrypted get request.  Note that the request is sent
                   2645: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   2646: #  information about the sensitive keys is given to the snooper.  Just not
                   2647: #  information about the values of the sensitive key.  Hmm if I wanted to
                   2648: #  know these I'd snoop for the egets. Get the profile item names from them
                   2649: #  and then issue a get for them since there's no enforcement of the
                   2650: #  requirement of an encrypted get for particular profile items.  If I
                   2651: #  were re-doing this, I'd force the request to be encrypted as well as the
                   2652: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   2653: #  that would prevent any covert channel snooping.
                   2654: #
                   2655: #  Parameters:
                   2656: #     $cmd               - Command keyword of request (eget).
                   2657: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
                   2658: #     $client            - File open on the client.
                   2659: #  Returns:
                   2660: #     1      - Continue processing
                   2661: #     0      - server should exit.
                   2662: sub get_profile_entry_encrypted {
                   2663:     my ($cmd, $tail, $client) = @_;
                   2664: 
                   2665:     my $userinput = "$cmd:$tail";
                   2666:    
                   2667:     my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
                   2668:     chomp($what);
1.255     foxr     2669:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   2670:     my ($first) = split(/:/, $qresult);
                   2671:     if($first ne "error") {
                   2672: 	
                   2673: 	if ($cipher) {
                   2674: 	    my $cmdlength=length($qresult);
                   2675: 	    $qresult.="         ";
                   2676: 	    my $encqresult='';
                   2677: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   2678: 		$encqresult.= unpack("H16", 
                   2679: 				     $cipher->encrypt(substr($qresult,
                   2680: 							     $encidx,
                   2681: 							     8)));
                   2682: 	    }
                   2683: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   2684: 	} else {
1.231     foxr     2685: 		&Failure( $client, "error:no_key\n", $userinput);
                   2686: 	    }
                   2687:     } else {
1.255     foxr     2688: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   2689: 
1.231     foxr     2690:     }
                   2691:     
                   2692:     return 1;
                   2693: }
1.255     foxr     2694: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 2695: 
1.231     foxr     2696: #
                   2697: #   Deletes a key in a user profile database.
                   2698: #   
                   2699: #   Parameters:
                   2700: #       $cmd                  - Command keyword (del).
                   2701: #       $tail                 - Command tail.  IN this case a colon
                   2702: #                               separated list containing:
                   2703: #                               The domain and user that identifies uniquely
                   2704: #                               the identity of the user.
                   2705: #                               The profile namespace (name of the profile
                   2706: #                               database file).
                   2707: #                               & separated list of keywords to delete.
                   2708: #       $client              - File open on client socket.
                   2709: # Returns:
                   2710: #     1   - Continue processing
                   2711: #     0   - Exit server.
                   2712: #
                   2713: #
                   2714: sub delete_profile_entry {
                   2715:     my ($cmd, $tail, $client) = @_;
                   2716: 
                   2717:     my $userinput = "cmd:$tail";
                   2718: 
                   2719:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2720:     chomp($what);
                   2721:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2722: 				 &GDBM_WRCREAT(),
                   2723: 				 "D",$what);
                   2724:     if ($hashref) {
                   2725:         my @keys=split(/\&/,$what);
                   2726: 	foreach my $key (@keys) {
                   2727: 	    delete($hashref->{$key});
                   2728: 	}
                   2729: 	if (untie(%$hashref)) {
                   2730: 	    &Reply($client, "ok\n", $userinput);
                   2731: 	} else {
                   2732: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2733: 		    "while attempting del\n", $userinput);
                   2734: 	}
                   2735:     } else {
                   2736: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2737: 		 "while attempting del\n", $userinput);
                   2738:     }
                   2739:     return 1;
                   2740: }
                   2741: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 2742: 
1.231     foxr     2743: #
                   2744: #  List the set of keys that are defined in a profile database file.
                   2745: #  A successful reply from this will contain an & separated list of
                   2746: #  the keys. 
                   2747: # Parameters:
                   2748: #     $cmd              - Command request (keys).
                   2749: #     $tail             - Remainder of the request, a colon separated
                   2750: #                         list containing domain/user that identifies the
                   2751: #                         user being queried, and the database namespace
                   2752: #                         (database filename essentially).
                   2753: #     $client           - File open on the client.
                   2754: #  Returns:
                   2755: #    1    - Continue processing.
                   2756: #    0    - Exit the server.
                   2757: #
                   2758: sub get_profile_keys {
                   2759:     my ($cmd, $tail, $client) = @_;
                   2760: 
                   2761:     my $userinput = "$cmd:$tail";
                   2762: 
                   2763:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   2764:     my $qresult='';
                   2765:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2766: 				  &GDBM_READER());
                   2767:     if ($hashref) {
                   2768: 	foreach my $key (keys %$hashref) {
                   2769: 	    $qresult.="$key&";
                   2770: 	}
                   2771: 	if (untie(%$hashref)) {
                   2772: 	    $qresult=~s/\&$//;
                   2773: 	    &Reply($client, "$qresult\n", $userinput);
                   2774: 	} else {
                   2775: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2776: 		    "while attempting keys\n", $userinput);
                   2777: 	}
                   2778:     } else {
                   2779: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2780: 		 "while attempting keys\n", $userinput);
                   2781:     }
                   2782:    
                   2783:     return 1;
                   2784: }
                   2785: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   2786: 
                   2787: #
                   2788: #   Dump the contents of a user profile database.
                   2789: #   Note that this constitutes a very large covert channel too since
                   2790: #   the dump will return sensitive information that is not encrypted.
                   2791: #   The naive security assumption is that the session negotiation ensures
                   2792: #   our client is trusted and I don't believe that's assured at present.
                   2793: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   2794: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   2795: # 
                   2796: #  Parameters:
                   2797: #     $cmd           - The command request keyword (currentdump).
                   2798: #     $tail          - Remainder of the request, consisting of a colon
                   2799: #                      separated list that has the domain/username and
                   2800: #                      the namespace to dump (database file).
                   2801: #     $client        - file open on the remote client.
                   2802: # Returns:
                   2803: #     1    - Continue processing.
                   2804: #     0    - Exit the server.
                   2805: #
                   2806: sub dump_profile_database {
                   2807:     my ($cmd, $tail, $client) = @_;
                   2808: 
                   2809:     my $userinput = "$cmd:$tail";
                   2810:    
                   2811:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   2812:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2813: 				 &GDBM_READER());
                   2814:     if ($hashref) {
                   2815: 	# Structure of %data:
                   2816: 	# $data{$symb}->{$parameter}=$value;
                   2817: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   2818: 	# since $parameter will be unescaped, we do not
                   2819:  	# have to worry about silly parameter names...
                   2820: 	
                   2821:         my $qresult='';
                   2822: 	my %data = ();                     # A hash of anonymous hashes..
                   2823: 	while (my ($key,$value) = each(%$hashref)) {
                   2824: 	    my ($v,$symb,$param) = split(/:/,$key);
                   2825: 	    next if ($v eq 'version' || $symb eq 'keys');
                   2826: 	    next if (exists($data{$symb}) && 
                   2827: 		     exists($data{$symb}->{$param}) &&
                   2828: 		     $data{$symb}->{'v.'.$param} > $v);
                   2829: 	    $data{$symb}->{$param}=$value;
                   2830: 	    $data{$symb}->{'v.'.$param}=$v;
                   2831: 	}
                   2832: 	if (untie(%$hashref)) {
                   2833: 	    while (my ($symb,$param_hash) = each(%data)) {
                   2834: 		while(my ($param,$value) = each (%$param_hash)){
                   2835: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   2836: 		    #
                   2837: 		    #   Just dump the symb=value pairs separated by &
                   2838: 		    #
                   2839: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   2840: 		}
                   2841: 	    }
                   2842: 	    chop($qresult);
                   2843: 	    &Reply($client , "$qresult\n", $userinput);
                   2844: 	} else {
                   2845: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2846: 		     "while attempting currentdump\n", $userinput);
                   2847: 	}
                   2848:     } else {
                   2849: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2850: 		"while attempting currentdump\n", $userinput);
                   2851:     }
                   2852: 
                   2853:     return 1;
                   2854: }
                   2855: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   2856: 
                   2857: #
                   2858: #   Dump a profile database with an optional regular expression
                   2859: #   to match against the keys.  In this dump, no effort is made
                   2860: #   to separate symb from version information. Presumably the
                   2861: #   databases that are dumped by this command are of a different
                   2862: #   structure.  Need to look at this and improve the documentation of
                   2863: #   both this and the currentdump handler.
                   2864: # Parameters:
                   2865: #    $cmd                     - The command keyword.
                   2866: #    $tail                    - All of the characters after the $cmd:
                   2867: #                               These are expected to be a colon
                   2868: #                               separated list containing:
                   2869: #                               domain/user - identifying the user.
                   2870: #                               namespace   - identifying the database.
                   2871: #                               regexp      - optional regular expression
                   2872: #                                             that is matched against
                   2873: #                                             database keywords to do
                   2874: #                                             selective dumps.
                   2875: #   $client                   - Channel open on the client.
                   2876: # Returns:
                   2877: #    1    - Continue processing.
                   2878: # Side effects:
                   2879: #    response is written to $client.
                   2880: #
                   2881: sub dump_with_regexp {
                   2882:     my ($cmd, $tail, $client) = @_;
                   2883: 
                   2884: 
                   2885:     my $userinput = "$cmd:$tail";
                   2886: 
                   2887:     my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);
                   2888:     if (defined($regexp)) {
                   2889: 	$regexp=&unescape($regexp);
                   2890:     } else {
                   2891: 	$regexp='.';
                   2892:     }
                   2893:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2894: 				 &GDBM_READER());
                   2895:     if ($hashref) {
                   2896:         my $qresult='';
                   2897: 	while (my ($key,$value) = each(%$hashref)) {
                   2898: 	    if ($regexp eq '.') {
                   2899: 		$qresult.=$key.'='.$value.'&';
                   2900: 	    } else {
                   2901: 		my $unescapeKey = &unescape($key);
                   2902: 		if (eval('$unescapeKey=~/$regexp/')) {
                   2903: 		    $qresult.="$key=$value&";
                   2904: 		}
                   2905: 	    }
                   2906: 	}
                   2907: 	if (untie(%$hashref)) {
                   2908: 	    chop($qresult);
                   2909: 	    &Reply($client, "$qresult\n", $userinput);
                   2910: 	} else {
                   2911: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2912: 		     "while attempting dump\n", $userinput);
                   2913: 	}
                   2914:     } else {
                   2915: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2916: 		"while attempting dump\n", $userinput);
                   2917:     }
                   2918: 
                   2919:     return 1;
                   2920: }
                   2921: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   2922: 
                   2923: #  Store a set of key=value pairs associated with a versioned name.
                   2924: #
                   2925: #  Parameters:
                   2926: #    $cmd                - Request command keyword.
                   2927: #    $tail               - Tail of the request.  This is a colon
                   2928: #                          separated list containing:
                   2929: #                          domain/user - User and authentication domain.
                   2930: #                          namespace   - Name of the database being modified
                   2931: #                          rid         - Resource keyword to modify.
                   2932: #                          what        - new value associated with rid.
                   2933: #
                   2934: #    $client             - Socket open on the client.
                   2935: #
                   2936: #
                   2937: #  Returns:
                   2938: #      1 (keep on processing).
                   2939: #  Side-Effects:
                   2940: #    Writes to the client
                   2941: sub store_handler {
                   2942:     my ($cmd, $tail, $client) = @_;
                   2943:  
                   2944:     my $userinput = "$cmd:$tail";
                   2945: 
                   2946:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
                   2947:     if ($namespace ne 'roles') {
                   2948: 
                   2949: 	chomp($what);
                   2950: 	my @pairs=split(/\&/,$what);
                   2951: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 2952: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     2953: 				       "$rid:$what");
                   2954: 	if ($hashref) {
                   2955: 	    my $now = time;
                   2956: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
                   2957: 	    my $key;
                   2958: 	    $hashref->{"version:$rid"}++;
                   2959: 	    my $version=$hashref->{"version:$rid"};
                   2960: 	    my $allkeys=''; 
                   2961: 	    foreach my $pair (@pairs) {
                   2962: 		my ($key,$value)=split(/=/,$pair);
                   2963: 		$allkeys.=$key.':';
                   2964: 		$hashref->{"$version:$rid:$key"}=$value;
                   2965: 	    }
                   2966: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   2967: 	    $allkeys.='timestamp';
                   2968: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
                   2969: 	    if (untie($hashref)) {
                   2970: 		&Reply($client, "ok\n", $userinput);
                   2971: 	    } else {
                   2972: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2973: 			"while attempting store\n", $userinput);
                   2974: 	    }
                   2975: 	} else {
                   2976: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2977: 		     "while attempting store\n", $userinput);
                   2978: 	}
                   2979:     } else {
                   2980: 	&Failure($client, "refused\n", $userinput);
                   2981:     }
                   2982: 
                   2983:     return 1;
                   2984: }
                   2985: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 2986: 
1.231     foxr     2987: #
                   2988: #  Dump out all versions of a resource that has key=value pairs associated
                   2989: # with it for each version.  These resources are built up via the store
                   2990: # command.
                   2991: #
                   2992: #  Parameters:
                   2993: #     $cmd               - Command keyword.
                   2994: #     $tail              - Remainder of the request which consists of:
                   2995: #                          domain/user   - User and auth. domain.
                   2996: #                          namespace     - name of resource database.
                   2997: #                          rid           - Resource id.
                   2998: #    $client             - socket open on the client.
                   2999: #
                   3000: # Returns:
                   3001: #      1  indicating the caller should not yet exit.
                   3002: # Side-effects:
                   3003: #   Writes a reply to the client.
                   3004: #   The reply is a string of the following shape:
                   3005: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3006: #    Where the 1 above represents version 1.
                   3007: #    this continues for all pairs of keys in all versions.
                   3008: #
                   3009: #
                   3010: #    
                   3011: #
                   3012: sub restore_handler {
                   3013:     my ($cmd, $tail, $client) = @_;
                   3014: 
                   3015:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
                   3016: 
                   3017:     my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
                   3018:     $namespace=~s/\//\_/g;
                   3019:     $namespace=~s/\W//g;
                   3020:     chomp($rid);
                   3021:     my $proname=&propath($udom,$uname);
                   3022:     my $qresult='';
                   3023:     my %hash;
                   3024:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
                   3025: 	    &GDBM_READER(),0640)) {
                   3026: 	my $version=$hash{"version:$rid"};
                   3027: 	$qresult.="version=$version&";
                   3028: 	my $scope;
                   3029: 	for ($scope=1;$scope<=$version;$scope++) {
                   3030: 	    my $vkeys=$hash{"$scope:keys:$rid"};
                   3031: 	    my @keys=split(/:/,$vkeys);
                   3032: 	    my $key;
                   3033: 	    $qresult.="$scope:keys=$vkeys&";
                   3034: 	    foreach $key (@keys) {
                   3035: 		$qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
                   3036: 	    }                                  
                   3037: 	}
                   3038: 	if (untie(%hash)) {
                   3039: 	    $qresult=~s/\&$//;
                   3040: 	    &Reply( $client, "$qresult\n", $userinput);
                   3041: 	} else {
                   3042: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3043: 		    "while attempting restore\n", $userinput);
                   3044: 	}
                   3045:     } else {
                   3046: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3047: 		"while attempting restore\n", $userinput);
                   3048:     }
                   3049:   
                   3050:     return 1;
                   3051: 
                   3052: 
                   3053: }
                   3054: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3055: 
                   3056: #
                   3057: #   Add a chat message to to a discussion board.
                   3058: #
                   3059: # Parameters:
                   3060: #    $cmd                - Request keyword.
                   3061: #    $tail               - Tail of the command. A colon separated list
                   3062: #                          containing:
                   3063: #                          cdom    - Domain on which the chat board lives
                   3064: #                          cnum    - Identifier of the discussion group.
                   3065: #                          post    - Body of the posting.
                   3066: #   $client              - Socket open on the client.
                   3067: # Returns:
                   3068: #   1    - Indicating caller should keep on processing.
                   3069: #
                   3070: # Side-effects:
                   3071: #   writes a reply to the client.
                   3072: #
                   3073: #
                   3074: sub send_chat_handler {
                   3075:     my ($cmd, $tail, $client) = @_;
                   3076: 
                   3077:     
                   3078:     my $userinput = "$cmd:$tail";
                   3079: 
                   3080:     my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
                   3081:     &chat_add($cdom,$cnum,$newpost);
                   3082:     &Reply($client, "ok\n", $userinput);
                   3083: 
                   3084:     return 1;
                   3085: }
                   3086: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3087: 
1.234     foxr     3088: #
                   3089: #   Retrieve the set of chat messagss from a discussion board.
                   3090: #
                   3091: #  Parameters:
                   3092: #    $cmd             - Command keyword that initiated the request.
                   3093: #    $tail            - Remainder of the request after the command
                   3094: #                       keyword.  In this case a colon separated list of
                   3095: #                       chat domain    - Which discussion board.
                   3096: #                       chat id        - Discussion thread(?)
                   3097: #                       domain/user    - Authentication domain and username
                   3098: #                                        of the requesting person.
                   3099: #   $client           - Socket open on the client program.
                   3100: # Returns:
                   3101: #    1     - continue processing
                   3102: # Side effects:
                   3103: #    Response is written to the client.
                   3104: #
                   3105: sub retrieve_chat_handler {
                   3106:     my ($cmd, $tail, $client) = @_;
                   3107: 
                   3108: 
                   3109:     my $userinput = "$cmd:$tail";
                   3110: 
                   3111:     my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
                   3112:     my $reply='';
                   3113:     foreach (&get_chat($cdom,$cnum,$udom,$uname)) {
                   3114: 	$reply.=&escape($_).':';
                   3115:     }
                   3116:     $reply=~s/\:$//;
                   3117:     &Reply($client, $reply."\n", $userinput);
                   3118: 
                   3119: 
                   3120:     return 1;
                   3121: }
                   3122: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3123: 
                   3124: #
                   3125: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3126: #  a file for later retrieval.  This prevents sql query results from
                   3127: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3128: #  less of an issue since multiple outstanding requests can be concurrently
                   3129: #  serviced.
                   3130: #
                   3131: #  Parameters:
                   3132: #     $cmd       - COmmand keyword that initiated the request.
                   3133: #     $tail      - Remainder of the command after the keyword.
                   3134: #                  For this function, this consists of a query and
                   3135: #                  3 arguments that are self-documentingly labelled
                   3136: #                  in the original arg1, arg2, arg3.
                   3137: #     $client    - Socket open on the client.
                   3138: # Return:
                   3139: #    1   - Indicating processing should continue.
                   3140: # Side-effects:
                   3141: #    a reply is written to $client.
                   3142: #
                   3143: sub send_query_handler {
                   3144:     my ($cmd, $tail, $client) = @_;
                   3145: 
                   3146: 
                   3147:     my $userinput = "$cmd:$tail";
                   3148: 
                   3149:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3150:     $query=~s/\n*$//g;
                   3151:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   3152: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   3153: 	  $userinput);
                   3154:     
                   3155:     return 1;
                   3156: }
                   3157: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   3158: 
                   3159: #
                   3160: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   3161: #   The query is submitted via a "querysend" transaction.
                   3162: #   There it is passed on to the lonsql daemon, queued and issued to
                   3163: #   mysql.
                   3164: #     This transaction is invoked when the sql transaction is complete
                   3165: #   it stores the query results in flie and indicates query completion.
                   3166: #   presumably local software then fetches this response... I'm guessing
                   3167: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   3168: #   lonsql on completion of the query interacts with the lond of our
                   3169: #   client to do a query reply storing two files:
                   3170: #    - id     - The results of the query.
                   3171: #    - id.end - Indicating the transaction completed. 
                   3172: #    NOTE: id is a unique id assigned to the query and querysend time.
                   3173: # Parameters:
                   3174: #    $cmd        - Command keyword that initiated this request.
                   3175: #    $tail       - Remainder of the tail.  In this case that's a colon
                   3176: #                  separated list containing the query Id and the 
                   3177: #                  results of the query.
                   3178: #    $client     - Socket open on the client.
                   3179: # Return:
                   3180: #    1           - Indicating that we should continue processing.
                   3181: # Side effects:
                   3182: #    ok written to the client.
                   3183: #
                   3184: sub reply_query_handler {
                   3185:     my ($cmd, $tail, $client) = @_;
                   3186: 
                   3187: 
                   3188:     my $userinput = "$cmd:$tail";
                   3189: 
                   3190:     my ($cmd,$id,$reply)=split(/:/,$userinput); 
                   3191:     my $store;
                   3192:     my $execdir=$perlvar{'lonDaemons'};
                   3193:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   3194: 	$reply=~s/\&/\n/g;
                   3195: 	print $store $reply;
                   3196: 	close $store;
                   3197: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   3198: 	print $store2 "done\n";
                   3199: 	close $store2;
                   3200: 	&Reply($client, "ok\n", $userinput);
                   3201:     } else {
                   3202: 	&Failure($client, "error: ".($!+0)
                   3203: 		." IO::File->new Failed ".
                   3204: 		"while attempting queryreply\n", $userinput);
                   3205:     }
                   3206:  
                   3207: 
                   3208:     return 1;
                   3209: }
                   3210: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   3211: 
                   3212: #
                   3213: #  Process the courseidput request.  Not quite sure what this means
                   3214: #  at the system level sense.  It appears a gdbm file in the 
                   3215: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   3216: #  a set of entries made in that database.
                   3217: #
                   3218: # Parameters:
                   3219: #   $cmd      - The command keyword that initiated this request.
                   3220: #   $tail     - Tail of the command.  In this case consists of a colon
                   3221: #               separated list contaning the domain to apply this to and
                   3222: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  3223: #               Each value is a colon separated list that includes:  
                   3224: #               description, institutional code and course owner.
                   3225: #               For backward compatibility with versions included
                   3226: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   3227: #               code and/or course owner are preserved from the existing 
                   3228: #               record when writing a new record in response to 1.1 or 
                   3229: #               1.2 implementations of lonnet::flushcourselogs().   
                   3230: #                      
1.234     foxr     3231: #   $client   - Socket open on the client.
                   3232: # Returns:
                   3233: #   1    - indicating that processing should continue
                   3234: #
                   3235: # Side effects:
                   3236: #   reply is written to the client.
                   3237: #
                   3238: sub put_course_id_handler {
                   3239:     my ($cmd, $tail, $client) = @_;
                   3240: 
                   3241: 
                   3242:     my $userinput = "$cmd:$tail";
                   3243: 
1.266     raeburn  3244:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     3245:     chomp($what);
                   3246:     my $now=time;
                   3247:     my @pairs=split(/\&/,$what);
                   3248: 
                   3249:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3250:     if ($hashref) {
                   3251: 	foreach my $pair (@pairs) {
1.271     raeburn  3252:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   3253:             $courseinfo =~ s/=/:/g;
1.272     raeburn  3254: 
1.273     albertel 3255:             my @current_items = split(/:/,$hashref->{$key});
                   3256:             shift(@current_items); # remove description
                   3257:             pop(@current_items);   # remove last access
1.272     raeburn  3258:             my $numcurrent = scalar(@current_items);
                   3259: 
1.273     albertel 3260:             my @new_items = split(/:/,$courseinfo);
1.272     raeburn  3261:             my $numnew = scalar(@new_items);
                   3262:             if ($numcurrent > 0) {
                   3263:                 if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
                   3264:                     $courseinfo .= ':'.join(':',@current_items);
                   3265:                 } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
                   3266:                     $courseinfo .= ':'.$current_items[$numcurrent-1];
                   3267:                 }
                   3268:             }
1.266     raeburn  3269: 	    $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     3270: 	}
                   3271: 	if (untie(%$hashref)) {
1.253     foxr     3272: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     3273: 	} else {
1.253     foxr     3274: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     3275: 		     ." untie(GDBM) Failed ".
                   3276: 		     "while attempting courseidput\n", $userinput);
                   3277: 	}
                   3278:     } else {
1.253     foxr     3279: 	&Failure($client, "error: ".($!+0)
1.234     foxr     3280: 		 ." tie(GDBM) Failed ".
                   3281: 		 "while attempting courseidput\n", $userinput);
                   3282:     }
1.253     foxr     3283:     
1.234     foxr     3284: 
                   3285:     return 1;
                   3286: }
                   3287: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   3288: 
                   3289: #  Retrieves the value of a course id resource keyword pattern
                   3290: #  defined since a starting date.  Both the starting date and the
                   3291: #  keyword pattern are optional.  If the starting date is not supplied it
                   3292: #  is treated as the beginning of time.  If the pattern is not found,
                   3293: #  it is treatred as "." matching everything.
                   3294: #
                   3295: #  Parameters:
                   3296: #     $cmd     - Command keyword that resulted in us being dispatched.
                   3297: #     $tail    - The remainder of the command that, in this case, consists
                   3298: #                of a colon separated list of:
                   3299: #                 domain   - The domain in which the course database is 
                   3300: #                            defined.
                   3301: #                 since    - Optional parameter describing the minimum
                   3302: #                            time of definition(?) of the resources that
                   3303: #                            will match the dump.
                   3304: #                 description - regular expression that is used to filter
                   3305: #                            the dump.  Only keywords matching this regexp
                   3306: #                            will be used.
1.272     raeburn  3307: #                 institutional code - optional supplied code to filter 
                   3308: #                            the dump. Only courses with an institutional code 
                   3309: #                            that match the supplied code will be returned.
                   3310: #                 owner    - optional supplied username of owner to filter
                   3311: #                            the dump.  Only courses for which the course 
                   3312: #                            owner matches the supplied username will be
1.274     albertel 3313: #                            returned. Implicit assumption that owner
                   3314: #                            is a user in the domain in which the
                   3315: #                            course database is defined.
1.234     foxr     3316: #     $client  - The socket open on the client.
                   3317: # Returns:
                   3318: #    1     - Continue processing.
                   3319: # Side Effects:
                   3320: #   a reply is written to $client.
                   3321: sub dump_course_id_handler {
                   3322:     my ($cmd, $tail, $client) = @_;
                   3323: 
                   3324:     my $userinput = "$cmd:$tail";
                   3325: 
1.282     raeburn  3326:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter) =split(/:/,$tail);
1.234     foxr     3327:     if (defined($description)) {
                   3328: 	$description=&unescape($description);
                   3329:     } else {
                   3330: 	$description='.';
                   3331:     }
1.266     raeburn  3332:     if (defined($instcodefilter)) {
                   3333:         $instcodefilter=&unescape($instcodefilter);
                   3334:     } else {
                   3335:         $instcodefilter='.';
                   3336:     }
                   3337:     if (defined($ownerfilter)) {
                   3338:         $ownerfilter=&unescape($ownerfilter);
                   3339:     } else {
                   3340:         $ownerfilter='.';
                   3341:     }
1.282     raeburn  3342:     if (defined($coursefilter)) {
                   3343:         $coursefilter=&unescape($coursefilter);
                   3344:     } else {
                   3345:         $coursefilter='.';
                   3346:     }
1.266     raeburn  3347: 
1.234     foxr     3348:     unless (defined($since)) { $since=0; }
                   3349:     my $qresult='';
                   3350:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3351:     if ($hashref) {
                   3352: 	while (my ($key,$value) = each(%$hashref)) {
1.266     raeburn  3353: 	    my ($descr,$lasttime,$inst_code,$owner);
1.274     albertel 3354:             my @courseitems = split(/:/,$value);
                   3355:             $lasttime = pop(@courseitems);
                   3356: 	    ($descr,$inst_code,$owner)=@courseitems;
1.234     foxr     3357: 	    if ($lasttime<$since) { next; }
1.266     raeburn  3358:             my $match = 1;
                   3359: 	    unless ($description eq '.') {
                   3360: 		my $unescapeDescr = &unescape($descr);
                   3361: 		unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
                   3362:                     $match = 0;
1.234     foxr     3363: 		}
1.266     raeburn  3364:             }
                   3365:             unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
                   3366:                 my $unescapeInstcode = &unescape($inst_code);
                   3367:                 unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
                   3368:                     $match = 0;
                   3369:                 }
1.234     foxr     3370: 	    }
1.266     raeburn  3371:             unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
                   3372:                 my $unescapeOwner = &unescape($owner);
                   3373:                 unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
                   3374:                     $match = 0;
                   3375:                 }
                   3376:             }
1.282     raeburn  3377:             unless ($coursefilter eq '.' || !defined($coursefilter)) {
                   3378:                 my $unescapeCourse = &unescape($key);
                   3379:                 unless (eval('$unescapeCourse=~/^$udom(_)\Q$coursefilter\E$/')) {
                   3380:                     $match = 0;
                   3381:                 }
                   3382:             }
1.266     raeburn  3383:             if ($match == 1) {
                   3384:                 $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
                   3385:             }
1.234     foxr     3386: 	}
                   3387: 	if (untie(%$hashref)) {
                   3388: 	    chop($qresult);
                   3389: 	    &Reply($client, "$qresult\n", $userinput);
                   3390: 	} else {
                   3391: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3392: 		    "while attempting courseiddump\n", $userinput);
                   3393: 	}
                   3394:     } else {
                   3395: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3396: 		"while attempting courseiddump\n", $userinput);
                   3397:     }
                   3398: 
                   3399: 
                   3400:     return 1;
                   3401: }
                   3402: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     3403: 
                   3404: #
                   3405: #  Puts an id to a domains id database. 
                   3406: #
                   3407: #  Parameters:
                   3408: #   $cmd     - The command that triggered us.
                   3409: #   $tail    - Remainder of the request other than the command. This is a 
                   3410: #              colon separated list containing:
                   3411: #              $domain  - The domain for which we are writing the id.
                   3412: #              $pairs  - The id info to write... this is and & separated list
                   3413: #                        of keyword=value.
                   3414: #   $client  - Socket open on the client.
                   3415: #  Returns:
                   3416: #    1   - Continue processing.
                   3417: #  Side effects:
                   3418: #     reply is written to $client.
                   3419: #
                   3420: sub put_id_handler {
                   3421:     my ($cmd,$tail,$client) = @_;
                   3422: 
                   3423: 
                   3424:     my $userinput = "$cmd:$tail";
                   3425: 
                   3426:     my ($udom,$what)=split(/:/,$tail);
                   3427:     chomp($what);
                   3428:     my @pairs=split(/\&/,$what);
                   3429:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   3430: 				   "P", $what);
                   3431:     if ($hashref) {
                   3432: 	foreach my $pair (@pairs) {
                   3433: 	    my ($key,$value)=split(/=/,$pair);
                   3434: 	    $hashref->{$key}=$value;
                   3435: 	}
                   3436: 	if (untie(%$hashref)) {
                   3437: 	    &Reply($client, "ok\n", $userinput);
                   3438: 	} else {
                   3439: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3440: 		     "while attempting idput\n", $userinput);
                   3441: 	}
                   3442:     } else {
                   3443: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3444: 		  "while attempting idput\n", $userinput);
                   3445:     }
                   3446: 
                   3447:     return 1;
                   3448: }
1.263     albertel 3449: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     3450: 
                   3451: #
                   3452: #  Retrieves a set of id values from the id database.
                   3453: #  Returns an & separated list of results, one for each requested id to the
                   3454: #  client.
                   3455: #
                   3456: # Parameters:
                   3457: #   $cmd       - Command keyword that caused us to be dispatched.
                   3458: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3459: #               domain - the domain whose id table we dump
                   3460: #               ids      Consists of an & separated list of
                   3461: #                        id keywords whose values will be fetched.
                   3462: #                        nonexisting keywords will have an empty value.
                   3463: #   $client    - Socket open on the client.
                   3464: #
                   3465: # Returns:
                   3466: #    1 - indicating processing should continue.
                   3467: # Side effects:
                   3468: #   An & separated list of results is written to $client.
                   3469: #
                   3470: sub get_id_handler {
                   3471:     my ($cmd, $tail, $client) = @_;
                   3472: 
                   3473:     
                   3474:     my $userinput = "$client:$tail";
                   3475:     
                   3476:     my ($udom,$what)=split(/:/,$tail);
                   3477:     chomp($what);
                   3478:     my @queries=split(/\&/,$what);
                   3479:     my $qresult='';
                   3480:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   3481:     if ($hashref) {
                   3482: 	for (my $i=0;$i<=$#queries;$i++) {
                   3483: 	    $qresult.="$hashref->{$queries[$i]}&";
                   3484: 	}
                   3485: 	if (untie(%$hashref)) {
                   3486: 	    $qresult=~s/\&$//;
                   3487: 	    &Reply($client, "$qresult\n", $userinput);
                   3488: 	} else {
                   3489: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3490: 		      "while attempting idget\n",$userinput);
                   3491: 	}
                   3492:     } else {
                   3493: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3494: 		 "while attempting idget\n",$userinput);
                   3495:     }
                   3496:     
                   3497:     return 1;
                   3498: }
1.263     albertel 3499: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     3500: 
                   3501: #
                   3502: #  Process the tmpput command I'm not sure what this does.. Seems to
                   3503: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   3504: # where Id is the client's ip concatenated with a sequence number.
                   3505: # The file will contain some value that is passed in.  Is this e.g.
                   3506: # a login token?
                   3507: #
                   3508: # Parameters:
                   3509: #    $cmd     - The command that got us dispatched.
                   3510: #    $tail    - The remainder of the request following $cmd:
                   3511: #               In this case this will be the contents of the file.
                   3512: #    $client  - Socket connected to the client.
                   3513: # Returns:
                   3514: #    1 indicating processing can continue.
                   3515: # Side effects:
                   3516: #   A file is created in the local filesystem.
                   3517: #   A reply is sent to the client.
                   3518: sub tmp_put_handler {
                   3519:     my ($cmd, $what, $client) = @_;
                   3520: 
                   3521:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   3522: 
                   3523: 
                   3524:     my $store;
                   3525:     $tmpsnum++;
                   3526:     my $id=$$.'_'.$clientip.'_'.$tmpsnum;
                   3527:     $id=~s/\W/\_/g;
                   3528:     $what=~s/\n//g;
                   3529:     my $execdir=$perlvar{'lonDaemons'};
                   3530:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
                   3531: 	print $store $what;
                   3532: 	close $store;
                   3533: 	&Reply($client, "$id\n", $userinput);
                   3534:     } else {
                   3535: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   3536: 		  "while attempting tmpput\n", $userinput);
                   3537:     }
                   3538:     return 1;
                   3539:   
                   3540: }
                   3541: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 3542: 
1.238     foxr     3543: #   Processes the tmpget command.  This command returns the contents
                   3544: #  of a temporary resource file(?) created via tmpput.
                   3545: #
                   3546: # Paramters:
                   3547: #    $cmd      - Command that got us dispatched.
                   3548: #    $id       - Tail of the command, contain the id of the resource
                   3549: #                we want to fetch.
                   3550: #    $client   - socket open on the client.
                   3551: # Return:
                   3552: #    1         - Inidcating processing can continue.
                   3553: # Side effects:
                   3554: #   A reply is sent to the client.
                   3555: #
                   3556: sub tmp_get_handler {
                   3557:     my ($cmd, $id, $client) = @_;
                   3558: 
                   3559:     my $userinput = "$cmd:$id"; 
                   3560:     
                   3561: 
                   3562:     $id=~s/\W/\_/g;
                   3563:     my $store;
                   3564:     my $execdir=$perlvar{'lonDaemons'};
                   3565:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   3566: 	my $reply=<$store>;
                   3567: 	&Reply( $client, "$reply\n", $userinput);
                   3568: 	close $store;
                   3569:     } else {
                   3570: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   3571: 		  "while attempting tmpget\n", $userinput);
                   3572:     }
                   3573: 
                   3574:     return 1;
                   3575: }
                   3576: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 3577: 
1.238     foxr     3578: #
                   3579: #  Process the tmpdel command.  This command deletes a temp resource
                   3580: #  created by the tmpput command.
                   3581: #
                   3582: # Parameters:
                   3583: #   $cmd      - Command that got us here.
                   3584: #   $id       - Id of the temporary resource created.
                   3585: #   $client   - socket open on the client process.
                   3586: #
                   3587: # Returns:
                   3588: #   1     - Indicating processing should continue.
                   3589: # Side Effects:
                   3590: #   A file is deleted
                   3591: #   A reply is sent to the client.
                   3592: sub tmp_del_handler {
                   3593:     my ($cmd, $id, $client) = @_;
                   3594:     
                   3595:     my $userinput= "$cmd:$id";
                   3596:     
                   3597:     chomp($id);
                   3598:     $id=~s/\W/\_/g;
                   3599:     my $execdir=$perlvar{'lonDaemons'};
                   3600:     if (unlink("$execdir/tmp/$id.tmp")) {
                   3601: 	&Reply($client, "ok\n", $userinput);
                   3602:     } else {
                   3603: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   3604: 		  "while attempting tmpdel\n", $userinput);
                   3605:     }
                   3606:     
                   3607:     return 1;
                   3608: 
                   3609: }
                   3610: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 3611: 
1.238     foxr     3612: #
1.246     foxr     3613: #   Processes the setannounce command.  This command
                   3614: #   creates a file named announce.txt in the top directory of
                   3615: #   the documentn root and sets its contents.  The announce.txt file is
                   3616: #   printed in its entirety at the LonCAPA login page.  Note:
                   3617: #   once the announcement.txt fileis created it cannot be deleted.
                   3618: #   However, setting the contents of the file to empty removes the
                   3619: #   announcement from the login page of loncapa so who cares.
                   3620: #
                   3621: # Parameters:
                   3622: #    $cmd          - The command that got us dispatched.
                   3623: #    $announcement - The text of the announcement.
                   3624: #    $client       - Socket open on the client process.
                   3625: # Retunrns:
                   3626: #   1             - Indicating request processing should continue
                   3627: # Side Effects:
                   3628: #   The file {DocRoot}/announcement.txt is created.
                   3629: #   A reply is sent to $client.
                   3630: #
                   3631: sub set_announce_handler {
                   3632:     my ($cmd, $announcement, $client) = @_;
                   3633:   
                   3634:     my $userinput    = "$cmd:$announcement";
                   3635: 
                   3636:     chomp($announcement);
                   3637:     $announcement=&unescape($announcement);
                   3638:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   3639: 				'/announcement.txt')) {
                   3640: 	print $store $announcement;
                   3641: 	close $store;
                   3642: 	&Reply($client, "ok\n", $userinput);
                   3643:     } else {
                   3644: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   3645:     }
                   3646: 
                   3647:     return 1;
                   3648: }
                   3649: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 3650: 
1.246     foxr     3651: #
                   3652: #  Return the version of the daemon.  This can be used to determine
                   3653: #  the compatibility of cross version installations or, alternatively to
                   3654: #  simply know who's out of date and who isn't.  Note that the version
                   3655: #  is returned concatenated with the tail.
                   3656: # Parameters:
                   3657: #   $cmd        - the request that dispatched to us.
                   3658: #   $tail       - Tail of the request (client's version?).
                   3659: #   $client     - Socket open on the client.
                   3660: #Returns:
                   3661: #   1 - continue processing requests.
                   3662: # Side Effects:
                   3663: #   Replies with version to $client.
                   3664: sub get_version_handler {
                   3665:     my ($cmd, $tail, $client) = @_;
                   3666: 
                   3667:     my $userinput  = $cmd.$tail;
                   3668:     
                   3669:     &Reply($client, &version($userinput)."\n", $userinput);
                   3670: 
                   3671: 
                   3672:     return 1;
                   3673: }
                   3674: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 3675: 
1.246     foxr     3676: #  Set the current host and domain.  This is used to support
                   3677: #  multihomed systems.  Each IP of the system, or even separate daemons
                   3678: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   3679: #  machine.  This command selects the virtual lonCAPA.  The client always
                   3680: #  knows the right one since it is lonc and it is selecting the domain/system
                   3681: #  from the hosts.tab file.
                   3682: # Parameters:
                   3683: #    $cmd      - Command that dispatched us.
                   3684: #    $tail     - Tail of the command (domain/host requested).
                   3685: #    $socket   - Socket open on the client.
                   3686: #
                   3687: # Returns:
                   3688: #     1   - Indicates the program should continue to process requests.
                   3689: # Side-effects:
                   3690: #     The default domain/system context is modified for this daemon.
                   3691: #     a reply is sent to the client.
                   3692: #
                   3693: sub set_virtual_host_handler {
                   3694:     my ($cmd, $tail, $socket) = @_;
                   3695:   
                   3696:     my $userinput  ="$cmd:$tail";
                   3697: 
                   3698:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   3699: 
                   3700: 
                   3701:     return 1;
                   3702: }
1.247     albertel 3703: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     3704: 
                   3705: #  Process a request to exit:
                   3706: #   - "bye" is sent to the client.
                   3707: #   - The client socket is shutdown and closed.
                   3708: #   - We indicate to the caller that we should exit.
                   3709: # Formal Parameters:
                   3710: #   $cmd                - The command that got us here.
                   3711: #   $tail               - Tail of the command (empty).
                   3712: #   $client             - Socket open on the tail.
                   3713: # Returns:
                   3714: #   0      - Indicating the program should exit!!
                   3715: #
                   3716: sub exit_handler {
                   3717:     my ($cmd, $tail, $client) = @_;
                   3718: 
                   3719:     my $userinput = "$cmd:$tail";
                   3720: 
                   3721:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   3722:     &Reply($client, "bye\n", $userinput);
                   3723:     $client->shutdown(2);        # shutdown the socket forcibly.
                   3724:     $client->close();
                   3725: 
                   3726:     return 0;
                   3727: }
1.248     foxr     3728: &register_handler("exit", \&exit_handler, 0,1,1);
                   3729: &register_handler("init", \&exit_handler, 0,1,1);
                   3730: &register_handler("quit", \&exit_handler, 0,1,1);
                   3731: 
                   3732: #  Determine if auto-enrollment is enabled.
                   3733: #  Note that the original had what I believe to be a defect.
                   3734: #  The original returned 0 if the requestor was not a registerd client.
                   3735: #  It should return "refused".
                   3736: # Formal Parameters:
                   3737: #   $cmd       - The command that invoked us.
                   3738: #   $tail      - The tail of the command (Extra command parameters.
                   3739: #   $client    - The socket open on the client that issued the request.
                   3740: # Returns:
                   3741: #    1         - Indicating processing should continue.
                   3742: #
                   3743: sub enrollment_enabled_handler {
                   3744:     my ($cmd, $tail, $client) = @_;
                   3745:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   3746: 
                   3747:     
                   3748:     my $cdom = split(/:/, $tail);   # Domain we're asking about.
                   3749:     my $outcome  = &localenroll::run($cdom);
                   3750:     &Reply($client, "$outcome\n", $userinput);
                   3751: 
                   3752:     return 1;
                   3753: }
                   3754: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   3755: 
                   3756: #   Get the official sections for which auto-enrollment is possible.
                   3757: #   Since the admin people won't know about 'unofficial sections' 
                   3758: #   we cannot auto-enroll on them.
                   3759: # Formal Parameters:
                   3760: #    $cmd     - The command request that got us dispatched here.
                   3761: #    $tail    - The remainder of the request.  In our case this
                   3762: #               will be split into:
                   3763: #               $coursecode   - The course name from the admin point of view.
                   3764: #               $cdom         - The course's domain(?).
                   3765: #    $client  - Socket open on the client.
                   3766: # Returns:
                   3767: #    1    - Indiciting processing should continue.
                   3768: #
                   3769: sub get_sections_handler {
                   3770:     my ($cmd, $tail, $client) = @_;
                   3771:     my $userinput = "$cmd:$tail";
                   3772: 
                   3773:     my ($coursecode, $cdom) = split(/:/, $tail);
                   3774:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   3775:     my $seclist = &escape(join(':',@secs));
                   3776: 
                   3777:     &Reply($client, "$seclist\n", $userinput);
                   3778:     
                   3779: 
                   3780:     return 1;
                   3781: }
                   3782: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   3783: 
                   3784: #   Validate the owner of a new course section.  
                   3785: #
                   3786: # Formal Parameters:
                   3787: #   $cmd      - Command that got us dispatched.
                   3788: #   $tail     - the remainder of the command.  For us this consists of a
                   3789: #               colon separated string containing:
                   3790: #                  $inst    - Course Id from the institutions point of view.
                   3791: #                  $owner   - Proposed owner of the course.
                   3792: #                  $cdom    - Domain of the course (from the institutions
                   3793: #                             point of view?)..
                   3794: #   $client   - Socket open on the client.
                   3795: #
                   3796: # Returns:
                   3797: #   1        - Processing should continue.
                   3798: #
                   3799: sub validate_course_owner_handler {
                   3800:     my ($cmd, $tail, $client)  = @_;
                   3801:     my $userinput = "$cmd:$tail";
                   3802:     my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
                   3803: 
                   3804:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
                   3805:     &Reply($client, "$outcome\n", $userinput);
                   3806: 
                   3807: 
                   3808: 
                   3809:     return 1;
                   3810: }
                   3811: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 3812: 
1.248     foxr     3813: #
                   3814: #   Validate a course section in the official schedule of classes
                   3815: #   from the institutions point of view (part of autoenrollment).
                   3816: #
                   3817: # Formal Parameters:
                   3818: #   $cmd          - The command request that got us dispatched.
                   3819: #   $tail         - The tail of the command.  In this case,
                   3820: #                   this is a colon separated set of words that will be split
                   3821: #                   into:
                   3822: #                        $inst_course_id - The course/section id from the
                   3823: #                                          institutions point of view.
                   3824: #                        $cdom           - The domain from the institutions
                   3825: #                                          point of view.
                   3826: #   $client       - Socket open on the client.
                   3827: # Returns:
                   3828: #    1           - Indicating processing should continue.
                   3829: #
                   3830: sub validate_course_section_handler {
                   3831:     my ($cmd, $tail, $client) = @_;
                   3832:     my $userinput = "$cmd:$tail";
                   3833:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   3834: 
                   3835:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
                   3836:     &Reply($client, "$outcome\n", $userinput);
                   3837: 
                   3838: 
                   3839:     return 1;
                   3840: }
                   3841: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   3842: 
                   3843: #
                   3844: #   Create a password for a new auto-enrollment user.
                   3845: #   I think/guess, this password allows access to the institutions 
                   3846: #   AIS class list server/services.  Stuart can correct this comment
                   3847: #   when he finds out how wrong I am.
                   3848: #
                   3849: # Formal Parameters:
                   3850: #    $cmd     - The command request that got us dispatched.
                   3851: #    $tail    - The tail of the command.   In this case this is a colon separated
                   3852: #               set of words that will be split into:
                   3853: #               $authparam - An authentication parameter (username??).
                   3854: #               $cdom      - The domain of the course from the institution's
                   3855: #                            point of view.
                   3856: #    $client  - The socket open on the client.
                   3857: # Returns:
                   3858: #    1 - continue processing.
                   3859: #
                   3860: sub create_auto_enroll_password_handler {
                   3861:     my ($cmd, $tail, $client) = @_;
                   3862:     my $userinput = "$cmd:$tail";
                   3863: 
                   3864:     my ($authparam, $cdom) = split(/:/, $userinput);
                   3865: 
                   3866:     my ($create_passwd,$authchk);
                   3867:     ($authparam,
                   3868:      $create_passwd,
                   3869:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   3870: 
                   3871:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   3872: 	   $userinput);
                   3873: 
                   3874: 
                   3875:     return 1;
                   3876: }
                   3877: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   3878: 		  0, 1, 0);
                   3879: 
                   3880: #   Retrieve and remove temporary files created by/during autoenrollment.
                   3881: #
                   3882: # Formal Parameters:
                   3883: #    $cmd      - The command that got us dispatched.
                   3884: #    $tail     - The tail of the command.  In our case this is a colon 
                   3885: #                separated list that will be split into:
                   3886: #                $filename - The name of the file to remove.
                   3887: #                            The filename is given as a path relative to
                   3888: #                            the LonCAPA temp file directory.
                   3889: #    $client   - Socket open on the client.
                   3890: #
                   3891: # Returns:
                   3892: #   1     - Continue processing.
                   3893: sub retrieve_auto_file_handler {
                   3894:     my ($cmd, $tail, $client)    = @_;
                   3895:     my $userinput                = "cmd:$tail";
                   3896: 
                   3897:     my ($filename)   = split(/:/, $tail);
                   3898: 
                   3899:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
                   3900:     if ( (-e $source) && ($filename ne '') ) {
                   3901: 	my $reply = '';
                   3902: 	if (open(my $fh,$source)) {
                   3903: 	    while (<$fh>) {
                   3904: 		chomp($_);
                   3905: 		$_ =~ s/^\s+//g;
                   3906: 		$_ =~ s/\s+$//g;
                   3907: 		$reply .= $_;
                   3908: 	    }
                   3909: 	    close($fh);
                   3910: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   3911: 
                   3912: #   Does this have to be uncommented??!?  (RF).
                   3913: #
                   3914: #                                unlink($source);
                   3915: 	} else {
                   3916: 	    &Failure($client, "error\n", $userinput);
                   3917: 	}
                   3918:     } else {
                   3919: 	&Failure($client, "error\n", $userinput);
                   3920:     }
                   3921:     
                   3922: 
                   3923:     return 1;
                   3924: }
                   3925: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   3926: 
                   3927: #
                   3928: #   Read and retrieve institutional code format (for support form).
                   3929: # Formal Parameters:
                   3930: #    $cmd        - Command that dispatched us.
                   3931: #    $tail       - Tail of the command.  In this case it conatins 
                   3932: #                  the course domain and the coursename.
                   3933: #    $client     - Socket open on the client.
                   3934: # Returns:
                   3935: #    1     - Continue processing.
                   3936: #
                   3937: sub get_institutional_code_format_handler {
                   3938:     my ($cmd, $tail, $client)   = @_;
                   3939:     my $userinput               = "$cmd:$tail";
                   3940: 
                   3941:     my $reply;
                   3942:     my($cdom,$course) = split(/:/,$tail);
                   3943:     my @pairs = split/\&/,$course;
                   3944:     my %instcodes = ();
                   3945:     my %codes = ();
                   3946:     my @codetitles = ();
                   3947:     my %cat_titles = ();
                   3948:     my %cat_order = ();
                   3949:     foreach (@pairs) {
                   3950: 	my ($key,$value) = split/=/,$_;
                   3951: 	$instcodes{&unescape($key)} = &unescape($value);
                   3952:     }
                   3953:     my $formatreply = &localenroll::instcode_format($cdom,
                   3954: 						    \%instcodes,
                   3955: 						    \%codes,
                   3956: 						    \@codetitles,
                   3957: 						    \%cat_titles,
                   3958: 						    \%cat_order);
                   3959:     if ($formatreply eq 'ok') {
                   3960: 	my $codes_str = &hash2str(%codes);
                   3961: 	my $codetitles_str = &array2str(@codetitles);
                   3962: 	my $cat_titles_str = &hash2str(%cat_titles);
                   3963: 	my $cat_order_str = &hash2str(%cat_order);
                   3964: 	&Reply($client,
                   3965: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   3966: 	       .$cat_order_str."\n",
                   3967: 	       $userinput);
                   3968:     } else {
                   3969: 	# this else branch added by RF since if not ok, lonc will
                   3970: 	# hang waiting on reply until timeout.
                   3971: 	#
                   3972: 	&Reply($client, "format_error\n", $userinput);
                   3973:     }
                   3974:     
                   3975:     return 1;
                   3976: }
1.265     albertel 3977: &register_handler("autoinstcodeformat",
                   3978: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     3979: 
1.265     albertel 3980: #
                   3981: # Gets a student's photo to exist (in the correct image type) in the user's 
                   3982: # directory.
                   3983: # Formal Parameters:
                   3984: #    $cmd     - The command request that got us dispatched.
                   3985: #    $tail    - A colon separated set of words that will be split into:
                   3986: #               $domain - student's domain
                   3987: #               $uname  - student username
                   3988: #               $type   - image type desired
                   3989: #    $client  - The socket open on the client.
                   3990: # Returns:
                   3991: #    1 - continue processing.
                   3992: sub student_photo_handler {
                   3993:     my ($cmd, $tail, $client) = @_;
                   3994:     my ($domain,$uname,$type) = split(/:/, $tail);
                   3995: 
                   3996:     my $path=&propath($domain,$uname).
                   3997: 	'/userfiles/internal/studentphoto.'.$type;
                   3998:     if (-e $path) {
                   3999: 	&Reply($client,"ok\n","$cmd:$tail");
                   4000: 	return 1;
                   4001:     }
                   4002:     &mkpath($path);
                   4003:     my $file=&localstudentphoto::fetch($domain,$uname);
                   4004:     if (!$file) {
                   4005: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   4006: 	return 1;
                   4007:     }
                   4008:     if (!-e $path) { &convert_photo($file,$path); }
                   4009:     if (-e $path) {
                   4010: 	&Reply($client,"ok\n","$cmd:$tail");
                   4011: 	return 1;
                   4012:     }
                   4013:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   4014:     return 1;
                   4015: }
                   4016: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     4017: 
1.264     albertel 4018: # mkpath makes all directories for a file, expects an absolute path with a
                   4019: # file or a trailing / if just a dir is passed
                   4020: # returns 1 on success 0 on failure
                   4021: sub mkpath {
                   4022:     my ($file)=@_;
                   4023:     my @parts=split(/\//,$file,-1);
                   4024:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   4025:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 4026: 	$now.='/'.$parts[$i]; 
1.264     albertel 4027: 	if (!-e $now) {
                   4028: 	    if  (!mkdir($now,0770)) { return 0; }
                   4029: 	}
                   4030:     }
                   4031:     return 1;
                   4032: }
                   4033: 
1.207     foxr     4034: #---------------------------------------------------------------
                   4035: #
                   4036: #   Getting, decoding and dispatching requests:
                   4037: #
                   4038: #
                   4039: #   Get a Request:
                   4040: #   Gets a Request message from the client.  The transaction
                   4041: #   is defined as a 'line' of text.  We remove the new line
                   4042: #   from the text line.  
1.226     foxr     4043: #
1.211     albertel 4044: sub get_request {
1.207     foxr     4045:     my $input = <$client>;
                   4046:     chomp($input);
1.226     foxr     4047: 
1.234     foxr     4048:     &Debug("get_request: Request = $input\n");
1.207     foxr     4049: 
                   4050:     &status('Processing '.$clientname.':'.$input);
                   4051: 
                   4052:     return $input;
                   4053: }
1.212     foxr     4054: #---------------------------------------------------------------
                   4055: #
                   4056: #  Process a request.  This sub should shrink as each action
                   4057: #  gets farmed out into a separat sub that is registered 
                   4058: #  with the dispatch hash.  
                   4059: #
                   4060: # Parameters:
                   4061: #    user_input   - The request received from the client (lonc).
                   4062: # Returns:
                   4063: #    true to keep processing, false if caller should exit.
                   4064: #
                   4065: sub process_request {
                   4066:     my ($userinput) = @_;      # Easier for now to break style than to
                   4067:                                 # fix all the userinput -> user_input.
                   4068:     my $wasenc    = 0;		# True if request was encrypted.
                   4069: # ------------------------------------------------------------ See if encrypted
                   4070:     if ($userinput =~ /^enc/) {
                   4071: 	$userinput = decipher($userinput);
                   4072: 	$wasenc=1;
                   4073: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     4074: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     4075: 	    return 0;
                   4076: 	}
                   4077:     }
                   4078:     Debug("process_request: $userinput\n");
                   4079:     
1.213     foxr     4080:     #  
                   4081:     #   The 'correct way' to add a command to lond is now to
                   4082:     #   write a sub to execute it and Add it to the command dispatch
                   4083:     #   hash via a call to register_handler..  The comments to that
                   4084:     #   sub should give you enough to go on to show how to do this
                   4085:     #   along with the examples that are building up as this code
                   4086:     #   is getting refactored.   Until all branches of the
                   4087:     #   if/elseif monster below have been factored out into
                   4088:     #   separate procesor subs, if the dispatch hash is missing
                   4089:     #   the command keyword, we will fall through to the remainder
                   4090:     #   of the if/else chain below in order to keep this thing in 
                   4091:     #   working order throughout the transmogrification.
                   4092: 
                   4093:     my ($command, $tail) = split(/:/, $userinput, 2);
                   4094:     chomp($command);
                   4095:     chomp($tail);
                   4096:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     4097:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   4098:     if(!$tail) {
                   4099: 	$tail ="";		# defined but blank.
                   4100:     }
1.213     foxr     4101: 
                   4102:     &Debug("Command received: $command, encoded = $wasenc");
                   4103: 
                   4104:     if(defined $Dispatcher{$command}) {
                   4105: 
                   4106: 	my $dispatch_info = $Dispatcher{$command};
                   4107: 	my $handler       = $$dispatch_info[0];
                   4108: 	my $need_encode   = $$dispatch_info[1];
                   4109: 	my $client_types  = $$dispatch_info[2];
                   4110: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   4111: 	      ."ClientType $client_types");
                   4112:       
                   4113: 	#  Validate the request:
                   4114:       
                   4115: 	my $ok = 1;
                   4116: 	my $requesterprivs = 0;
                   4117: 	if(&isClient()) {
                   4118: 	    $requesterprivs |= $CLIENT_OK;
                   4119: 	}
                   4120: 	if(&isManager()) {
                   4121: 	    $requesterprivs |= $MANAGER_OK;
                   4122: 	}
                   4123: 	if($need_encode && (!$wasenc)) {
                   4124: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   4125: 	    $ok = 0;
                   4126: 	}
                   4127: 	if(($client_types & $requesterprivs) == 0) {
                   4128: 	    Debug("Client not privileged to do this operation");
                   4129: 	    $ok = 0;
                   4130: 	}
                   4131: 
                   4132: 	if($ok) {
                   4133: 	    Debug("Dispatching to handler $command $tail");
                   4134: 	    my $keep_going = &$handler($command, $tail, $client);
                   4135: 	    return $keep_going;
                   4136: 	} else {
                   4137: 	    Debug("Refusing to dispatch because client did not match requirements");
                   4138: 	    Failure($client, "refused\n", $userinput);
                   4139: 	    return 1;
                   4140: 	}
                   4141: 
                   4142:     }    
                   4143: 
1.262     foxr     4144:     print $client "unknown_cmd\n";
1.212     foxr     4145: # -------------------------------------------------------------------- complete
                   4146:     Debug("process_request - returning 1");
                   4147:     return 1;
                   4148: }
1.207     foxr     4149: #
                   4150: #   Decipher encoded traffic
                   4151: #  Parameters:
                   4152: #     input      - Encoded data.
                   4153: #  Returns:
                   4154: #     Decoded data or undef if encryption key was not yet negotiated.
                   4155: #  Implicit input:
                   4156: #     cipher  - This global holds the negotiated encryption key.
                   4157: #
1.211     albertel 4158: sub decipher {
1.207     foxr     4159:     my ($input)  = @_;
                   4160:     my $output = '';
1.212     foxr     4161:     
                   4162:     
1.207     foxr     4163:     if($cipher) {
                   4164: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   4165: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   4166: 	    $output .= 
                   4167: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   4168: 	}
                   4169: 	return substr($output, 0, $enclength);
                   4170:     } else {
                   4171: 	return undef;
                   4172:     }
                   4173: }
                   4174: 
                   4175: #
                   4176: #   Register a command processor.  This function is invoked to register a sub
                   4177: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   4178: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   4179: #   as well:
                   4180: #    - Is the keyword recognized.
                   4181: #    - Is the proper client type attempting the request.
                   4182: #    - Is the request encrypted if it has to be.
                   4183: #   Parameters:
                   4184: #    $request_name         - Name of the request being registered.
                   4185: #                           This is the command request that will match
                   4186: #                           against the hash keywords to lookup the information
                   4187: #                           associated with the dispatch information.
                   4188: #    $procedure           - Reference to a sub to call to process the request.
                   4189: #                           All subs get called as follows:
                   4190: #                             Procedure($cmd, $tail, $replyfd, $key)
                   4191: #                             $cmd    - the actual keyword that invoked us.
                   4192: #                             $tail   - the tail of the request that invoked us.
                   4193: #                             $replyfd- File descriptor connected to the client
                   4194: #    $must_encode          - True if the request must be encoded to be good.
                   4195: #    $client_ok            - True if it's ok for a client to request this.
                   4196: #    $manager_ok           - True if it's ok for a manager to request this.
                   4197: # Side effects:
                   4198: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   4199: #      - On failure, the program will die as it's a bad internal bug to try to 
                   4200: #        register a duplicate command handler.
                   4201: #
1.211     albertel 4202: sub register_handler {
1.212     foxr     4203:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     4204: 
                   4205:     #  Don't allow duplication#
                   4206:    
                   4207:     if (defined $Dispatcher{$request_name}) {
                   4208: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   4209:     }
                   4210:     #   Build the client type mask:
                   4211:     
                   4212:     my $client_type_mask = 0;
                   4213:     if($client_ok) {
                   4214: 	$client_type_mask  |= $CLIENT_OK;
                   4215:     }
                   4216:     if($manager_ok) {
                   4217: 	$client_type_mask  |= $MANAGER_OK;
                   4218:     }
                   4219:    
                   4220:     #  Enter the hash:
                   4221:       
                   4222:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   4223:    
                   4224:     $Dispatcher{$request_name} = \@entry;
                   4225:    
                   4226: }
                   4227: 
                   4228: 
                   4229: #------------------------------------------------------------------
                   4230: 
                   4231: 
                   4232: 
                   4233: 
1.141     foxr     4234: #
1.96      foxr     4235: #  Convert an error return code from lcpasswd to a string value.
                   4236: #
                   4237: sub lcpasswdstrerror {
                   4238:     my $ErrorCode = shift;
1.97      foxr     4239:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     4240: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   4241:     } else {
1.98      foxr     4242: 	return $passwderrors[$ErrorCode];
1.96      foxr     4243:     }
                   4244: }
                   4245: 
1.97      foxr     4246: #
                   4247: # Convert an error return code from lcuseradd to a string value:
                   4248: #
                   4249: sub lcuseraddstrerror {
                   4250:     my $ErrorCode = shift;
                   4251:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
                   4252: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
                   4253:     } else {
1.98      foxr     4254: 	return $adderrors[$ErrorCode];
1.97      foxr     4255:     }
                   4256: }
                   4257: 
1.23      harris41 4258: # grabs exception and records it to log before exiting
                   4259: sub catchexception {
1.27      albertel 4260:     my ($error)=@_;
1.25      www      4261:     $SIG{'QUIT'}='DEFAULT';
                   4262:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 4263:     &status("Catching exception");
1.190     albertel 4264:     &logthis("<font color='red'>CRITICAL: "
1.134     albertel 4265:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27      albertel 4266:      ."a crash with this error msg->[$error]</font>");
1.57      www      4267:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 4268:     if ($client) { print $client "error: $error\n"; }
1.59      www      4269:     $server->close();
1.27      albertel 4270:     die($error);
1.23      harris41 4271: }
1.63      www      4272: sub timeout {
1.165     albertel 4273:     &status("Handling Timeout");
1.190     albertel 4274:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      4275:     &catchexception('Timeout');
                   4276: }
1.22      harris41 4277: # -------------------------------- Set signal handlers to record abnormal exits
                   4278: 
1.226     foxr     4279: 
1.22      harris41 4280: $SIG{'QUIT'}=\&catchexception;
                   4281: $SIG{__DIE__}=\&catchexception;
                   4282: 
1.81      matthew  4283: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 4284: &status("Read loncapa.conf and loncapa_apache.conf");
                   4285: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     4286: %perlvar=%{$perlvarref};
1.80      harris41 4287: undef $perlvarref;
1.19      www      4288: 
1.35      harris41 4289: # ----------------------------- Make sure this process is running from user=www
                   4290: my $wwwid=getpwnam('www');
                   4291: if ($wwwid!=$<) {
1.134     albertel 4292:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4293:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 4294:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 4295:  mailto $emailto -s '$subj' > /dev/null");
                   4296:    exit 1;
                   4297: }
                   4298: 
1.19      www      4299: # --------------------------------------------- Check if other instance running
                   4300: 
                   4301: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   4302: 
                   4303: if (-e $pidfile) {
                   4304:    my $lfh=IO::File->new("$pidfile");
                   4305:    my $pide=<$lfh>;
                   4306:    chomp($pide);
1.29      harris41 4307:    if (kill 0 => $pide) { die "already running"; }
1.19      www      4308: }
1.1       albertel 4309: 
                   4310: # ------------------------------------------------------------- Read hosts file
                   4311: 
                   4312: 
                   4313: 
                   4314: # establish SERVER socket, bind and listen.
                   4315: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   4316:                                 Type      => SOCK_STREAM,
                   4317:                                 Proto     => 'tcp',
                   4318:                                 Reuse     => 1,
                   4319:                                 Listen    => 10 )
1.29      harris41 4320:   or die "making socket: $@\n";
1.1       albertel 4321: 
                   4322: # --------------------------------------------------------- Do global variables
                   4323: 
                   4324: # global variables
                   4325: 
1.134     albertel 4326: my %children               = ();       # keys are current child process IDs
1.1       albertel 4327: 
                   4328: sub REAPER {                        # takes care of dead children
                   4329:     $SIG{CHLD} = \&REAPER;
1.165     albertel 4330:     &status("Handling child death");
1.178     foxr     4331:     my $pid;
                   4332:     do {
                   4333: 	$pid = waitpid(-1,&WNOHANG());
                   4334: 	if (defined($children{$pid})) {
                   4335: 	    &logthis("Child $pid died");
                   4336: 	    delete($children{$pid});
1.183     albertel 4337: 	} elsif ($pid > 0) {
1.178     foxr     4338: 	    &logthis("Unknown Child $pid died");
                   4339: 	}
                   4340:     } while ( $pid > 0 );
                   4341:     foreach my $child (keys(%children)) {
                   4342: 	$pid = waitpid($child,&WNOHANG());
                   4343: 	if ($pid > 0) {
                   4344: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   4345: 	    delete($children{$pid});
                   4346: 	}
1.176     albertel 4347:     }
1.165     albertel 4348:     &status("Finished Handling child death");
1.1       albertel 4349: }
                   4350: 
                   4351: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 4352:     &status("Killing children (INT)");
1.1       albertel 4353:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   4354:     kill 'INT' => keys %children;
1.59      www      4355:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 4356:     my $execdir=$perlvar{'lonDaemons'};
                   4357:     unlink("$execdir/logs/lond.pid");
1.190     albertel 4358:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 4359:     &status("Done killing children");
1.1       albertel 4360:     exit;                           # clean up with dignity
                   4361: }
                   4362: 
                   4363: sub HUPSMAN {                      # signal handler for SIGHUP
                   4364:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 4365:     &status("Killing children for restart (HUP)");
1.1       albertel 4366:     kill 'INT' => keys %children;
1.59      www      4367:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 4368:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 4369:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 4370:     unlink("$execdir/logs/lond.pid");
1.165     albertel 4371:     &status("Restarting self (HUP)");
1.1       albertel 4372:     exec("$execdir/lond");         # here we go again
                   4373: }
                   4374: 
1.144     foxr     4375: #
1.148     foxr     4376: #    Kill off hashes that describe the host table prior to re-reading it.
                   4377: #    Hashes affected are:
1.200     matthew  4378: #       %hostid, %hostdom %hostip %hostdns.
1.148     foxr     4379: #
                   4380: sub KillHostHashes {
                   4381:     foreach my $key (keys %hostid) {
                   4382: 	delete $hostid{$key};
                   4383:     }
                   4384:     foreach my $key (keys %hostdom) {
                   4385: 	delete $hostdom{$key};
                   4386:     }
                   4387:     foreach my $key (keys %hostip) {
                   4388: 	delete $hostip{$key};
                   4389:     }
1.200     matthew  4390:     foreach my $key (keys %hostdns) {
                   4391: 	delete $hostdns{$key};
                   4392:     }
1.148     foxr     4393: }
                   4394: #
                   4395: #   Read in the host table from file and distribute it into the various hashes:
                   4396: #
                   4397: #    - %hostid  -  Indexed by IP, the loncapa hostname.
                   4398: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
                   4399: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
                   4400: sub ReadHostTable {
                   4401: 
                   4402:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200     matthew  4403:     my $myloncapaname = $perlvar{'lonHostID'};
                   4404:     Debug("My loncapa name is : $myloncapaname");
1.148     foxr     4405:     while (my $configline=<CONFIG>) {
1.277     albertel 4406: 	if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
                   4407: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   4408: 	    $name=~s/\s//g;
1.279     albertel 4409: 	    my $ip = gethostbyname($name);
1.277     albertel 4410: 	    if (length($ip) ne 4) {
                   4411: 		&logthis("Skipping host $id name $name no IP $ip found\n");
                   4412: 		next;
                   4413: 	    }
                   4414: 	    $ip=inet_ntoa($ip);
1.200     matthew  4415: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
                   4416: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
1.277     albertel 4417: 	    $hostip{$id}=$ip;         # IP address of host.
1.200     matthew  4418: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
                   4419: 
                   4420: 	    if ($id eq $perlvar{'lonHostID'}) { 
                   4421: 		Debug("Found me in the host table: $name");
                   4422: 		$thisserver=$name; 
                   4423: 	    }
1.178     foxr     4424: 	}
1.148     foxr     4425:     }
                   4426:     close(CONFIG);
                   4427: }
                   4428: #
                   4429: #  Reload the Apache daemon's state.
1.150     foxr     4430: #  This is done by invoking /home/httpd/perl/apachereload
                   4431: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     4432: #
                   4433: sub ReloadApache {
1.150     foxr     4434:     my $execdir = $perlvar{'lonDaemons'};
                   4435:     my $script  = $execdir."/apachereload";
                   4436:     system($script);
1.148     foxr     4437: }
                   4438: 
                   4439: #
1.144     foxr     4440: #   Called in response to a USR2 signal.
                   4441: #   - Reread hosts.tab
                   4442: #   - All children connected to hosts that were removed from hosts.tab
                   4443: #     are killed via SIGINT
                   4444: #   - All children connected to previously existing hosts are sent SIGUSR1
                   4445: #   - Our internal hosts hash is updated to reflect the new contents of
                   4446: #     hosts.tab causing connections from hosts added to hosts.tab to
                   4447: #     now be honored.
                   4448: #
                   4449: sub UpdateHosts {
1.165     albertel 4450:     &status("Reload hosts.tab");
1.147     foxr     4451:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     4452:     #
                   4453:     #  The %children hash has the set of IP's we currently have children
                   4454:     #  on.  These need to be matched against records in the hosts.tab
                   4455:     #  Any ip's no longer in the table get killed off they correspond to
                   4456:     #  either dropped or changed hosts.  Note that the re-read of the table
                   4457:     #  will take care of new and changed hosts as connections come into being.
                   4458: 
                   4459: 
                   4460:     KillHostHashes;
                   4461:     ReadHostTable;
                   4462: 
                   4463:     foreach my $child (keys %children) {
                   4464: 	my $childip = $children{$child};
                   4465: 	if(!$hostid{$childip}) {
1.149     foxr     4466: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   4467: 		    ." $child for ip $childip </font>");
1.148     foxr     4468: 	    kill('INT', $child);
1.149     foxr     4469: 	} else {
                   4470: 	    logthis('<font color="green"> keeping child for ip '
                   4471: 		    ." $childip (pid=$child) </font>");
1.148     foxr     4472: 	}
                   4473:     }
                   4474:     ReloadApache;
1.165     albertel 4475:     &status("Finished reloading hosts.tab");
1.144     foxr     4476: }
                   4477: 
1.148     foxr     4478: 
1.57      www      4479: sub checkchildren {
1.165     albertel 4480:     &status("Checking on the children (sending signals)");
1.57      www      4481:     &initnewstatus();
                   4482:     &logstatus();
                   4483:     &logthis('Going to check on the children');
1.134     albertel 4484:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 4485:     foreach (sort keys %children) {
1.221     albertel 4486: 	#sleep 1;
1.57      www      4487:         unless (kill 'USR1' => $_) {
                   4488: 	    &logthis ('Child '.$_.' is dead');
                   4489:             &logstatus($$.' is dead');
1.221     albertel 4490: 	    delete($children{$_});
1.57      www      4491:         } 
1.61      harris41 4492:     }
1.63      www      4493:     sleep 5;
1.212     foxr     4494:     $SIG{ALRM} = sub { Debug("timeout"); 
                   4495: 		       die "timeout";  };
1.113     albertel 4496:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 4497:     &status("Checking on the children (waiting for reports)");
1.63      www      4498:     foreach (sort keys %children) {
                   4499:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 4500:           eval {
                   4501:             alarm(300);
1.63      www      4502: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 4503: 	    kill 9 => $_;
1.131     albertel 4504: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4505: 	    #$subj="LON: $currenthostid killed lond process $_";
                   4506: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   4507: 	    #$execdir=$perlvar{'lonDaemons'};
                   4508: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 4509: 	    delete($children{$_});
1.113     albertel 4510: 	    alarm(0);
                   4511: 	  }
1.63      www      4512:         }
                   4513:     }
1.113     albertel 4514:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 4515:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 4516:     &status("Finished checking children");
1.221     albertel 4517:     &logthis('Finished Checking children');
1.57      www      4518: }
                   4519: 
1.1       albertel 4520: # --------------------------------------------------------------------- Logging
                   4521: 
                   4522: sub logthis {
                   4523:     my $message=shift;
                   4524:     my $execdir=$perlvar{'lonDaemons'};
                   4525:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   4526:     my $now=time;
                   4527:     my $local=localtime($now);
1.58      www      4528:     $lastlog=$local.': '.$message;
1.1       albertel 4529:     print $fh "$local ($$): $message\n";
                   4530: }
                   4531: 
1.77      foxr     4532: # ------------------------- Conditional log if $DEBUG true.
                   4533: sub Debug {
                   4534:     my $message = shift;
                   4535:     if($DEBUG) {
                   4536: 	&logthis($message);
                   4537:     }
                   4538: }
1.161     foxr     4539: 
                   4540: #
                   4541: #   Sub to do replies to client.. this gives a hook for some
                   4542: #   debug tracing too:
                   4543: #  Parameters:
                   4544: #     fd      - File open on client.
                   4545: #     reply   - Text to send to client.
                   4546: #     request - Original request from client.
                   4547: #
                   4548: sub Reply {
1.192     foxr     4549:     my ($fd, $reply, $request) = @_;
1.161     foxr     4550:     print $fd $reply;
                   4551:     Debug("Request was $request  Reply was $reply");
                   4552: 
1.212     foxr     4553:     $Transactions++;
                   4554: }
                   4555: 
                   4556: 
                   4557: #
                   4558: #    Sub to report a failure.
                   4559: #    This function:
                   4560: #     -   Increments the failure statistic counters.
                   4561: #     -   Invokes Reply to send the error message to the client.
                   4562: # Parameters:
                   4563: #    fd       - File descriptor open on the client
                   4564: #    reply    - Reply text to emit.
                   4565: #    request  - The original request message (used by Reply
                   4566: #               to debug if that's enabled.
                   4567: # Implicit outputs:
                   4568: #    $Failures- The number of failures is incremented.
                   4569: #    Reply (invoked here) sends a message to the 
                   4570: #    client:
                   4571: #
                   4572: sub Failure {
                   4573:     my $fd      = shift;
                   4574:     my $reply   = shift;
                   4575:     my $request = shift;
                   4576:    
                   4577:     $Failures++;
                   4578:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     4579: }
1.57      www      4580: # ------------------------------------------------------------------ Log status
                   4581: 
                   4582: sub logstatus {
1.178     foxr     4583:     &status("Doing logging");
                   4584:     my $docdir=$perlvar{'lonDocRoot'};
                   4585:     {
                   4586: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  4587:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     4588:         $fh->close();
                   4589:     }
1.221     albertel 4590:     &status("Finished $$.txt");
                   4591:     {
                   4592: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   4593: 	flock(LOG,LOCK_EX);
                   4594: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   4595: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 4596: 	flock(LOG,LOCK_UN);
1.221     albertel 4597: 	close(LOG);
                   4598:     }
1.178     foxr     4599:     &status("Finished logging");
1.57      www      4600: }
                   4601: 
                   4602: sub initnewstatus {
                   4603:     my $docdir=$perlvar{'lonDocRoot'};
                   4604:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
                   4605:     my $now=time;
                   4606:     my $local=localtime($now);
                   4607:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      4608:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 4609:     while (my $filename=readdir(DIR)) {
1.64      www      4610:         unlink("$docdir/lon-status/londchld/$filename");
                   4611:     }
                   4612:     closedir(DIR);
1.57      www      4613: }
                   4614: 
                   4615: # -------------------------------------------------------------- Status setting
                   4616: 
                   4617: sub status {
                   4618:     my $what=shift;
                   4619:     my $now=time;
                   4620:     my $local=localtime($now);
1.178     foxr     4621:     $status=$local.': '.$what;
                   4622:     $0='lond: '.$what.' '.$local;
1.57      www      4623: }
1.11      www      4624: 
                   4625: # -------------------------------------------------------- Escape Special Chars
                   4626: 
                   4627: sub escape {
                   4628:     my $str=shift;
                   4629:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   4630:     return $str;
                   4631: }
                   4632: 
                   4633: # ----------------------------------------------------- Un-Escape Special Chars
                   4634: 
                   4635: sub unescape {
                   4636:     my $str=shift;
                   4637:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   4638:     return $str;
                   4639: }
                   4640: 
1.1       albertel 4641: # ----------------------------------------------------------- Send USR1 to lonc
                   4642: 
                   4643: sub reconlonc {
                   4644:     my $peerfile=shift;
                   4645:     &logthis("Trying to reconnect for $peerfile");
                   4646:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                   4647:     if (my $fh=IO::File->new("$loncfile")) {
                   4648: 	my $loncpid=<$fh>;
                   4649:         chomp($loncpid);
                   4650:         if (kill 0 => $loncpid) {
                   4651: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                   4652:             kill USR1 => $loncpid;
                   4653:         } else {
1.9       www      4654: 	    &logthis(
1.190     albertel 4655:               "<font color='red'>CRITICAL: "
1.9       www      4656:              ."lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel 4657:         }
                   4658:     } else {
1.190     albertel 4659:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1       albertel 4660:     }
                   4661: }
                   4662: 
                   4663: # -------------------------------------------------- Non-critical communication
1.11      www      4664: 
1.1       albertel 4665: sub subreply {
                   4666:     my ($cmd,$server)=@_;
                   4667:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                   4668:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   4669:                                       Type    => SOCK_STREAM,
                   4670:                                       Timeout => 10)
                   4671:        or return "con_lost";
                   4672:     print $sclient "$cmd\n";
                   4673:     my $answer=<$sclient>;
                   4674:     chomp($answer);
                   4675:     if (!$answer) { $answer="con_lost"; }
                   4676:     return $answer;
                   4677: }
                   4678: 
                   4679: sub reply {
                   4680:   my ($cmd,$server)=@_;
                   4681:   my $answer;
1.115     albertel 4682:   if ($server ne $currenthostid) { 
1.1       albertel 4683:     $answer=subreply($cmd,$server);
                   4684:     if ($answer eq 'con_lost') {
                   4685: 	$answer=subreply("ping",$server);
                   4686:         if ($answer ne $server) {
1.115     albertel 4687: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1       albertel 4688:            &reconlonc("$perlvar{'lonSockDir'}/$server");
                   4689:         }
                   4690:         $answer=subreply($cmd,$server);
                   4691:     }
                   4692:   } else {
                   4693:     $answer='self_reply';
                   4694:   } 
                   4695:   return $answer;
                   4696: }
                   4697: 
1.13      www      4698: # -------------------------------------------------------------- Talk to lonsql
                   4699: 
1.234     foxr     4700: sub sql_reply {
1.12      harris41 4701:     my ($cmd)=@_;
1.234     foxr     4702:     my $answer=&sub_sql_reply($cmd);
                   4703:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 4704:     return $answer;
                   4705: }
                   4706: 
1.234     foxr     4707: sub sub_sql_reply {
1.12      harris41 4708:     my ($cmd)=@_;
                   4709:     my $unixsock="mysqlsock";
                   4710:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   4711:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   4712:                                       Type    => SOCK_STREAM,
                   4713:                                       Timeout => 10)
                   4714:        or return "con_lost";
                   4715:     print $sclient "$cmd\n";
                   4716:     my $answer=<$sclient>;
                   4717:     chomp($answer);
                   4718:     if (!$answer) { $answer="con_lost"; }
                   4719:     return $answer;
                   4720: }
                   4721: 
1.1       albertel 4722: # -------------------------------------------- Return path to profile directory
1.11      www      4723: 
1.1       albertel 4724: sub propath {
                   4725:     my ($udom,$uname)=@_;
                   4726:     $udom=~s/\W//g;
                   4727:     $uname=~s/\W//g;
1.16      www      4728:     my $subdir=$uname.'__';
1.1       albertel 4729:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4730:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   4731:     return $proname;
                   4732: } 
                   4733: 
                   4734: # --------------------------------------- Is this the home server of an author?
1.11      www      4735: 
1.1       albertel 4736: sub ishome {
                   4737:     my $author=shift;
                   4738:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   4739:     my ($udom,$uname)=split(/\//,$author);
                   4740:     my $proname=propath($udom,$uname);
                   4741:     if (-e $proname) {
                   4742: 	return 'owner';
                   4743:     } else {
                   4744:         return 'not_owner';
                   4745:     }
                   4746: }
                   4747: 
                   4748: # ======================================================= Continue main program
                   4749: # ---------------------------------------------------- Fork once and dissociate
                   4750: 
1.134     albertel 4751: my $fpid=fork;
1.1       albertel 4752: exit if $fpid;
1.29      harris41 4753: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 4754: 
1.29      harris41 4755: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 4756: 
                   4757: # ------------------------------------------------------- Write our PID on disk
                   4758: 
1.134     albertel 4759: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 4760: open (PIDSAVE,">$execdir/logs/lond.pid");
                   4761: print PIDSAVE "$$\n";
                   4762: close(PIDSAVE);
1.190     albertel 4763: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      4764: &status('Starting');
1.1       albertel 4765: 
1.106     foxr     4766: 
1.1       albertel 4767: 
                   4768: # ----------------------------------------------------- Install signal handlers
                   4769: 
1.57      www      4770: 
1.1       albertel 4771: $SIG{CHLD} = \&REAPER;
                   4772: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   4773: $SIG{HUP}  = \&HUPSMAN;
1.57      www      4774: $SIG{USR1} = \&checkchildren;
1.144     foxr     4775: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     4776: 
1.148     foxr     4777: #  Read the host hashes:
                   4778: 
                   4779: ReadHostTable;
1.106     foxr     4780: 
1.286     albertel 4781: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
                   4782: 
1.106     foxr     4783: # --------------------------------------------------------------
                   4784: #   Accept connections.  When a connection comes in, it is validated
                   4785: #   and if good, a child process is created to process transactions
                   4786: #   along the connection.
                   4787: 
1.1       albertel 4788: while (1) {
1.165     albertel 4789:     &status('Starting accept');
1.106     foxr     4790:     $client = $server->accept() or next;
1.165     albertel 4791:     &status('Accepted '.$client.' off to spawn');
1.106     foxr     4792:     make_new_child($client);
1.165     albertel 4793:     &status('Finished spawning');
1.1       albertel 4794: }
                   4795: 
1.212     foxr     4796: sub make_new_child {
                   4797:     my $pid;
                   4798: #    my $cipher;     # Now global
                   4799:     my $sigset;
1.178     foxr     4800: 
1.212     foxr     4801:     $client = shift;
                   4802:     &status('Starting new child '.$client);
                   4803:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   4804: 	     ")</font>");    
                   4805:     # block signal for fork
                   4806:     $sigset = POSIX::SigSet->new(SIGINT);
                   4807:     sigprocmask(SIG_BLOCK, $sigset)
                   4808:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     4809: 
1.212     foxr     4810:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     4811: 
1.212     foxr     4812:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   4813: 	                               # connection liveness.
1.178     foxr     4814: 
1.212     foxr     4815:     #
                   4816:     #  Figure out who we're talking to so we can record the peer in 
                   4817:     #  the pid hash.
                   4818:     #
                   4819:     my $caller = getpeername($client);
                   4820:     my ($port,$iaddr);
                   4821:     if (defined($caller) && length($caller) > 0) {
                   4822: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   4823:     } else {
                   4824: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   4825:     }
                   4826:     if (defined($iaddr)) {
                   4827: 	$clientip  = inet_ntoa($iaddr);
                   4828: 	Debug("Connected with $clientip");
                   4829:     } else {
                   4830: 	&logthis("Unable to determine clientip");
                   4831: 	$clientip='Unavailable';
                   4832:     }
                   4833:     
                   4834:     if ($pid) {
                   4835:         # Parent records the child's birth and returns.
                   4836:         sigprocmask(SIG_UNBLOCK, $sigset)
                   4837:             or die "Can't unblock SIGINT for fork: $!\n";
                   4838:         $children{$pid} = $clientip;
                   4839:         &status('Started child '.$pid);
                   4840:         return;
                   4841:     } else {
                   4842:         # Child can *not* return from this subroutine.
                   4843:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   4844:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   4845:                                 #don't get intercepted
                   4846:         $SIG{USR1}= \&logstatus;
                   4847:         $SIG{ALRM}= \&timeout;
                   4848:         $lastlog='Forked ';
                   4849:         $status='Forked';
1.178     foxr     4850: 
1.212     foxr     4851:         # unblock signals
                   4852:         sigprocmask(SIG_UNBLOCK, $sigset)
                   4853:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     4854: 
1.212     foxr     4855: #        my $tmpsnum=0;            # Now global
                   4856: #---------------------------------------------------- kerberos 5 initialization
                   4857:         &Authen::Krb5::init_context();
1.286     albertel 4858: 	if ($dist ne 'fedora4') {
                   4859: 	    &Authen::Krb5::init_ets();
                   4860: 	}
1.209     albertel 4861: 
1.212     foxr     4862: 	&status('Accepted connection');
                   4863: # =============================================================================
                   4864:             # do something with the connection
                   4865: # -----------------------------------------------------------------------------
                   4866: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     4867: 
1.212     foxr     4868: 	ReadManagerTable;	# May also be a manager!!
                   4869: 	
1.278     albertel 4870: 	my $outsideip=$clientip;
                   4871: 	if ($clientip eq '127.0.0.1') {
                   4872: 	    $outsideip=$hostip{$perlvar{'lonHostID'}};
                   4873: 	}
                   4874: 
                   4875: 	my $clientrec=($hostid{$outsideip}     ne undef);
                   4876: 	my $ismanager=($managers{$outsideip}    ne undef);
1.212     foxr     4877: 	$clientname  = "[unknonwn]";
                   4878: 	if($clientrec) {	# Establish client type.
                   4879: 	    $ConnectionType = "client";
1.278     albertel 4880: 	    $clientname = $hostid{$outsideip};
1.212     foxr     4881: 	    if($ismanager) {
                   4882: 		$ConnectionType = "both";
                   4883: 	    }
                   4884: 	} else {
                   4885: 	    $ConnectionType = "manager";
1.278     albertel 4886: 	    $clientname = $managers{$outsideip};
1.212     foxr     4887: 	}
                   4888: 	my $clientok;
1.178     foxr     4889: 
1.212     foxr     4890: 	if ($clientrec || $ismanager) {
                   4891: 	    &status("Waiting for init from $clientip $clientname");
                   4892: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   4893: 		     $clientip.
                   4894: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   4895: 	    &status("Connecting $clientip  ($clientname))"); 
                   4896: 	    my $remotereq=<$client>;
                   4897: 	    chomp($remotereq);
                   4898: 	    Debug("Got init: $remotereq");
                   4899: 	    my $inikeyword = split(/:/, $remotereq);
                   4900: 	    if ($remotereq =~ /^init/) {
                   4901: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   4902: 		#
                   4903: 		#  If the remote is attempting a local init... give that a try:
                   4904: 		#
                   4905: 		my ($i, $inittype) = split(/:/, $remotereq);
1.209     albertel 4906: 
1.212     foxr     4907: 		# If the connection type is ssl, but I didn't get my
                   4908: 		# certificate files yet, then I'll drop  back to 
                   4909: 		# insecure (if allowed).
                   4910: 		
                   4911: 		if($inittype eq "ssl") {
                   4912: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   4913: 		    my $kfile       = lonssl::KeyFile;
                   4914: 		    if((!$ca)   || 
                   4915: 		       (!$cert) || 
                   4916: 		       (!$kfile)) {
                   4917: 			$inittype = ""; # This forces insecure attempt.
                   4918: 			&logthis("<font color=\"blue\"> Certificates not "
                   4919: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     4920: 		    } else {	# SSL certificates are in place so
1.212     foxr     4921: 		    }		# Leave the inittype alone.
                   4922: 		}
                   4923: 
                   4924: 		if($inittype eq "local") {
                   4925: 		    my $key = LocalConnection($client, $remotereq);
                   4926: 		    if($key) {
                   4927: 			Debug("Got local key $key");
                   4928: 			$clientok     = 1;
                   4929: 			my $cipherkey = pack("H32", $key);
                   4930: 			$cipher       = new IDEA($cipherkey);
                   4931: 			print $client "ok:local\n";
                   4932: 			&logthis('<font color="green"'
                   4933: 				 . "Successful local authentication </font>");
                   4934: 			$keymode = "local"
1.178     foxr     4935: 		    } else {
1.212     foxr     4936: 			Debug("Failed to get local key");
                   4937: 			$clientok = 0;
                   4938: 			shutdown($client, 3);
                   4939: 			close $client;
1.178     foxr     4940: 		    }
1.212     foxr     4941: 		} elsif ($inittype eq "ssl") {
                   4942: 		    my $key = SSLConnection($client);
                   4943: 		    if ($key) {
                   4944: 			$clientok = 1;
                   4945: 			my $cipherkey = pack("H32", $key);
                   4946: 			$cipher       = new IDEA($cipherkey);
                   4947: 			&logthis('<font color="green">'
                   4948: 				 ."Successfull ssl authentication with $clientname </font>");
                   4949: 			$keymode = "ssl";
                   4950: 	     
1.178     foxr     4951: 		    } else {
1.212     foxr     4952: 			$clientok = 0;
                   4953: 			close $client;
1.178     foxr     4954: 		    }
1.212     foxr     4955: 	   
                   4956: 		} else {
                   4957: 		    my $ok = InsecureConnection($client);
                   4958: 		    if($ok) {
                   4959: 			$clientok = 1;
                   4960: 			&logthis('<font color="green">'
                   4961: 				 ."Successful insecure authentication with $clientname </font>");
                   4962: 			print $client "ok\n";
                   4963: 			$keymode = "insecure";
1.178     foxr     4964: 		    } else {
1.212     foxr     4965: 			&logthis('<font color="yellow">'
                   4966: 				  ."Attempted insecure connection disallowed </font>");
                   4967: 			close $client;
                   4968: 			$clientok = 0;
1.178     foxr     4969: 			
                   4970: 		    }
                   4971: 		}
1.212     foxr     4972: 	    } else {
                   4973: 		&logthis(
                   4974: 			 "<font color='blue'>WARNING: "
                   4975: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   4976: 		&status('No init '.$clientip);
                   4977: 	    }
                   4978: 	    
                   4979: 	} else {
                   4980: 	    &logthis(
                   4981: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   4982: 	    &status('Hung up on '.$clientip);
                   4983: 	}
                   4984:  
                   4985: 	if ($clientok) {
                   4986: # ---------------- New known client connecting, could mean machine online again
                   4987: 	    
                   4988: 	    foreach my $id (keys(%hostip)) {
                   4989: 		if ($hostip{$id} ne $clientip ||
                   4990: 		    $hostip{$currenthostid} eq $clientip) {
                   4991: 		    # no need to try to do recon's to myself
                   4992: 		    next;
                   4993: 		}
                   4994: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
                   4995: 	    }
                   4996: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   4997: 	    &status('Will listen to '.$clientname);
                   4998: # ------------------------------------------------------------ Process requests
                   4999: 	    my $keep_going = 1;
                   5000: 	    my $user_input;
                   5001: 	    while(($user_input = get_request) && $keep_going) {
                   5002: 		alarm(120);
                   5003: 		Debug("Main: Got $user_input\n");
                   5004: 		$keep_going = &process_request($user_input);
1.178     foxr     5005: 		alarm(0);
1.212     foxr     5006: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     5007: 	    }
1.212     foxr     5008: 
1.59      www      5009: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     5010: 	}  else {
1.161     foxr     5011: 	    print $client "refused\n";
                   5012: 	    $client->close();
1.190     albertel 5013: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     5014: 		     ."Rejected client $clientip, closing connection</font>");
                   5015: 	}
1.212     foxr     5016:     }            
1.161     foxr     5017:     
1.1       albertel 5018: # =============================================================================
1.161     foxr     5019:     
1.190     albertel 5020:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     5021: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   5022:     
                   5023:     
                   5024:     # this exit is VERY important, otherwise the child will become
                   5025:     # a producer of more and more children, forking yourself into
                   5026:     # process death.
                   5027:     exit;
1.106     foxr     5028:     
1.78      foxr     5029: }
1.261     foxr     5030: #
                   5031: #   Determine if a user is an author for the indicated domain.
                   5032: #
                   5033: # Parameters:
                   5034: #    domain          - domain to check in .
                   5035: #    user            - Name of user to check.
                   5036: #
                   5037: # Return:
                   5038: #     1             - User is an author for domain.
                   5039: #     0             - User is not an author for domain.
                   5040: sub is_author {
                   5041:     my ($domain, $user) = @_;
                   5042: 
                   5043:     &Debug("is_author: $user @ $domain");
                   5044: 
                   5045:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   5046: 				 &GDBM_READER());
                   5047: 
                   5048:     #  Author role should show up as a key /domain/_au
1.78      foxr     5049: 
1.261     foxr     5050:     my $key   = "/$domain/_au";
                   5051:     my $value = $hashref->{$key};
1.78      foxr     5052: 
1.261     foxr     5053:     if(defined($value)) {
                   5054: 	&Debug("$user @ $domain is an author");
                   5055:     }
                   5056: 
                   5057:     return defined($value);
                   5058: }
1.78      foxr     5059: #
                   5060: #   Checks to see if the input roleput request was to set
                   5061: # an author role.  If so, invokes the lchtmldir script to set
                   5062: # up a correct public_html 
                   5063: # Parameters:
                   5064: #    request   - The request sent to the rolesput subchunk.
                   5065: #                We're looking for  /domain/_au
                   5066: #    domain    - The domain in which the user is having roles doctored.
                   5067: #    user      - Name of the user for which the role is being put.
                   5068: #    authtype  - The authentication type associated with the user.
                   5069: #
1.230     foxr     5070: sub manage_permissions
1.78      foxr     5071: {
1.192     foxr     5072: 
1.261     foxr     5073: 
1.192     foxr     5074:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     5075: 
1.261     foxr     5076:     &Debug("manage_permissions: $request $domain $user $authtype");
                   5077: 
1.78      foxr     5078:     # See if the request is of the form /$domain/_au
                   5079:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
                   5080: 	my $execdir = $perlvar{'lonDaemons'};
                   5081: 	my $userhome= "/home/$user" ;
1.134     albertel 5082: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261     foxr     5083: 	&Debug("Setting homedir permissions for $userhome");
1.78      foxr     5084: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   5085:     }
                   5086: }
1.222     foxr     5087: 
                   5088: 
                   5089: #
                   5090: #  Return the full path of a user password file, whether it exists or not.
                   5091: # Parameters:
                   5092: #   domain     - Domain in which the password file lives.
                   5093: #   user       - name of the user.
                   5094: # Returns:
                   5095: #    Full passwd path:
                   5096: #
                   5097: sub password_path {
                   5098:     my ($domain, $user) = @_;
1.264     albertel 5099:     return &propath($domain, $user).'/passwd';
1.222     foxr     5100: }
                   5101: 
                   5102: #   Password Filename
                   5103: #   Returns the path to a passwd file given domain and user... only if
                   5104: #  it exists.
                   5105: # Parameters:
                   5106: #   domain    - Domain in which to search.
                   5107: #   user      - username.
                   5108: # Returns:
                   5109: #   - If the password file exists returns its path.
                   5110: #   - If the password file does not exist, returns undefined.
                   5111: #
                   5112: sub password_filename {
                   5113:     my ($domain, $user) = @_;
                   5114: 
                   5115:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   5116: 
                   5117:     my $path  = &password_path($domain, $user);
                   5118:     Debug("PasswordFilename got path: $path");
                   5119:     if(-e $path) {
                   5120: 	return $path;
                   5121:     } else {
                   5122: 	return undef;
                   5123:     }
                   5124: }
                   5125: 
                   5126: #
                   5127: #   Rewrite the contents of the user's passwd file.
                   5128: #  Parameters:
                   5129: #    domain    - domain of the user.
                   5130: #    name      - User's name.
                   5131: #    contents  - New contents of the file.
                   5132: # Returns:
                   5133: #   0    - Failed.
                   5134: #   1    - Success.
                   5135: #
                   5136: sub rewrite_password_file {
                   5137:     my ($domain, $user, $contents) = @_;
                   5138: 
                   5139:     my $file = &password_filename($domain, $user);
                   5140:     if (defined $file) {
                   5141: 	my $pf = IO::File->new(">$file");
                   5142: 	if($pf) {
                   5143: 	    print $pf "$contents\n";
                   5144: 	    return 1;
                   5145: 	} else {
                   5146: 	    return 0;
                   5147: 	}
                   5148:     } else {
                   5149: 	return 0;
                   5150:     }
                   5151: 
                   5152: }
                   5153: 
1.78      foxr     5154: #
1.222     foxr     5155: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     5156: 
                   5157: #     Returns the authorization type or nouser if there is no such user.
                   5158: #
1.222     foxr     5159: sub get_auth_type 
1.78      foxr     5160: {
1.192     foxr     5161: 
                   5162:     my ($domain, $user)  = @_;
1.78      foxr     5163: 
1.222     foxr     5164:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     5165:     my $proname    = &propath($domain, $user); 
                   5166:     my $passwdfile = "$proname/passwd";
                   5167:     if( -e $passwdfile ) {
                   5168: 	my $pf = IO::File->new($passwdfile);
                   5169: 	my $realpassword = <$pf>;
                   5170: 	chomp($realpassword);
1.79      foxr     5171: 	Debug("Password info = $realpassword\n");
1.78      foxr     5172: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     5173: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  5174: 	return "$authtype:$contentpwd";     
1.224     foxr     5175:     } else {
1.79      foxr     5176: 	Debug("Returning nouser");
1.78      foxr     5177: 	return "nouser";
                   5178:     }
1.1       albertel 5179: }
                   5180: 
1.220     foxr     5181: #
                   5182: #  Validate a user given their domain, name and password.  This utility
                   5183: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   5184: #  to validate the login credentials of a user.
                   5185: # Parameters:
                   5186: #    $domain    - The domain being logged into (this is required due to
                   5187: #                 the capability for multihomed systems.
                   5188: #    $user      - The name of the user being validated.
                   5189: #    $password  - The user's propoposed password.
                   5190: #
                   5191: # Returns:
                   5192: #     1        - The domain,user,pasword triplet corresponds to a valid
                   5193: #                user.
                   5194: #     0        - The domain,user,password triplet is not a valid user.
                   5195: #
                   5196: sub validate_user {
                   5197:     my ($domain, $user, $password) = @_;
                   5198: 
                   5199: 
                   5200:     # Why negative ~pi you may well ask?  Well this function is about
                   5201:     # authentication, and therefore very important to get right.
                   5202:     # I've initialized the flag that determines whether or not I've 
                   5203:     # validated correctly to a value it's not supposed to get.
                   5204:     # At the end of this function. I'll ensure that it's not still that
                   5205:     # value so we don't just wind up returning some accidental value
                   5206:     # as a result of executing an unforseen code path that
1.249     foxr     5207:     # did not set $validated.  At the end of valid execution paths,
                   5208:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     5209: 
                   5210:     my $validated = -3.14159;
                   5211: 
                   5212:     #  How we authenticate is determined by the type of authentication
                   5213:     #  the user has been assigned.  If the authentication type is
                   5214:     #  "nouser", the user does not exist so we will return 0.
                   5215: 
1.222     foxr     5216:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     5217:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   5218: 
                   5219:     my $null = pack("C",0);	# Used by kerberos auth types.
                   5220: 
                   5221:     if ($howpwd ne 'nouser') {
                   5222: 
                   5223: 	if($howpwd eq "internal") { # Encrypted is in local password file.
                   5224: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
                   5225: 	}
                   5226: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   5227: 	    $contentpwd = (getpwnam($user))[1];
                   5228: 	    if($contentpwd) {
                   5229: 		if($contentpwd eq 'x') { # Shadow password file...
                   5230: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   5231: 		    open PWAUTH,  "|$pwauth_path" or
                   5232: 			die "Cannot invoke authentication";
                   5233: 		    print PWAUTH "$user\n$password\n";
                   5234: 		    close PWAUTH;
                   5235: 		    $validated = ! $?;
                   5236: 
                   5237: 		} else { 	         # Passwords in /etc/passwd. 
                   5238: 		    $validated = (crypt($password,
                   5239: 					$contentpwd) eq $contentpwd);
                   5240: 		}
                   5241: 	    } else {
                   5242: 		$validated = 0;
                   5243: 	    }
                   5244: 	}
                   5245: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   5246: 	    if(! ($password =~ /$null/) ) {
                   5247: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   5248: 							   "",
                   5249: 							   $contentpwd,,
                   5250: 							   'krbtgt',
                   5251: 							   $contentpwd,
                   5252: 							   1,
                   5253: 							   $password);
                   5254: 		if(!$k4error) {
                   5255: 		    $validated = 1;
1.224     foxr     5256: 		} else {
1.220     foxr     5257: 		    $validated = 0;
                   5258: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   5259: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   5260: 		}
1.224     foxr     5261: 	    } else {
1.220     foxr     5262: 		$validated = 0; # Password has a match with null.
                   5263: 	    }
1.224     foxr     5264: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220     foxr     5265: 	    if(!($password =~ /$null/)) { # Null password not allowed.
                   5266: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   5267: 							  .$contentpwd);
                   5268: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   5269: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   5270: 		my $credentials= &Authen::Krb5::cc_default();
                   5271: 		$credentials->initialize($krbclient);
1.270     matthew  5272: 		my $krbreturn  = &Authen::Krb5::get_in_tkt_with_password($krbclient,
1.220     foxr     5273: 									 $krbserver,
                   5274: 									 $password,
                   5275: 									 $credentials);
                   5276: 		$validated = ($krbreturn == 1);
1.224     foxr     5277: 	    } else {
1.220     foxr     5278: 		$validated = 0;
                   5279: 	    }
1.224     foxr     5280: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     5281: 	    #  Authenticate via installation specific authentcation method:
                   5282: 	    $validated = &localauth::localauth($user, 
                   5283: 					       $password, 
                   5284: 					       $contentpwd);
1.224     foxr     5285: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     5286: 	    $validated = 0;
                   5287: 	}
                   5288:     } else {
                   5289: 	$validated = 0;
                   5290:     }
                   5291:     #
                   5292:     #  $validated has the correct stat of the authentication:
                   5293:     #
                   5294: 
                   5295:     unless ($validated != -3.14159) {
1.249     foxr     5296: 	#  I >really really< want to know if this happens.
                   5297: 	#  since it indicates that user authentication is badly
                   5298: 	#  broken in some code path.
                   5299:         #
                   5300: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     5301:     }
                   5302:     return $validated;
                   5303: }
                   5304: 
                   5305: 
1.84      albertel 5306: sub addline {
                   5307:     my ($fname,$hostid,$ip,$newline)=@_;
                   5308:     my $contents;
                   5309:     my $found=0;
                   5310:     my $expr='^'.$hostid.':'.$ip.':';
                   5311:     $expr =~ s/\./\\\./g;
1.134     albertel 5312:     my $sh;
1.84      albertel 5313:     if ($sh=IO::File->new("$fname.subscription")) {
                   5314: 	while (my $subline=<$sh>) {
                   5315: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   5316: 	}
                   5317: 	$sh->close();
                   5318:     }
                   5319:     $sh=IO::File->new(">$fname.subscription");
                   5320:     if ($contents) { print $sh $contents; }
                   5321:     if ($newline) { print $sh $newline; }
                   5322:     $sh->close();
                   5323:     return $found;
1.86      www      5324: }
                   5325: 
1.234     foxr     5326: sub get_chat {
1.122     www      5327:     my ($cdom,$cname,$udom,$uname)=@_;
1.87      www      5328:     my %hash;
                   5329:     my $proname=&propath($cdom,$cname);
                   5330:     my @entries=();
1.88      albertel 5331:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   5332: 	    &GDBM_READER(),0640)) {
                   5333: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   5334: 	untie %hash;
1.123     www      5335:     }
1.124     www      5336:     my @participants=();
1.134     albertel 5337:     my $cutoff=time-60;
1.123     www      5338:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124     www      5339: 	    &GDBM_WRCREAT(),0640)) {
                   5340:         $hash{$uname.':'.$udom}=time;
1.123     www      5341:         foreach (sort keys %hash) {
                   5342: 	    if ($hash{$_}>$cutoff) {
1.124     www      5343: 		$participants[$#participants+1]='active_participant:'.$_;
1.123     www      5344:             }
                   5345:         }
                   5346:         untie %hash;
1.86      www      5347:     }
1.124     www      5348:     return (@participants,@entries);
1.86      www      5349: }
                   5350: 
1.234     foxr     5351: sub chat_add {
1.88      albertel 5352:     my ($cdom,$cname,$newchat)=@_;
                   5353:     my %hash;
                   5354:     my $proname=&propath($cdom,$cname);
                   5355:     my @entries=();
1.142     www      5356:     my $time=time;
1.88      albertel 5357:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   5358: 	    &GDBM_WRCREAT(),0640)) {
                   5359: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   5360: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   5361: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   5362: 	my $newid=$time.'_000000';
                   5363: 	if ($thentime==$time) {
                   5364: 	    $idnum=~s/^0+//;
                   5365: 	    $idnum++;
                   5366: 	    $idnum=substr('000000'.$idnum,-6,6);
                   5367: 	    $newid=$time.'_'.$idnum;
                   5368: 	}
                   5369: 	$hash{$newid}=$newchat;
                   5370: 	my $expired=$time-3600;
                   5371: 	foreach (keys %hash) {
                   5372: 	    my ($thistime)=($_=~/(\d+)\_/);
                   5373: 	    if ($thistime<$expired) {
1.89      www      5374: 		delete $hash{$_};
1.88      albertel 5375: 	    }
                   5376: 	}
                   5377: 	untie %hash;
1.142     www      5378:     }
                   5379:     {
                   5380: 	my $hfh;
                   5381: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
                   5382: 	    print $hfh "$time:".&unescape($newchat)."\n";
                   5383: 	}
1.86      www      5384:     }
1.84      albertel 5385: }
                   5386: 
                   5387: sub unsub {
                   5388:     my ($fname,$clientip)=@_;
                   5389:     my $result;
1.188     foxr     5390:     my $unsubs = 0;		# Number of successful unsubscribes:
                   5391: 
                   5392: 
                   5393:     # An old way subscriptions were handled was to have a 
                   5394:     # subscription marker file:
                   5395: 
                   5396:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     5397:     if (unlink("$fname.$clientname")) {
1.188     foxr     5398: 	$unsubs++;		# Successful unsub via marker file.
                   5399:     } 
                   5400: 
                   5401:     # The more modern way to do it is to have a subscription list
                   5402:     # file:
                   5403: 
1.84      albertel 5404:     if (-e "$fname.subscription") {
1.161     foxr     5405: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     5406: 	if ($found) { 
                   5407: 	    $unsubs++;
                   5408: 	}
                   5409:     } 
                   5410: 
                   5411:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   5412:     #  resource we can return ok:
                   5413: 
                   5414:     if($unsubs) {
                   5415: 	$result = "ok\n";
1.84      albertel 5416:     } else {
1.188     foxr     5417: 	$result = "not_subscribed\n";
1.84      albertel 5418:     }
1.188     foxr     5419: 
1.84      albertel 5420:     return $result;
                   5421: }
                   5422: 
1.101     www      5423: sub currentversion {
                   5424:     my $fname=shift;
                   5425:     my $version=-1;
                   5426:     my $ulsdir='';
                   5427:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   5428:        $ulsdir=$1;
                   5429:     }
1.114     albertel 5430:     my ($fnamere1,$fnamere2);
                   5431:     # remove version if already specified
1.101     www      5432:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 5433:     # get the bits that go before and after the version number
                   5434:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   5435: 	$fnamere1=$1;
                   5436: 	$fnamere2='.'.$2;
                   5437:     }
1.101     www      5438:     if (-e $fname) { $version=1; }
                   5439:     if (-e $ulsdir) {
1.134     albertel 5440: 	if(-d $ulsdir) {
                   5441: 	    if (opendir(LSDIR,$ulsdir)) {
                   5442: 		my $ulsfn;
                   5443: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      5444: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 5445: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   5446: 		    unless (-l $thisfile) {
1.160     www      5447: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 5448: 			    if ($1>$version) { $version=$1; }
                   5449: 			}
                   5450: 		    }
                   5451: 		}
                   5452: 		closedir(LSDIR);
                   5453: 		$version++;
                   5454: 	    }
                   5455: 	}
                   5456:     }
                   5457:     return $version;
1.101     www      5458: }
                   5459: 
                   5460: sub thisversion {
                   5461:     my $fname=shift;
                   5462:     my $version=-1;
                   5463:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   5464: 	$version=$1;
                   5465:     }
                   5466:     return $version;
                   5467: }
                   5468: 
1.84      albertel 5469: sub subscribe {
                   5470:     my ($userinput,$clientip)=@_;
                   5471:     my $result;
                   5472:     my ($cmd,$fname)=split(/:/,$userinput);
                   5473:     my $ownership=&ishome($fname);
                   5474:     if ($ownership eq 'owner') {
1.101     www      5475: # explitly asking for the current version?
                   5476:         unless (-e $fname) {
                   5477:             my $currentversion=&currentversion($fname);
                   5478: 	    if (&thisversion($fname)==$currentversion) {
                   5479:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   5480: 		    my $root=$1;
                   5481:                     my $extension=$2;
                   5482:                     symlink($root.'.'.$extension,
                   5483:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      5484:                     unless ($extension=~/\.meta$/) {
                   5485:                        symlink($root.'.'.$extension.'.meta',
                   5486:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   5487: 		    }
1.101     www      5488:                 }
                   5489:             }
                   5490:         }
1.84      albertel 5491: 	if (-e $fname) {
                   5492: 	    if (-d $fname) {
                   5493: 		$result="directory\n";
                   5494: 	    } else {
1.161     foxr     5495: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 5496: 		my $now=time;
1.161     foxr     5497: 		my $found=&addline($fname,$clientname,$clientip,
                   5498: 				   "$clientname:$clientip:$now\n");
1.84      albertel 5499: 		if ($found) { $result="$fname\n"; }
                   5500: 		# if they were subscribed to only meta data, delete that
                   5501:                 # subscription, when you subscribe to a file you also get
                   5502:                 # the metadata
                   5503: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   5504: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
                   5505: 		$fname="http://$thisserver/".$fname;
                   5506: 		$result="$fname\n";
                   5507: 	    }
                   5508: 	} else {
                   5509: 	    $result="not_found\n";
                   5510: 	}
                   5511:     } else {
                   5512: 	$result="rejected\n";
                   5513:     }
                   5514:     return $result;
                   5515: }
1.287     foxr     5516: #  Change the passwd of a unix user.  The caller must have
                   5517: #  first verified that the user is a loncapa user.
                   5518: #
                   5519: # Parameters:
                   5520: #    user      - Unix user name to change.
                   5521: #    pass      - New password for the user.
                   5522: # Returns:
                   5523: #    ok    - if success
                   5524: #    other - Some meaningfule error message string.
                   5525: # NOTE:
                   5526: #    invokes a setuid script to change the passwd.
                   5527: sub change_unix_password {
                   5528:     my ($user, $pass) = @_;
                   5529: 
                   5530:     &Debug("change_unix_password");
                   5531:     my $execdir=$perlvar{'lonDaemons'};
                   5532:     &Debug("Opening lcpasswd pipeline");
                   5533:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   5534: 			   ."$perlvar{'lonDaemons'}"
                   5535: 			   ."/logs/lcpasswd.log");
                   5536:     print $pf "$user\n$pass\n$pass\n";
                   5537:     close $pf;
                   5538:     my $err = $?;
                   5539:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   5540: 	"pwchange_falure - unknown error";
                   5541: 
                   5542:     
                   5543: }
                   5544: 
1.91      albertel 5545: 
                   5546: sub make_passwd_file {
1.98      foxr     5547:     my ($uname, $umode,$npass,$passfilename)=@_;
1.91      albertel 5548:     my $result="ok\n";
                   5549:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   5550: 	{
                   5551: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5552: 	    if ($pf) {
                   5553: 		print $pf "$umode:$npass\n";
                   5554: 	    } else {
                   5555: 		$result = "pass_file_failed_error";
                   5556: 	    }
1.91      albertel 5557: 	}
                   5558:     } elsif ($umode eq 'internal') {
                   5559: 	my $salt=time;
                   5560: 	$salt=substr($salt,6,2);
                   5561: 	my $ncpass=crypt($npass,$salt);
                   5562: 	{
                   5563: 	    &Debug("Creating internal auth");
                   5564: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5565: 	    if($pf) {
                   5566: 		print $pf "internal:$ncpass\n"; 
                   5567: 	    } else {
                   5568: 		$result = "pass_file_failed_error";
                   5569: 	    }
1.91      albertel 5570: 	}
                   5571:     } elsif ($umode eq 'localauth') {
                   5572: 	{
                   5573: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5574: 	    if($pf) {
                   5575: 		print $pf "localauth:$npass\n";
                   5576: 	    } else {
                   5577: 		$result = "pass_file_failed_error";
                   5578: 	    }
1.91      albertel 5579: 	}
                   5580:     } elsif ($umode eq 'unix') {
                   5581: 	{
1.186     foxr     5582: 	    #
                   5583: 	    #  Don't allow the creation of privileged accounts!!! that would
                   5584: 	    #  be real bad!!!
                   5585: 	    #
                   5586: 	    my $uid = getpwnam($uname);
                   5587: 	    if((defined $uid) && ($uid == 0)) {
                   5588: 		&logthis(">>>Attempted to create privilged account blocked");
                   5589: 		return "no_priv_account_error\n";
                   5590: 	    }
                   5591: 
1.223     foxr     5592: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224     foxr     5593: 
                   5594: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
1.91      albertel 5595: 	    {
                   5596: 		&Debug("Executing external: ".$execpath);
1.98      foxr     5597: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  5598: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 5599: 		print $se "$uname\n";
                   5600: 		print $se "$npass\n";
                   5601: 		print $se "$npass\n";
1.223     foxr     5602: 		print $se "$lc_error_file\n"; # Status -> unique file.
1.97      foxr     5603: 	    }
1.285     foxr     5604: 	    if (-r $lc_error_file) {
                   5605: 		&Debug("Opening error file: $lc_error_file");
                   5606: 		my $error = IO::File->new("< $lc_error_file");
                   5607: 		my $useraddok = <$error>;
                   5608: 		$error->close;
                   5609: 		unlink($lc_error_file);
                   5610: 		
                   5611: 		chomp $useraddok;
                   5612: 	
                   5613: 		if($useraddok > 0) {
                   5614: 		    my $error_text = &lcuseraddstrerror($useraddok);
                   5615: 		    &logthis("Failed lcuseradd: $error_text");
                   5616: 		    $result = "lcuseradd_failed:$error_text\n";
                   5617: 		}  else {
                   5618: 		    my $pf = IO::File->new(">$passfilename");
                   5619: 		    if($pf) {
                   5620: 			print $pf "unix:\n";
                   5621: 		    } else {
                   5622: 			$result = "pass_file_failed_error";
                   5623: 		    }
                   5624: 		}
1.224     foxr     5625: 	    }  else {
1.285     foxr     5626: 		&Debug("Could not locate lcuseradd error: $lc_error_file");
                   5627: 		$result="bug_lcuseradd_no_output_file";
1.91      albertel 5628: 	    }
                   5629: 	}
                   5630:     } elsif ($umode eq 'none') {
                   5631: 	{
1.223     foxr     5632: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     5633: 	    if($pf) {
                   5634: 		print $pf "none:\n";
                   5635: 	    } else {
                   5636: 		$result = "pass_file_failed_error";
                   5637: 	    }
1.91      albertel 5638: 	}
                   5639:     } else {
                   5640: 	$result="auth_mode_error\n";
                   5641:     }
                   5642:     return $result;
1.121     albertel 5643: }
                   5644: 
1.265     albertel 5645: sub convert_photo {
                   5646:     my ($start,$dest)=@_;
                   5647:     system("convert $start $dest");
                   5648: }
                   5649: 
1.121     albertel 5650: sub sethost {
                   5651:     my ($remotereq) = @_;
                   5652:     my (undef,$hostid)=split(/:/,$remotereq);
                   5653:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
                   5654:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200     matthew  5655: 	$currenthostid  =$hostid;
1.121     albertel 5656: 	$currentdomainid=$hostdom{$hostid};
                   5657: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
                   5658:     } else {
                   5659: 	&logthis("Requested host id $hostid not an alias of ".
                   5660: 		 $perlvar{'lonHostID'}." refusing connection");
                   5661: 	return 'unable_to_set';
                   5662:     }
                   5663:     return 'ok';
                   5664: }
                   5665: 
                   5666: sub version {
                   5667:     my ($userinput)=@_;
                   5668:     $remoteVERSION=(split(/:/,$userinput))[1];
                   5669:     return "version:$VERSION";
1.127     albertel 5670: }
1.178     foxr     5671: 
1.128     albertel 5672: #There is a copy of this in lonnet.pm
1.127     albertel 5673: sub userload {
                   5674:     my $numusers=0;
                   5675:     {
                   5676: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   5677: 	my $filename;
                   5678: 	my $curtime=time;
                   5679: 	while ($filename=readdir(LONIDS)) {
                   5680: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.138     albertel 5681: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159     albertel 5682: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.127     albertel 5683: 	}
                   5684: 	closedir(LONIDS);
                   5685:     }
                   5686:     my $userloadpercent=0;
                   5687:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   5688:     if ($maxuserload) {
1.129     albertel 5689: 	$userloadpercent=100*$numusers/$maxuserload;
1.127     albertel 5690:     }
1.130     albertel 5691:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127     albertel 5692:     return $userloadpercent;
1.91      albertel 5693: }
                   5694: 
1.205     raeburn  5695: # Routines for serializing arrays and hashes (copies from lonnet)
                   5696: 
                   5697: sub array2str {
                   5698:   my (@array) = @_;
                   5699:   my $result=&arrayref2str(\@array);
                   5700:   $result=~s/^__ARRAY_REF__//;
                   5701:   $result=~s/__END_ARRAY_REF__$//;
                   5702:   return $result;
                   5703: }
                   5704:                                                                                  
                   5705: sub arrayref2str {
                   5706:   my ($arrayref) = @_;
                   5707:   my $result='__ARRAY_REF__';
                   5708:   foreach my $elem (@$arrayref) {
                   5709:     if(ref($elem) eq 'ARRAY') {
                   5710:       $result.=&arrayref2str($elem).'&';
                   5711:     } elsif(ref($elem) eq 'HASH') {
                   5712:       $result.=&hashref2str($elem).'&';
                   5713:     } elsif(ref($elem)) {
                   5714:       #print("Got a ref of ".(ref($elem))." skipping.");
                   5715:     } else {
                   5716:       $result.=&escape($elem).'&';
                   5717:     }
                   5718:   }
                   5719:   $result=~s/\&$//;
                   5720:   $result .= '__END_ARRAY_REF__';
                   5721:   return $result;
                   5722: }
                   5723:                                                                                  
                   5724: sub hash2str {
                   5725:   my (%hash) = @_;
                   5726:   my $result=&hashref2str(\%hash);
                   5727:   $result=~s/^__HASH_REF__//;
                   5728:   $result=~s/__END_HASH_REF__$//;
                   5729:   return $result;
                   5730: }
                   5731:                                                                                  
                   5732: sub hashref2str {
                   5733:   my ($hashref)=@_;
                   5734:   my $result='__HASH_REF__';
                   5735:   foreach (sort(keys(%$hashref))) {
                   5736:     if (ref($_) eq 'ARRAY') {
                   5737:       $result.=&arrayref2str($_).'=';
                   5738:     } elsif (ref($_) eq 'HASH') {
                   5739:       $result.=&hashref2str($_).'=';
                   5740:     } elsif (ref($_)) {
                   5741:       $result.='=';
                   5742:       #print("Got a ref of ".(ref($_))." skipping.");
                   5743:     } else {
                   5744:         if ($_) {$result.=&escape($_).'=';} else { last; }
                   5745:     }
                   5746: 
                   5747:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   5748:       $result.=&arrayref2str($hashref->{$_}).'&';
                   5749:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   5750:       $result.=&hashref2str($hashref->{$_}).'&';
                   5751:     } elsif(ref($hashref->{$_})) {
                   5752:        $result.='&';
                   5753:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
                   5754:     } else {
                   5755:       $result.=&escape($hashref->{$_}).'&';
                   5756:     }
                   5757:   }
                   5758:   $result=~s/\&$//;
                   5759:   $result .= '__END_HASH_REF__';
                   5760:   return $result;
                   5761: }
1.200     matthew  5762: 
1.61      harris41 5763: # ----------------------------------- POD (plain old documentation, CPAN style)
                   5764: 
                   5765: =head1 NAME
                   5766: 
                   5767: lond - "LON Daemon" Server (port "LOND" 5663)
                   5768: 
                   5769: =head1 SYNOPSIS
                   5770: 
1.74      harris41 5771: Usage: B<lond>
                   5772: 
                   5773: Should only be run as user=www.  This is a command-line script which
                   5774: is invoked by B<loncron>.  There is no expectation that a typical user
                   5775: will manually start B<lond> from the command-line.  (In other words,
                   5776: DO NOT START B<lond> YOURSELF.)
1.61      harris41 5777: 
                   5778: =head1 DESCRIPTION
                   5779: 
1.74      harris41 5780: There are two characteristics associated with the running of B<lond>,
                   5781: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   5782: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   5783: subscriptions, etc).  These are described in two large
                   5784: sections below.
                   5785: 
                   5786: B<PROCESS MANAGEMENT>
                   5787: 
1.61      harris41 5788: Preforker - server who forks first. Runs as a daemon. HUPs.
                   5789: Uses IDEA encryption
                   5790: 
1.74      harris41 5791: B<lond> forks off children processes that correspond to the other servers
                   5792: in the network.  Management of these processes can be done at the
                   5793: parent process level or the child process level.
                   5794: 
                   5795: B<logs/lond.log> is the location of log messages.
                   5796: 
                   5797: The process management is now explained in terms of linux shell commands,
                   5798: subroutines internal to this code, and signal assignments:
                   5799: 
                   5800: =over 4
                   5801: 
                   5802: =item *
                   5803: 
                   5804: PID is stored in B<logs/lond.pid>
                   5805: 
                   5806: This is the process id number of the parent B<lond> process.
                   5807: 
                   5808: =item *
                   5809: 
                   5810: SIGTERM and SIGINT
                   5811: 
                   5812: Parent signal assignment:
                   5813:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   5814: 
                   5815: Child signal assignment:
                   5816:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   5817: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   5818:  to restart a new child.)
                   5819: 
                   5820: Command-line invocations:
                   5821:  B<kill> B<-s> SIGTERM I<PID>
                   5822:  B<kill> B<-s> SIGINT I<PID>
                   5823: 
                   5824: Subroutine B<HUNTSMAN>:
                   5825:  This is only invoked for the B<lond> parent I<PID>.
                   5826: This kills all the children, and then the parent.
                   5827: The B<lonc.pid> file is cleared.
                   5828: 
                   5829: =item *
                   5830: 
                   5831: SIGHUP
                   5832: 
                   5833: Current bug:
                   5834:  This signal can only be processed the first time
                   5835: on the parent process.  Subsequent SIGHUP signals
                   5836: have no effect.
                   5837: 
                   5838: Parent signal assignment:
                   5839:  $SIG{HUP}  = \&HUPSMAN;
                   5840: 
                   5841: Child signal assignment:
                   5842:  none (nothing happens)
                   5843: 
                   5844: Command-line invocations:
                   5845:  B<kill> B<-s> SIGHUP I<PID>
                   5846: 
                   5847: Subroutine B<HUPSMAN>:
                   5848:  This is only invoked for the B<lond> parent I<PID>,
                   5849: This kills all the children, and then the parent.
                   5850: The B<lond.pid> file is cleared.
                   5851: 
                   5852: =item *
                   5853: 
                   5854: SIGUSR1
                   5855: 
                   5856: Parent signal assignment:
                   5857:  $SIG{USR1} = \&USRMAN;
                   5858: 
                   5859: Child signal assignment:
                   5860:  $SIG{USR1}= \&logstatus;
                   5861: 
                   5862: Command-line invocations:
                   5863:  B<kill> B<-s> SIGUSR1 I<PID>
                   5864: 
                   5865: Subroutine B<USRMAN>:
                   5866:  When invoked for the B<lond> parent I<PID>,
                   5867: SIGUSR1 is sent to all the children, and the status of
                   5868: each connection is logged.
1.144     foxr     5869: 
                   5870: =item *
                   5871: 
                   5872: SIGUSR2
                   5873: 
                   5874: Parent Signal assignment:
                   5875:     $SIG{USR2} = \&UpdateHosts
                   5876: 
                   5877: Child signal assignment:
                   5878:     NONE
                   5879: 
1.74      harris41 5880: 
                   5881: =item *
                   5882: 
                   5883: SIGCHLD
                   5884: 
                   5885: Parent signal assignment:
                   5886:  $SIG{CHLD} = \&REAPER;
                   5887: 
                   5888: Child signal assignment:
                   5889:  none
                   5890: 
                   5891: Command-line invocations:
                   5892:  B<kill> B<-s> SIGCHLD I<PID>
                   5893: 
                   5894: Subroutine B<REAPER>:
                   5895:  This is only invoked for the B<lond> parent I<PID>.
                   5896: Information pertaining to the child is removed.
                   5897: The socket port is cleaned up.
                   5898: 
                   5899: =back
                   5900: 
                   5901: B<SERVER-SIDE ACTIVITIES>
                   5902: 
                   5903: Server-side information can be accepted in an encrypted or non-encrypted
                   5904: method.
                   5905: 
                   5906: =over 4
                   5907: 
                   5908: =item ping
                   5909: 
                   5910: Query a client in the hosts.tab table; "Are you there?"
                   5911: 
                   5912: =item pong
                   5913: 
                   5914: Respond to a ping query.
                   5915: 
                   5916: =item ekey
                   5917: 
                   5918: Read in encrypted key, make cipher.  Respond with a buildkey.
                   5919: 
                   5920: =item load
                   5921: 
                   5922: Respond with CPU load based on a computation upon /proc/loadavg.
                   5923: 
                   5924: =item currentauth
                   5925: 
                   5926: Reply with current authentication information (only over an
                   5927: encrypted channel).
                   5928: 
                   5929: =item auth
                   5930: 
                   5931: Only over an encrypted channel, reply as to whether a user's
                   5932: authentication information can be validated.
                   5933: 
                   5934: =item passwd
                   5935: 
                   5936: Allow for a password to be set.
                   5937: 
                   5938: =item makeuser
                   5939: 
                   5940: Make a user.
                   5941: 
                   5942: =item passwd
                   5943: 
                   5944: Allow for authentication mechanism and password to be changed.
                   5945: 
                   5946: =item home
1.61      harris41 5947: 
1.74      harris41 5948: Respond to a question "are you the home for a given user?"
                   5949: 
                   5950: =item update
                   5951: 
                   5952: Update contents of a subscribed resource.
                   5953: 
                   5954: =item unsubscribe
                   5955: 
                   5956: The server is unsubscribing from a resource.
                   5957: 
                   5958: =item subscribe
                   5959: 
                   5960: The server is subscribing to a resource.
                   5961: 
                   5962: =item log
                   5963: 
                   5964: Place in B<logs/lond.log>
                   5965: 
                   5966: =item put
                   5967: 
                   5968: stores hash in namespace
                   5969: 
1.230     foxr     5970: =item rolesputy
1.74      harris41 5971: 
                   5972: put a role into a user's environment
                   5973: 
                   5974: =item get
                   5975: 
                   5976: returns hash with keys from array
                   5977: reference filled in from namespace
                   5978: 
                   5979: =item eget
                   5980: 
                   5981: returns hash with keys from array
                   5982: reference filled in from namesp (encrypts the return communication)
                   5983: 
                   5984: =item rolesget
                   5985: 
                   5986: get a role from a user's environment
                   5987: 
                   5988: =item del
                   5989: 
                   5990: deletes keys out of array from namespace
                   5991: 
                   5992: =item keys
                   5993: 
                   5994: returns namespace keys
                   5995: 
                   5996: =item dump
                   5997: 
                   5998: dumps the complete (or key matching regexp) namespace into a hash
                   5999: 
                   6000: =item store
                   6001: 
                   6002: stores hash permanently
                   6003: for this url; hashref needs to be given and should be a \%hashname; the
                   6004: remaining args aren't required and if they aren't passed or are '' they will
                   6005: be derived from the ENV
                   6006: 
                   6007: =item restore
                   6008: 
                   6009: returns a hash for a given url
                   6010: 
                   6011: =item querysend
                   6012: 
                   6013: Tells client about the lonsql process that has been launched in response
                   6014: to a sent query.
                   6015: 
                   6016: =item queryreply
                   6017: 
                   6018: Accept information from lonsql and make appropriate storage in temporary
                   6019: file space.
                   6020: 
                   6021: =item idput
                   6022: 
                   6023: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   6024: for each student, defined perhaps by the institutional Registrar.)
                   6025: 
                   6026: =item idget
                   6027: 
                   6028: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   6029: for each student, defined perhaps by the institutional Registrar.)
                   6030: 
                   6031: =item tmpput
                   6032: 
                   6033: Accept and store information in temporary space.
                   6034: 
                   6035: =item tmpget
                   6036: 
                   6037: Send along temporarily stored information.
                   6038: 
                   6039: =item ls
                   6040: 
                   6041: List part of a user's directory.
                   6042: 
1.135     foxr     6043: =item pushtable
                   6044: 
                   6045: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   6046: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   6047: must be restored manually in case of a problem with the new table file.
                   6048: pushtable requires that the request be encrypted and validated via
                   6049: ValidateManager.  The form of the command is:
                   6050: enc:pushtable tablename <tablecontents> \n
                   6051: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   6052: cleartext newline.
                   6053: 
1.74      harris41 6054: =item Hanging up (exit or init)
                   6055: 
                   6056: What to do when a client tells the server that they (the client)
                   6057: are leaving the network.
                   6058: 
                   6059: =item unknown command
                   6060: 
                   6061: If B<lond> is sent an unknown command (not in the list above),
                   6062: it replys to the client "unknown_cmd".
1.135     foxr     6063: 
1.74      harris41 6064: 
                   6065: =item UNKNOWN CLIENT
                   6066: 
                   6067: If the anti-spoofing algorithm cannot verify the client,
                   6068: the client is rejected (with a "refused" message sent
                   6069: to the client, and the connection is closed.
                   6070: 
                   6071: =back
1.61      harris41 6072: 
                   6073: =head1 PREREQUISITES
                   6074: 
                   6075: IO::Socket
                   6076: IO::File
                   6077: Apache::File
                   6078: Symbol
                   6079: POSIX
                   6080: Crypt::IDEA
                   6081: LWP::UserAgent()
                   6082: GDBM_File
                   6083: Authen::Krb4
1.91      albertel 6084: Authen::Krb5
1.61      harris41 6085: 
                   6086: =head1 COREQUISITES
                   6087: 
                   6088: =head1 OSNAMES
                   6089: 
                   6090: linux
                   6091: 
                   6092: =head1 SCRIPT CATEGORIES
                   6093: 
                   6094: Server/Process
                   6095: 
                   6096: =cut

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