Annotation of loncom/lond, revision 1.289

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.289   ! albertel    5: # $Id: lond,v 1.288 2005/06/27 14:16:30 albertel 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.289   ! albertel   61: my $VERSION='$Revision: 1.288 $'; #' 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.289   ! albertel 5070: sub manage_permissions {
1.192     foxr     5071:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     5072: 
1.261     foxr     5073:     &Debug("manage_permissions: $request $domain $user $authtype");
                   5074: 
1.78      foxr     5075:     # See if the request is of the form /$domain/_au
1.289   ! albertel 5076:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.78      foxr     5077: 	my $execdir = $perlvar{'lonDaemons'};
                   5078: 	my $userhome= "/home/$user" ;
1.134     albertel 5079: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261     foxr     5080: 	&Debug("Setting homedir permissions for $userhome");
1.78      foxr     5081: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   5082:     }
                   5083: }
1.222     foxr     5084: 
                   5085: 
                   5086: #
                   5087: #  Return the full path of a user password file, whether it exists or not.
                   5088: # Parameters:
                   5089: #   domain     - Domain in which the password file lives.
                   5090: #   user       - name of the user.
                   5091: # Returns:
                   5092: #    Full passwd path:
                   5093: #
                   5094: sub password_path {
                   5095:     my ($domain, $user) = @_;
1.264     albertel 5096:     return &propath($domain, $user).'/passwd';
1.222     foxr     5097: }
                   5098: 
                   5099: #   Password Filename
                   5100: #   Returns the path to a passwd file given domain and user... only if
                   5101: #  it exists.
                   5102: # Parameters:
                   5103: #   domain    - Domain in which to search.
                   5104: #   user      - username.
                   5105: # Returns:
                   5106: #   - If the password file exists returns its path.
                   5107: #   - If the password file does not exist, returns undefined.
                   5108: #
                   5109: sub password_filename {
                   5110:     my ($domain, $user) = @_;
                   5111: 
                   5112:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   5113: 
                   5114:     my $path  = &password_path($domain, $user);
                   5115:     Debug("PasswordFilename got path: $path");
                   5116:     if(-e $path) {
                   5117: 	return $path;
                   5118:     } else {
                   5119: 	return undef;
                   5120:     }
                   5121: }
                   5122: 
                   5123: #
                   5124: #   Rewrite the contents of the user's passwd file.
                   5125: #  Parameters:
                   5126: #    domain    - domain of the user.
                   5127: #    name      - User's name.
                   5128: #    contents  - New contents of the file.
                   5129: # Returns:
                   5130: #   0    - Failed.
                   5131: #   1    - Success.
                   5132: #
                   5133: sub rewrite_password_file {
                   5134:     my ($domain, $user, $contents) = @_;
                   5135: 
                   5136:     my $file = &password_filename($domain, $user);
                   5137:     if (defined $file) {
                   5138: 	my $pf = IO::File->new(">$file");
                   5139: 	if($pf) {
                   5140: 	    print $pf "$contents\n";
                   5141: 	    return 1;
                   5142: 	} else {
                   5143: 	    return 0;
                   5144: 	}
                   5145:     } else {
                   5146: 	return 0;
                   5147:     }
                   5148: 
                   5149: }
                   5150: 
1.78      foxr     5151: #
1.222     foxr     5152: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     5153: 
                   5154: #     Returns the authorization type or nouser if there is no such user.
                   5155: #
1.222     foxr     5156: sub get_auth_type 
1.78      foxr     5157: {
1.192     foxr     5158: 
                   5159:     my ($domain, $user)  = @_;
1.78      foxr     5160: 
1.222     foxr     5161:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     5162:     my $proname    = &propath($domain, $user); 
                   5163:     my $passwdfile = "$proname/passwd";
                   5164:     if( -e $passwdfile ) {
                   5165: 	my $pf = IO::File->new($passwdfile);
                   5166: 	my $realpassword = <$pf>;
                   5167: 	chomp($realpassword);
1.79      foxr     5168: 	Debug("Password info = $realpassword\n");
1.78      foxr     5169: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     5170: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  5171: 	return "$authtype:$contentpwd";     
1.224     foxr     5172:     } else {
1.79      foxr     5173: 	Debug("Returning nouser");
1.78      foxr     5174: 	return "nouser";
                   5175:     }
1.1       albertel 5176: }
                   5177: 
