Annotation of loncom/lond, revision 1.276

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

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