1.220     foxr     5178: #
                   5179: #  Validate a user given their domain, name and password.  This utility
                   5180: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   5181: #  to validate the login credentials of a user.
                   5182: # Parameters:
                   5183: #    $domain    - The domain being logged into (this is required due to
                   5184: #                 the capability for multihomed systems.
                   5185: #    $user      - The name of the user being validated.
                   5186: #    $password  - The user's propoposed password.
                   5187: #
                   5188: # Returns:
                   5189: #     1        - The domain,user,pasword triplet corresponds to a valid
                   5190: #                user.
                   5191: #     0        - The domain,user,password triplet is not a valid user.
                   5192: #
                   5193: sub validate_user {
                   5194:     my ($domain, $user, $password) = @_;
                   5195: 
                   5196: 
                   5197:     # Why negative ~pi you may well ask?  Well this function is about
                   5198:     # authentication, and therefore very important to get right.
                   5199:     # I've initialized the flag that determines whether or not I've 
                   5200:     # validated correctly to a value it's not supposed to get.
                   5201:     # At the end of this function. I'll ensure that it's not still that
                   5202:     # value so we don't just wind up returning some accidental value
                   5203:     # as a result of executing an unforseen code path that
1.249     foxr     5204:     # did not set $validated.  At the end of valid execution paths,
                   5205:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     5206: 
                   5207:     my $validated = -3.14159;
                   5208: 
                   5209:     #  How we authenticate is determined by the type of authentication
                   5210:     #  the user has been assigned.  If the authentication type is
                   5211:     #  "nouser", the user does not exist so we will return 0.
                   5212: 
1.222     foxr     5213:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     5214:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   5215: 
                   5216:     my $null = pack("C",0);	# Used by kerberos auth types.
                   5217: 
                   5218:     if ($howpwd ne 'nouser') {
                   5219: 
                   5220: 	if($howpwd eq "internal") { # Encrypted is in local password file.
                   5221: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
                   5222: 	}
                   5223: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   5224: 	    $contentpwd = (getpwnam($user))[1];
                   5225: 	    if($contentpwd) {
                   5226: 		if($contentpwd eq 'x') { # Shadow password file...
                   5227: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   5228: 		    open PWAUTH,  "|$pwauth_path" or
                   5229: 			die "Cannot invoke authentication";
                   5230: 		    print PWAUTH "$user\n$password\n";
                   5231: 		    close PWAUTH;
                   5232: 		    $validated = ! $?;
                   5233: 
                   5234: 		} else { 	         # Passwords in /etc/passwd. 
                   5235: 		    $validated = (crypt($password,
                   5236: 					$contentpwd) eq $contentpwd);
                   5237: 		}
                   5238: 	    } else {
                   5239: 		$validated = 0;
                   5240: 	    }
                   5241: 	}
                   5242: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   5243: 	    if(! ($password =~ /$null/) ) {
                   5244: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   5245: 							   "",
                   5246: 							   $contentpwd,,
                   5247: 							   'krbtgt',
                   5248: 							   $contentpwd,
                   5249: 							   1,
                   5250: 							   $password);
                   5251: 		if(!$k4error) {
                   5252: 		    $validated = 1;
1.224     foxr     5253: 		} else {
1.220     foxr     5254: 		    $validated = 0;
                   5255: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   5256: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   5257: 		}
1.224     foxr     5258: 	    } else {
1.220     foxr     5259: 		$validated = 0; # Password has a match with null.
                   5260: 	    }
1.224     foxr     5261: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220     foxr     5262: 	    if(!($password =~ /$null/)) { # Null password not allowed.
                   5263: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   5264: 							  .$contentpwd);
                   5265: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   5266: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   5267: 		my $credentials= &Authen::Krb5::cc_default();
                   5268: 		$credentials->initialize($krbclient);
1.270     matthew  5269: 		my $krbreturn  = &Authen::Krb5::get_in_tkt_with_password($krbclient,
1.220     foxr     5270: 									 $krbserver,
                   5271: 									 $password,
                   5272: 									 $credentials);
                   5273: 		$validated = ($krbreturn == 1);
1.224     foxr     5274: 	    } else {
1.220     foxr     5275: 		$validated = 0;
                   5276: 	    }
1.224     foxr     5277: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     5278: 	    #  Authenticate via installation specific authentcation method:
                   5279: 	    $validated = &localauth::localauth($user, 
                   5280: 					       $password, 
                   5281: 					       $contentpwd);
1.224     foxr     5282: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     5283: 	    $validated = 0;
                   5284: 	}
                   5285:     } else {
                   5286: 	$validated = 0;
                   5287:     }
                   5288:     #
                   5289:     #  $validated has the correct stat of the authentication:
                   5290:     #
                   5291: 
                   5292:     unless ($validated != -3.14159) {
1.249     foxr     5293: 	#  I >really really< want to know if this happens.
                   5294: 	#  since it indicates that user authentication is badly
                   5295: 	#  broken in some code path.
                   5296:         #
                   5297: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     5298:     }
                   5299:     return $validated;
                   5300: }
                   5301: 
                   5302: 
1.84      albertel 5303: sub addline {
                   5304:     my ($fname,$hostid,$ip,$newline)=@_;
                   5305:     my $contents;
                   5306:     my $found=0;
                   5307:     my $expr='^'.$hostid.':'.$ip.':';
                   5308:     $expr =~ s/\./\\\./g;
1.134     albertel 5309:     my $sh;
1.84      albertel 5310:     if ($sh=IO::File->new("$fname.subscription")) {
                   5311: 	while (my $subline=<$sh>) {
                   5312: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   5313: 	}
                   5314: 	$sh->close();
                   5315:     }
                   5316:     $sh=IO::File->new(">$fname.subscription");
                   5317:     if ($contents) { print $sh $contents; }
                   5318:     if ($newline) { print $sh $newline; }
                   5319:     $sh->close();
                   5320:     return $found;
1.86      www      5321: }
                   5322: 
1.234     foxr     5323: sub get_chat {
1.122     www      5324:     my ($cdom,$cname,$udom,$uname)=@_;
1.87      www      5325:     my %hash;
                   5326:     my $proname=&propath($cdom,$cname);
                   5327:     my @entries=();
1.88      albertel 5328:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   5329: 	    &GDBM_READER(),0640)) {
                   5330: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   5331: 	untie %hash;
1.123     www      5332:     }
1.124     www      5333:     my @participants=();
1.134     albertel 5334:     my $cutoff=time-60;
1.123     www      5335:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124     www      5336: 	    &GDBM_WRCREAT(),0640)) {
                   5337:         $hash{$uname.':'.$udom}=time;
1.123     www      5338:         foreach (sort keys %hash) {
                   5339: 	    if ($hash{$_}>$cutoff) {
1.124     www      5340: 		$participants[$#participants+1]='active_participant:'.$_;
1.123     www      5341:             }
                   5342:         }
                   5343:         untie %hash;
1.86      www      5344:     }
1.124     www      5345:     return (@participants,@entries);
1.86      www      5346: }
                   5347: 
1.234     foxr     5348: sub chat_add {
1.88      albertel 5349:     my ($cdom,$cname,$newchat)=@_;
                   5350:     my %hash;
                   5351:     my $proname=&propath($cdom,$cname);
                   5352:     my @entries=();
1.142     www      5353:     my $time=time;
1.88      albertel 5354:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   5355: 	    &GDBM_WRCREAT(),0640)) {
                   5356: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   5357: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   5358: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   5359: 	my $newid=$time.'_000000';
                   5360: 	if ($thentime==$time) {
                   5361: 	    $idnum=~s/^0+//;
                   5362: 	    $idnum++;
                   5363: 	    $idnum=substr('000000'.$idnum,-6,6);
                   5364: 	    $newid=$time.'_'.$idnum;
                   5365: 	}
                   5366: 	$hash{$newid}=$newchat;
                   5367: 	my $expired=$time-3600;
                   5368: 	foreach (keys %hash) {
                   5369: 	    my ($thistime)=($_=~/(\d+)\_/);
                   5370: 	    if ($thistime<$expired) {
1.89      www      5371: 		delete $hash{$_};
1.88      albertel 5372: 	    }
                   5373: 	}
                   5374: 	untie %hash;
1.142     www      5375:     }
                   5376:     {
                   5377: 	my $hfh;
                   5378: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
                   5379: 	    print $hfh "$time:".&unescape($newchat)."\n";
                   5380: 	}
1.86      www      5381:     }
1.84      albertel 5382: }
                   5383: 
                   5384: sub unsub {
                   5385:     my ($fname,$clientip)=@_;
                   5386:     my $result;
1.188     foxr     5387:     my $unsubs = 0;		# Number of successful unsubscribes:
                   5388: 
                   5389: 
                   5390:     # An old way subscriptions were handled was to have a 
                   5391:     # subscription marker file:
                   5392: 
                   5393:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     5394:     if (unlink("$fname.$clientname")) {
1.188     foxr     5395: 	$unsubs++;		# Successful unsub via marker file.
                   5396:     } 
                   5397: 
                   5398:     # The more modern way to do it is to have a subscription list
                   5399:     # file:
                   5400: 
1.84      albertel 5401:     if (-e "$fname.subscription") {
1.161     foxr     5402: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     5403: 	if ($found) { 
                   5404: 	    $unsubs++;
                   5405: 	}
                   5406:     } 
                   5407: 
                   5408:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   5409:     #  resource we can return ok:
                   5410: 
                   5411:     if($unsubs) {
                   5412: 	$result = "ok\n";
1.84      albertel 5413:     } else {
1.188     foxr     5414: 	$result = "not_subscribed\n";
1.84      albertel 5415:     }
1.188     foxr     5416: 
1.84      albertel 5417:     return $result;
                   5418: }
                   5419: 
1.101     www      5420: sub currentversion {
                   5421:     my $fname=shift;
                   5422:     my $version=-1;
                   5423:     my $ulsdir='';
                   5424:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   5425:        $ulsdir=$1;
                   5426:     }
1.114     albertel 5427:     my ($fnamere1,$fnamere2);
                   5428:     # remove version if already specified
1.101     www      5429:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 5430:     # get the bits that go before and after the version number
                   5431:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   5432: 	$fnamere1=$1;
                   5433: 	$fnamere2='.'.$2;
                   5434:     }
1.101     www      5435:     if (-e $fname) { $version=1; }
                   5436:     if (-e $ulsdir) {
1.134     albertel 5437: 	if(-d $ulsdir) {
                   5438: 	    if (opendir(LSDIR,$ulsdir)) {
                   5439: 		my $ulsfn;
                   5440: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      5441: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 5442: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   5443: 		    unless (-l $thisfile) {
1.160     www      5444: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 5445: 			    if ($1>$version) { $version=$1; }
                   5446: 			}
                   5447: 		    }
                   5448: 		}
                   5449: 		closedir(LSDIR);
                   5450: 		$version++;
                   5451: 	    }
                   5452: 	}
                   5453:     }
                   5454:     return $version;
1.101     www      5455: }
                   5456: 
                   5457: sub thisversion {
                   5458:     my $fname=shift;
                   5459:     my $version=-1;
                   5460:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   5461: 	$version=$1;
                   5462:     }
                   5463:     return $version;
                   5464: }
                   5465: 
1.84      albertel 5466: sub subscribe {
                   5467:     my ($userinput,$clientip)=@_;
                   5468:     my $result;
                   5469:     my ($cmd,$fname)=split(/:/,$userinput);
                   5470:     my $ownership=&ishome($fname);
                   5471:     if ($ownership eq 'owner') {
1.101     www      5472: # explitly asking for the current version?
                   5473:         unless (-e $fname) {
                   5474:             my $currentversion=&currentversion($fname);
                   5475: 	    if (&thisversion($fname)==$currentversion) {
                   5476:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   5477: 		    my $root=$1;
                   5478:                     my $extension=$2;
                   5479:                     symlink($root.'.'.$extension,
                   5480:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      5481:                     unless ($extension=~/\.meta$/) {
                   5482:                        symlink($root.'.'.$extension.'.meta',
                   5483:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   5484: 		    }
1.101     www      5485:                 }
                   5486:             }
                   5487:         }
1.84      albertel 5488: 	if (-e $fname) {
                   5489: 	    if (-d $fname) {
                   5490: 		$result="directory\n";
                   5491: 	    } else {
1.161     foxr     5492: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 5493: 		my $now=time;
1.161     foxr     5494: 		my $found=&addline($fname,$clientname,$clientip,
                   5495: 				   "$clientname:$clientip:$now\n");
1.84      albertel 5496: 		if ($found) { $result="$fname\n"; }
                   5497: 		# if they were subscribed to only meta data, delete that
                   5498:                 # subscription, when you subscribe to a file you also get
                   5499:                 # the metadata
                   5500: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   5501: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
                   5502: 		$fname="http://$thisserver/".$fname;
                   5503: 		$result="$fname\n";
                   5504: 	    }
                   5505: 	} else {
                   5506: 	    $result="not_found\n";
                   5507: 	}
                   5508:     } else {
                   5509: 	$result="rejected\n";
                   5510:     }
                   5511:     return $result;
                   5512: }
1.287     foxr     5513: #  Change the passwd of a unix user.  The caller must have
                   5514: #  first verified that the user is a loncapa user.
                   5515: #
                   5516: # Parameters:
                   5517: #    user      - Unix user name to change.
                   5518: #    pass      - New password for the user.
                   5519: # Returns:
                   5520: #    ok    - if success
                   5521: #    other - Some meaningfule error message string.
                   5522: # NOTE:
                   5523: #    invokes a setuid script to change the passwd.
                   5524: sub change_unix_password {
                   5525:     my ($user, $pass) = @_;
                   5526: 
                   5527:     &Debug("change_unix_password");
                   5528:     my $execdir=$perlvar{'lonDaemons'};
                   5529:     &Debug("Opening lcpasswd pipeline");
                   5530:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   5531: 			   ."$perlvar{'lonDaemons'}"
                   5532: 			   ."/logs/lcpasswd.log");
                   5533:     print $pf "$user\n$pass\n$pass\n";
                   5534:     close $pf;
                   5535:     my $err = $?;
                   5536:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   5537: 	"pwchange_falure - unknown error";
                   5538: 
                   5539:     
                   5540: }
                   5541: 
1.91      albertel 5542: 
                   5543: sub make_passwd_file {
1.98      foxr     5544:     my ($uname, $umode,$npass,$passfilename)=@_;
1.91      albertel 5545:     my $result="ok\n";
                   5546:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   5547: 	{
                   5548: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5549: 	    if ($pf) {
                   5550: 		print $pf "$umode:$npass\n";
                   5551: 	    } else {
                   5552: 		$result = "pass_file_failed_error";
                   5553: 	    }
1.91      albertel 5554: 	}
                   5555:     } elsif ($umode eq 'internal') {
                   5556: 	my $salt=time;
                   5557: 	$salt=substr($salt,6,2);
                   5558: 	my $ncpass=crypt($npass,$salt);
                   5559: 	{
                   5560: 	    &Debug("Creating internal auth");
                   5561: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5562: 	    if($pf) {
                   5563: 		print $pf "internal:$ncpass\n"; 
                   5564: 	    } else {
                   5565: 		$result = "pass_file_failed_error";
                   5566: 	    }
1.91      albertel 5567: 	}
                   5568:     } elsif ($umode eq 'localauth') {
                   5569: 	{
                   5570: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5571: 	    if($pf) {
                   5572: 		print $pf "localauth:$npass\n";
                   5573: 	    } else {
                   5574: 		$result = "pass_file_failed_error";
                   5575: 	    }
1.91      albertel 5576: 	}
                   5577:     } elsif ($umode eq 'unix') {
                   5578: 	{
1.186     foxr     5579: 	    #
                   5580: 	    #  Don't allow the creation of privileged accounts!!! that would
                   5581: 	    #  be real bad!!!
                   5582: 	    #
                   5583: 	    my $uid = getpwnam($uname);
                   5584: 	    if((defined $uid) && ($uid == 0)) {
                   5585: 		&logthis(">>>Attempted to create privilged account blocked");
                   5586: 		return "no_priv_account_error\n";
                   5587: 	    }
                   5588: 
1.223     foxr     5589: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224     foxr     5590: 
                   5591: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
1.91      albertel 5592: 	    {
                   5593: 		&Debug("Executing external: ".$execpath);
1.98      foxr     5594: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  5595: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 5596: 		print $se "$uname\n";
                   5597: 		print $se "$npass\n";
                   5598: 		print $se "$npass\n";
1.223     foxr     5599: 		print $se "$lc_error_file\n"; # Status -> unique file.
1.97      foxr     5600: 	    }
1.285     foxr     5601: 	    if (-r $lc_error_file) {
                   5602: 		&Debug("Opening error file: $lc_error_file");
                   5603: 		my $error = IO::File->new("< $lc_error_file");
                   5604: 		my $useraddok = <$error>;
                   5605: 		$error->close;
                   5606: 		unlink($lc_error_file);
                   5607: 		
                   5608: 		chomp $useraddok;
                   5609: 	
                   5610: 		if($useraddok > 0) {
                   5611: 		    my $error_text = &lcuseraddstrerror($useraddok);
                   5612: 		    &logthis("Failed lcuseradd: $error_text");
                   5613: 		    $result = "lcuseradd_failed:$error_text\n";
                   5614: 		}  else {
                   5615: 		    my $pf = IO::File->new(">$passfilename");
                   5616: 		    if($pf) {
                   5617: 			print $pf "unix:\n";
                   5618: 		    } else {
                   5619: 			$result = "pass_file_failed_error";
                   5620: 		    }
                   5621: 		}
1.224     foxr     5622: 	    }  else {
1.285     foxr     5623: 		&Debug("Could not locate lcuseradd error: $lc_error_file");
                   5624: 		$result="bug_lcuseradd_no_output_file";
1.91      albertel 5625: 	    }
                   5626: 	}
                   5627:     } elsif ($umode eq 'none') {
                   5628: 	{
1.223     foxr     5629: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     5630: 	    if($pf) {
                   5631: 		print $pf "none:\n";
                   5632: 	    } else {
                   5633: 		$result = "pass_file_failed_error";
                   5634: 	    }
1.91      albertel 5635: 	}
                   5636:     } else {
                   5637: 	$result="auth_mode_error\n";
                   5638:     }
                   5639:     return $result;
1.121     albertel 5640: }
                   5641: 
1.265     albertel 5642: sub convert_photo {
                   5643:     my ($start,$dest)=@_;
                   5644:     system("convert $start $dest");
                   5645: }
                   5646: 
1.121     albertel 5647: sub sethost {
                   5648:     my ($remotereq) = @_;
                   5649:     my (undef,$hostid)=split(/:/,$remotereq);
                   5650:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
                   5651:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200     matthew  5652: 	$currenthostid  =$hostid;
1.121     albertel 5653: 	$currentdomainid=$hostdom{$hostid};
                   5654: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
                   5655:     } else {
                   5656: 	&logthis("Requested host id $hostid not an alias of ".
                   5657: 		 $perlvar{'lonHostID'}." refusing connection");
                   5658: 	return 'unable_to_set';
                   5659:     }
                   5660:     return 'ok';
                   5661: }
                   5662: 
                   5663: sub version {
                   5664:     my ($userinput)=@_;
                   5665:     $remoteVERSION=(split(/:/,$userinput))[1];
                   5666:     return "version:$VERSION";
1.127     albertel 5667: }
1.178     foxr     5668: 
1.128     albertel 5669: #There is a copy of this in lonnet.pm
1.127     albertel 5670: sub userload {
                   5671:     my $numusers=0;
                   5672:     {
                   5673: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   5674: 	my $filename;
                   5675: 	my $curtime=time;
                   5676: 	while ($filename=readdir(LONIDS)) {
                   5677: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.138     albertel 5678: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159     albertel 5679: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.127     albertel 5680: 	}
                   5681: 	closedir(LONIDS);
                   5682:     }
                   5683:     my $userloadpercent=0;
                   5684:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   5685:     if ($maxuserload) {
1.129     albertel 5686: 	$userloadpercent=100*$numusers/$maxuserload;
1.127     albertel 5687:     }
1.130     albertel 5688:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127     albertel 5689:     return $userloadpercent;
1.91      albertel 5690: }
                   5691: 
1.205     raeburn  5692: # Routines for serializing arrays and hashes (copies from lonnet)
                   5693: 
                   5694: sub array2str {
                   5695:   my (@array) = @_;
                   5696:   my $result=&arrayref2str(\@array);
                   5697:   $result=~s/^__ARRAY_REF__//;
                   5698:   $result=~s/__END_ARRAY_REF__$//;
                   5699:   return $result;
                   5700: }
                   5701:                                                                                  
                   5702: sub arrayref2str {
                   5703:   my ($arrayref) = @_;
                   5704:   my $result='__ARRAY_REF__';
                   5705:   foreach my $elem (@$arrayref) {
                   5706:     if(ref($elem) eq 'ARRAY') {
                   5707:       $result.=&arrayref2str($elem).'&';
                   5708:     } elsif(ref($elem) eq 'HASH') {
                   5709:       $result.=&hashref2str($elem).'&';
                   5710:     } elsif(ref($elem)) {
                   5711:       #print("Got a ref of ".(ref($elem))." skipping.");
                   5712:     } else {
                   5713:       $result.=&escape($elem).'&';
                   5714:     }
                   5715:   }
                   5716:   $result=~s/\&$//;
                   5717:   $result .= '__END_ARRAY_REF__';
                   5718:   return $result;
                   5719: }
                   5720:                                                                                  
                   5721: sub hash2str {
                   5722:   my (%hash) = @_;
                   5723:   my $result=&hashref2str(\%hash);
                   5724:   $result=~s/^__HASH_REF__//;
                   5725:   $result=~s/__END_HASH_REF__$//;
                   5726:   return $result;
                   5727: }
                   5728:                                                                                  
                   5729: sub hashref2str {
                   5730:   my ($hashref)=@_;
                   5731:   my $result='__HASH_REF__';
                   5732:   foreach (sort(keys(%$hashref))) {
                   5733:     if (ref($_) eq 'ARRAY') {
                   5734:       $result.=&arrayref2str($_).'=';
                   5735:     } elsif (ref($_) eq 'HASH') {
                   5736:       $result.=&hashref2str($_).'=';
                   5737:     } elsif (ref($_)) {
                   5738:       $result.='=';
                   5739:       #print("Got a ref of ".(ref($_))." skipping.");
                   5740:     } else {
                   5741:         if ($_) {$result.=&escape($_).'=';} else { last; }
                   5742:     }
                   5743: 
                   5744:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   5745:       $result.=&arrayref2str($hashref->{$_}).'&';
                   5746:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   5747:       $result.=&hashref2str($hashref->{$_}).'&';
                   5748:     } elsif(ref($hashref->{$_})) {
                   5749:        $result.='&';
                   5750:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
                   5751:     } else {
                   5752:       $result.=&escape($hashref->{$_}).'&';
                   5753:     }
                   5754:   }
                   5755:   $result=~s/\&$//;
                   5756:   $result .= '__END_HASH_REF__';
                   5757:   return $result;
                   5758: }
1.200     matthew  5759: 
1.61      harris41 5760: # ----------------------------------- POD (plain old documentation, CPAN style)
                   5761: 
                   5762: =head1 NAME
                   5763: 
                   5764: lond - "LON Daemon" Server (port "LOND" 5663)
                   5765: 
                   5766: =head1 SYNOPSIS
                   5767: 
1.74      harris41 5768: Usage: B<lond>
                   5769: 
                   5770: Should only be run as user=www.  This is a command-line script which
                   5771: is invoked by B<loncron>.  There is no expectation that a typical user
                   5772: will manually start B<lond> from the command-line.  (In other words,
                   5773: DO NOT START B<lond> YOURSELF.)
1.61      harris41 5774: 
                   5775: =head1 DESCRIPTION
                   5776: 
1.74      harris41 5777: There are two characteristics associated with the running of B<lond>,
                   5778: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   5779: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   5780: subscriptions, etc).  These are described in two large
                   5781: sections below.
                   5782: 
                   5783: B<PROCESS MANAGEMENT>
                   5784: 
1.61      harris41 5785: Preforker - server who forks first. Runs as a daemon. HUPs.
                   5786: Uses IDEA encryption
                   5787: 
1.74      harris41 5788: B<lond> forks off children processes that correspond to the other servers
                   5789: in the network.  Management of these processes can be done at the
                   5790: parent process level or the child process level.
                   5791: 
                   5792: B<logs/lond.log> is the location of log messages.
                   5793: 
                   5794: The process management is now explained in terms of linux shell commands,
                   5795: subroutines internal to this code, and signal assignments:
                   5796: 
                   5797: =over 4
                   5798: 
                   5799: =item *
                   5800: 
                   5801: PID is stored in B<logs/lond.pid>
                   5802: 
                   5803: This is the process id number of the parent B<lond> process.
                   5804: 
                   5805: =item *
                   5806: 
                   5807: SIGTERM and SIGINT
                   5808: 
                   5809: Parent signal assignment:
                   5810:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   5811: 
                   5812: Child signal assignment:
                   5813:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   5814: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   5815:  to restart a new child.)
                   5816: 
                   5817: Command-line invocations:
                   5818:  B<kill> B<-s> SIGTERM I<PID>
                   5819:  B<kill> B<-s> SIGINT I<PID>
                   5820: 
                   5821: Subroutine B<HUNTSMAN>:
                   5822:  This is only invoked for the B<lond> parent I<PID>.
                   5823: This kills all the children, and then the parent.
                   5824: The B<lonc.pid> file is cleared.
                   5825: 
                   5826: =item *
                   5827: 
                   5828: SIGHUP
                   5829: 
                   5830: Current bug:
                   5831:  This signal can only be processed the first time
                   5832: on the parent process.  Subsequent SIGHUP signals
                   5833: have no effect.
                   5834: 
                   5835: Parent signal assignment:
                   5836:  $SIG{HUP}  = \&HUPSMAN;
                   5837: 
                   5838: Child signal assignment:
                   5839:  none (nothing happens)
                   5840: 
                   5841: Command-line invocations:
                   5842:  B<kill> B<-s> SIGHUP I<PID>
                   5843: 
                   5844: Subroutine B<HUPSMAN>:
                   5845:  This is only invoked for the B<lond> parent I<PID>,
                   5846: This kills all the children, and then the parent.
                   5847: The B<lond.pid> file is cleared.
                   5848: 
                   5849: =item *
                   5850: 
                   5851: SIGUSR1
                   5852: 
                   5853: Parent signal assignment:
                   5854:  $SIG{USR1} = \&USRMAN;
                   5855: 
                   5856: Child signal assignment:
                   5857:  $SIG{USR1}= \&logstatus;
                   5858: 
                   5859: Command-line invocations:
                   5860:  B<kill> B<-s> SIGUSR1 I<PID>
                   5861: 
                   5862: Subroutine B<USRMAN>:
                   5863:  When invoked for the B<lond> parent I<PID>,
                   5864: SIGUSR1 is sent to all the children, and the status of
                   5865: each connection is logged.
1.144     foxr     5866: 
                   5867: =item *
                   5868: 
                   5869: SIGUSR2
                   5870: 
                   5871: Parent Signal assignment:
                   5872:     $SIG{USR2} = \&UpdateHosts
                   5873: 
                   5874: Child signal assignment:
                   5875:     NONE
                   5876: 
1.74      harris41 5877: 
                   5878: =item *
                   5879: 
                   5880: SIGCHLD
                   5881: 
                   5882: Parent signal assignment:
                   5883:  $SIG{CHLD} = \&REAPER;
                   5884: 
                   5885: Child signal assignment:
                   5886:  none
                   5887: 
                   5888: Command-line invocations:
                   5889:  B<kill> B<-s> SIGCHLD I<PID>
                   5890: 
                   5891: Subroutine B<REAPER>:
                   5892:  This is only invoked for the B<lond> parent I<PID>.
                   5893: Information pertaining to the child is removed.
                   5894: The socket port is cleaned up.
                   5895: 
                   5896: =back
                   5897: 
                   5898: B<SERVER-SIDE ACTIVITIES>
                   5899: 
                   5900: Server-side information can be accepted in an encrypted or non-encrypted
                   5901: method.
                   5902: 
                   5903: =over 4
                   5904: 
                   5905: =item ping
                   5906: 
                   5907: Query a client in the hosts.tab table; "Are you there?"
                   5908: 
                   5909: =item pong
                   5910: 
                   5911: Respond to a ping query.
                   5912: 
                   5913: =item ekey
                   5914: 
                   5915: Read in encrypted key, make cipher.  Respond with a buildkey.
                   5916: 
                   5917: =item load
                   5918: 
                   5919: Respond with CPU load based on a computation upon /proc/loadavg.
                   5920: 
                   5921: =item currentauth
                   5922: 
                   5923: Reply with current authentication information (only over an
                   5924: encrypted channel).
                   5925: 
                   5926: =item auth
                   5927: 
                   5928: Only over an encrypted channel, reply as to whether a user's
                   5929: authentication information can be validated.
                   5930: 
                   5931: =item passwd
                   5932: 
                   5933: Allow for a password to be set.
                   5934: 
                   5935: =item makeuser
                   5936: 
                   5937: Make a user.
                   5938: 
                   5939: =item passwd
                   5940: 
                   5941: Allow for authentication mechanism and password to be changed.
                   5942: 
                   5943: =item home
1.61      harris41 5944: 
1.74      harris41 5945: Respond to a question "are you the home for a given user?"
                   5946: 
                   5947: =item update
                   5948: 
                   5949: Update contents of a subscribed resource.
                   5950: 
                   5951: =item unsubscribe
                   5952: 
                   5953: The server is unsubscribing from a resource.
                   5954: 
                   5955: =item subscribe
                   5956: 
                   5957: The server is subscribing to a resource.
                   5958: 
                   5959: =item log
                   5960: 
                   5961: Place in B<logs/lond.log>
                   5962: 
                   5963: =item put
                   5964: 
                   5965: stores hash in namespace
                   5966: 
1.230     foxr     5967: =item rolesputy
1.74      harris41 5968: 
                   5969: put a role into a user's environment
                   5970: 
                   5971: =item get
                   5972: 
                   5973: returns hash with keys from array
                   5974: reference filled in from namespace
                   5975: 
                   5976: =item eget
                   5977: 
                   5978: returns hash with keys from array
                   5979: reference filled in from namesp (encrypts the return communication)
                   5980: 
                   5981: =item rolesget
                   5982: 
                   5983: get a role from a user's environment
                   5984: 
                   5985: =item del
                   5986: 
                   5987: deletes keys out of array from namespace
                   5988: 
                   5989: =item keys
                   5990: 
                   5991: returns namespace keys
                   5992: 
                   5993: =item dump
                   5994: 
                   5995: dumps the complete (or key matching regexp) namespace into a hash
                   5996: 
                   5997: =item store
                   5998: 
                   5999: stores hash permanently
                   6000: for this url; hashref needs to be given and should be a \%hashname; the
                   6001: remaining args aren't required and if they aren't passed or are '' they will
                   6002: be derived from the ENV
                   6003: 
                   6004: =item restore
                   6005: 
                   6006: returns a hash for a given url
                   6007: 
                   6008: =item querysend
                   6009: 
                   6010: Tells client about the lonsql process that has been launched in response
                   6011: to a sent query.
                   6012: 
                   6013: =item queryreply
                   6014: 
                   6015: Accept information from lonsql and make appropriate storage in temporary
                   6016: file space.
                   6017: 
                   6018: =item idput
                   6019: 
                   6020: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   6021: for each student, defined perhaps by the institutional Registrar.)
                   6022: 
                   6023: =item idget
                   6024: 
                   6025: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   6026: for each student, defined perhaps by the institutional Registrar.)
                   6027: 
                   6028: =item tmpput
                   6029: 
                   6030: Accept and store information in temporary space.
                   6031: 
                   6032: =item tmpget
                   6033: 
                   6034: Send along temporarily stored information.
                   6035: 
                   6036: =item ls
                   6037: 
                   6038: List part of a user's directory.
                   6039: 
1.135     foxr     6040: =item pushtable
                   6041: 
                   6042: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   6043: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   6044: must be restored manually in case of a problem with the new table file.
                   6045: pushtable requires that the request be encrypted and validated via
                   6046: ValidateManager.  The form of the command is:
                   6047: enc:pushtable tablename <tablecontents> \n
                   6048: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   6049: cleartext newline.
                   6050: 
1.74      harris41 6051: =item Hanging up (exit or init)
                   6052: 
                   6053: What to do when a client tells the server that they (the client)
                   6054: are leaving the network.
                   6055: 
                   6056: =item unknown command
                   6057: 
                   6058: If B<lond> is sent an unknown command (not in the list above),
                   6059: it replys to the client "unknown_cmd".
1.135     foxr     6060: 
1.74      harris41 6061: 
                   6062: =item UNKNOWN CLIENT
                   6063: 
                   6064: If the anti-spoofing algorithm cannot verify the client,
                   6065: the client is rejected (with a "refused" message sent
                   6066: to the client, and the connection is closed.
                   6067: 
                   6068: =back
1.61      harris41 6069: 
                   6070: =head1 PREREQUISITES
                   6071: 
                   6072: IO::Socket
                   6073: IO::File
                   6074: Apache::File
                   6075: Symbol
                   6076: POSIX
                   6077: Crypt::IDEA
                   6078: LWP::UserAgent()
                   6079: GDBM_File
                   6080: Authen::Krb4
1.91      albertel 6081: Authen::Krb5
1.61      harris41 6082: 
                   6083: =head1 COREQUISITES
                   6084: 
                   6085: =head1 OSNAMES
                   6086: 
                   6087: linux
                   6088: 
                   6089: =head1 SCRIPT CATEGORIES
                   6090: 
                   6091: Server/Process
                   6092: 
                   6093: =cut

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