Annotation of loncom/lond, revision 1.273

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.273   ! albertel    5: # $Id: lond,v 1.272 2005/01/01 02:31:05 raeburn 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.273   ! albertel   61: my $VERSION='$Revision: 1.272 $'; #' 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: 
                   1802: 	    if( ($oldauth =~ /^unix/) && ($umode eq "internal")) { # unix -> internal
                   1803: 		if(&is_author($udom, $uname)) {
                   1804: 		    &Debug(" Need to manage author permissions...");
                   1805: 		    &manage_permissions("/$udom/_au", $udom, $uname, "internal:");
                   1806: 		}
                   1807: 	    }
                   1808: 	       
                   1809: 
1.225     foxr     1810: 	    &Reply($client, $result, $userinput);
                   1811: 	} else {	       
1.251     foxr     1812: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     1813: 	}
                   1814:     }
                   1815:     return 1;
                   1816: }
                   1817: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   1818: 
                   1819: #
                   1820: #   Determines if this is the home server for a user.  The home server
                   1821: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   1822: #   to do is determine if this file exists.
                   1823: #
                   1824: # Parameters:
                   1825: #    $cmd      - The command that got us here.
                   1826: #    $tail     - Tail of the command (remaining parameters).
                   1827: #    $client   - File descriptor connected to client.
                   1828: # Returns
                   1829: #     0        - Requested to exit, caller should shut down.
                   1830: #     1        - Continue processing.
                   1831: # Implicit inputs:
                   1832: #    The authentication systems describe above have their own forms of implicit
                   1833: #    input into the authentication process that are described above.
                   1834: #
                   1835: sub is_home_handler {
                   1836:     my ($cmd, $tail, $client) = @_;
                   1837:    
                   1838:     my $userinput  = "$cmd:$tail";
                   1839:    
                   1840:     my ($udom,$uname)=split(/:/,$tail);
                   1841:     chomp($uname);
                   1842:     my $passfile = &password_filename($udom, $uname);
                   1843:     if($passfile) {
                   1844: 	&Reply( $client, "found\n", $userinput);
                   1845:     } else {
                   1846: 	&Failure($client, "not_found\n", $userinput);
                   1847:     }
                   1848:     return 1;
                   1849: }
                   1850: &register_handler("home", \&is_home_handler, 0,1,0);
                   1851: 
                   1852: #
                   1853: #   Process an update request for a resource?? I think what's going on here is
                   1854: #   that a resource has been modified that we hold a subscription to.
                   1855: #   If the resource is not local, then we must update, or at least invalidate our
                   1856: #   cached copy of the resource. 
                   1857: #   FUTURE WORK:
                   1858: #      I need to look at this logic carefully.  My druthers would be to follow
                   1859: #      typical caching logic, and simple invalidate the cache, drop any subscription
                   1860: #      an let the next fetch start the ball rolling again... however that may
                   1861: #      actually be more difficult than it looks given the complex web of
                   1862: #      proxy servers.
                   1863: # Parameters:
                   1864: #    $cmd      - The command that got us here.
                   1865: #    $tail     - Tail of the command (remaining parameters).
                   1866: #    $client   - File descriptor connected to client.
                   1867: # Returns
                   1868: #     0        - Requested to exit, caller should shut down.
                   1869: #     1        - Continue processing.
                   1870: # Implicit inputs:
                   1871: #    The authentication systems describe above have their own forms of implicit
                   1872: #    input into the authentication process that are described above.
                   1873: #
                   1874: sub update_resource_handler {
                   1875: 
                   1876:     my ($cmd, $tail, $client) = @_;
                   1877:    
                   1878:     my $userinput = "$cmd:$tail";
                   1879:    
                   1880:     my $fname= $tail;		# This allows interactive testing
                   1881: 
                   1882: 
                   1883:     my $ownership=ishome($fname);
                   1884:     if ($ownership eq 'not_owner') {
                   1885: 	if (-e $fname) {
                   1886: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   1887: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   1888: 	    my $now=time;
                   1889: 	    my $since=$now-$atime;
                   1890: 	    if ($since>$perlvar{'lonExpire'}) {
                   1891: 		my $reply=&reply("unsub:$fname","$clientname");
                   1892: 		unlink("$fname");
                   1893: 	    } else {
                   1894: 		my $transname="$fname.in.transfer";
                   1895: 		my $remoteurl=&reply("sub:$fname","$clientname");
                   1896: 		my $response;
                   1897: 		alarm(120);
                   1898: 		{
                   1899: 		    my $ua=new LWP::UserAgent;
                   1900: 		    my $request=new HTTP::Request('GET',"$remoteurl");
                   1901: 		    $response=$ua->request($request,$transname);
                   1902: 		}
                   1903: 		alarm(0);
                   1904: 		if ($response->is_error()) {
                   1905: 		    unlink($transname);
                   1906: 		    my $message=$response->status_line;
                   1907: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   1908: 		} else {
                   1909: 		    if ($remoteurl!~/\.meta$/) {
                   1910: 			alarm(120);
                   1911: 			{
                   1912: 			    my $ua=new LWP::UserAgent;
                   1913: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1914: 			    my $mresponse=$ua->request($mrequest,$fname.'.meta');
                   1915: 			    if ($mresponse->is_error()) {
                   1916: 				unlink($fname.'.meta');
                   1917: 			    }
                   1918: 			}
                   1919: 			alarm(0);
                   1920: 		    }
                   1921: 		    rename($transname,$fname);
                   1922: 		}
                   1923: 	    }
                   1924: 	    &Reply( $client, "ok\n", $userinput);
                   1925: 	} else {
                   1926: 	    &Failure($client, "not_found\n", $userinput);
                   1927: 	}
                   1928:     } else {
                   1929: 	&Failure($client, "rejected\n", $userinput);
                   1930:     }
                   1931:     return 1;
                   1932: }
                   1933: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   1934: 
                   1935: #
1.226     foxr     1936: #   Fetch a user file from a remote server to the user's home directory
                   1937: #   userfiles subdir.
1.225     foxr     1938: # Parameters:
                   1939: #    $cmd      - The command that got us here.
                   1940: #    $tail     - Tail of the command (remaining parameters).
                   1941: #    $client   - File descriptor connected to client.
                   1942: # Returns
                   1943: #     0        - Requested to exit, caller should shut down.
                   1944: #     1        - Continue processing.
                   1945: #
                   1946: sub fetch_user_file_handler {
                   1947: 
                   1948:     my ($cmd, $tail, $client) = @_;
                   1949: 
                   1950:     my $userinput = "$cmd:$tail";
                   1951:     my $fname           = $tail;
1.232     foxr     1952:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     1953:     my $udir=&propath($udom,$uname).'/userfiles';
                   1954:     unless (-e $udir) {
                   1955: 	mkdir($udir,0770); 
                   1956:     }
1.232     foxr     1957:     Debug("fetch user file for $fname");
1.225     foxr     1958:     if (-e $udir) {
                   1959: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     1960: 
                   1961: 	# IF necessary, create the path right down to the file.
                   1962: 	# Note that any regular files in the way of this path are
                   1963: 	# wiped out to deal with some earlier folly of mine.
                   1964: 
1.267     raeburn  1965: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 1966: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     1967: 	}
                   1968: 
1.225     foxr     1969: 	my $destname=$udir.'/'.$ufile;
                   1970: 	my $transname=$udir.'/'.$ufile.'.in.transit';
                   1971: 	my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
                   1972: 	my $response;
1.232     foxr     1973: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.225     foxr     1974: 	alarm(120);
                   1975: 	{
                   1976: 	    my $ua=new LWP::UserAgent;
                   1977: 	    my $request=new HTTP::Request('GET',"$remoteurl");
                   1978: 	    $response=$ua->request($request,$transname);
                   1979: 	}
                   1980: 	alarm(0);
                   1981: 	if ($response->is_error()) {
                   1982: 	    unlink($transname);
                   1983: 	    my $message=$response->status_line;
                   1984: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   1985: 	    &Failure($client, "failed\n", $userinput);
                   1986: 	} else {
1.232     foxr     1987: 	    Debug("Renaming $transname to $destname");
1.225     foxr     1988: 	    if (!rename($transname,$destname)) {
                   1989: 		&logthis("Unable to move $transname to $destname");
                   1990: 		unlink($transname);
                   1991: 		&Failure($client, "failed\n", $userinput);
                   1992: 	    } else {
                   1993: 		&Reply($client, "ok\n", $userinput);
                   1994: 	    }
                   1995: 	}   
                   1996:     } else {
                   1997: 	&Failure($client, "not_home\n", $userinput);
                   1998:     }
                   1999:     return 1;
                   2000: }
                   2001: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2002: 
1.226     foxr     2003: #
                   2004: #   Remove a file from a user's home directory userfiles subdirectory.
                   2005: # Parameters:
                   2006: #    cmd   - the Lond request keyword that got us here.
                   2007: #    tail  - the part of the command past the keyword.
                   2008: #    client- File descriptor connected with the client.
                   2009: #
                   2010: # Returns:
                   2011: #    1    - Continue processing.
                   2012: sub remove_user_file_handler {
                   2013:     my ($cmd, $tail, $client) = @_;
                   2014: 
                   2015:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2016: 
                   2017:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2018:     if ($ufile =~m|/\.\./|) {
                   2019: 	# any files paths with /../ in them refuse 
                   2020: 	# to deal with
                   2021: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2022:     } else {
                   2023: 	my $udir = &propath($udom,$uname);
                   2024: 	if (-e $udir) {
                   2025: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2026: 	    if (-e $file) {
1.253     foxr     2027: 		#
                   2028: 		#   If the file is a regular file unlink is fine...
                   2029: 		#   However it's possible the client wants a dir.
                   2030: 		#   removed, in which case rmdir is more approprate:
                   2031: 		#
1.240     banghart 2032: 	        if (-f $file){
1.241     albertel 2033: 		    unlink($file);
                   2034: 		} elsif(-d $file) {
                   2035: 		    rmdir($file);
1.240     banghart 2036: 		}
1.226     foxr     2037: 		if (-e $file) {
1.253     foxr     2038: 		    #  File is still there after we deleted it ?!?
                   2039: 
1.226     foxr     2040: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2041: 		} else {
                   2042: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2043: 		}
                   2044: 	    } else {
                   2045: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2046: 	    }
                   2047: 	} else {
                   2048: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2049: 	}
                   2050:     }
                   2051:     return 1;
                   2052: }
                   2053: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2054: 
1.236     albertel 2055: #
                   2056: #   make a directory in a user's home directory userfiles subdirectory.
                   2057: # Parameters:
                   2058: #    cmd   - the Lond request keyword that got us here.
                   2059: #    tail  - the part of the command past the keyword.
                   2060: #    client- File descriptor connected with the client.
                   2061: #
                   2062: # Returns:
                   2063: #    1    - Continue processing.
                   2064: sub mkdir_user_file_handler {
                   2065:     my ($cmd, $tail, $client) = @_;
                   2066: 
                   2067:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2068:     $dir=&unescape($dir);
                   2069:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2070:     if ($ufile =~m|/\.\./|) {
                   2071: 	# any files paths with /../ in them refuse 
                   2072: 	# to deal with
                   2073: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2074:     } else {
                   2075: 	my $udir = &propath($udom,$uname);
                   2076: 	if (-e $udir) {
1.264     albertel 2077: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2078: 	    if (!&mkpath($newdir)) {
                   2079: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2080: 	    }
1.264     albertel 2081: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2082: 	} else {
                   2083: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2084: 	}
                   2085:     }
                   2086:     return 1;
                   2087: }
                   2088: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2089: 
1.237     albertel 2090: #
                   2091: #   rename a file in a user's home directory userfiles subdirectory.
                   2092: # Parameters:
                   2093: #    cmd   - the Lond request keyword that got us here.
                   2094: #    tail  - the part of the command past the keyword.
                   2095: #    client- File descriptor connected with the client.
                   2096: #
                   2097: # Returns:
                   2098: #    1    - Continue processing.
                   2099: sub rename_user_file_handler {
                   2100:     my ($cmd, $tail, $client) = @_;
                   2101: 
                   2102:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2103:     $old=&unescape($old);
                   2104:     $new=&unescape($new);
                   2105:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2106: 	# any files paths with /../ in them refuse to deal with
                   2107: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2108:     } else {
                   2109: 	my $udir = &propath($udom,$uname);
                   2110: 	if (-e $udir) {
                   2111: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2112: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2113: 	    if (-e $newfile) {
                   2114: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2115: 	    } elsif (! -e $oldfile) {
                   2116: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2117: 	    } else {
                   2118: 		if (!rename($oldfile,$newfile)) {
                   2119: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2120: 		} else {
                   2121: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2122: 		}
                   2123: 	    }
                   2124: 	} else {
                   2125: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2126: 	}
                   2127:     }
                   2128:     return 1;
                   2129: }
                   2130: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2131: 
1.227     foxr     2132: #
1.263     albertel 2133: #  Authenticate access to a user file by checking that the token the user's 
                   2134: #  passed also exists in their session file
1.227     foxr     2135: #
                   2136: # Parameters:
                   2137: #   cmd      - The request keyword that dispatched to tus.
                   2138: #   tail     - The tail of the request (colon separated parameters).
                   2139: #   client   - Filehandle open on the client.
                   2140: # Return:
                   2141: #    1.
                   2142: sub token_auth_user_file_handler {
                   2143:     my ($cmd, $tail, $client) = @_;
                   2144: 
                   2145:     my ($fname, $session) = split(/:/, $tail);
                   2146:     
                   2147:     chomp($session);
1.251     foxr     2148:     my $reply="non_auth\n";
1.227     foxr     2149:     if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
                   2150: 	     $session.'.id')) {
                   2151: 	while (my $line=<ENVIN>) {
1.251     foxr     2152: 	    if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply="ok\n"; }
1.227     foxr     2153: 	}
                   2154: 	close(ENVIN);
1.251     foxr     2155: 	&Reply($client, $reply, "$cmd:$tail");
1.227     foxr     2156:     } else {
                   2157: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2158:     }
                   2159:     return 1;
                   2160: 
                   2161: }
                   2162: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2163: 
                   2164: #
                   2165: #   Unsubscribe from a resource.
                   2166: #
                   2167: # Parameters:
                   2168: #    $cmd      - The command that got us here.
                   2169: #    $tail     - Tail of the command (remaining parameters).
                   2170: #    $client   - File descriptor connected to client.
                   2171: # Returns
                   2172: #     0        - Requested to exit, caller should shut down.
                   2173: #     1        - Continue processing.
                   2174: #
                   2175: sub unsubscribe_handler {
                   2176:     my ($cmd, $tail, $client) = @_;
                   2177: 
                   2178:     my $userinput= "$cmd:$tail";
                   2179:     
                   2180:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   2181: 
                   2182:     &Debug("Unsubscribing $fname");
                   2183:     if (-e $fname) {
                   2184: 	&Debug("Exists");
                   2185: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   2186:     } else {
                   2187: 	&Failure($client, "not_found\n", $userinput);
                   2188:     }
                   2189:     return 1;
                   2190: }
                   2191: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 2192: 
1.230     foxr     2193: #   Subscribe to a resource
                   2194: #
                   2195: # Parameters:
                   2196: #    $cmd      - The command that got us here.
                   2197: #    $tail     - Tail of the command (remaining parameters).
                   2198: #    $client   - File descriptor connected to client.
                   2199: # Returns
                   2200: #     0        - Requested to exit, caller should shut down.
                   2201: #     1        - Continue processing.
                   2202: #
                   2203: sub subscribe_handler {
                   2204:     my ($cmd, $tail, $client)= @_;
                   2205: 
                   2206:     my $userinput  = "$cmd:$tail";
                   2207: 
                   2208:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   2209: 
                   2210:     return 1;
                   2211: }
                   2212: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   2213: 
                   2214: #
                   2215: #   Determine the version of a resource (?) Or is it return
                   2216: #   the top version of the resource?  Not yet clear from the
                   2217: #   code in currentversion.
                   2218: #
                   2219: # Parameters:
                   2220: #    $cmd      - The command that got us here.
                   2221: #    $tail     - Tail of the command (remaining parameters).
                   2222: #    $client   - File descriptor connected to client.
                   2223: # Returns
                   2224: #     0        - Requested to exit, caller should shut down.
                   2225: #     1        - Continue processing.
                   2226: #
                   2227: sub current_version_handler {
                   2228:     my ($cmd, $tail, $client) = @_;
                   2229: 
                   2230:     my $userinput= "$cmd:$tail";
                   2231:    
                   2232:     my $fname   = $tail;
                   2233:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   2234:     return 1;
                   2235: 
                   2236: }
                   2237: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   2238: 
                   2239: #  Make an entry in a user's activity log.
                   2240: #
                   2241: # Parameters:
                   2242: #    $cmd      - The command that got us here.
                   2243: #    $tail     - Tail of the command (remaining parameters).
                   2244: #    $client   - File descriptor connected to client.
                   2245: # Returns
                   2246: #     0        - Requested to exit, caller should shut down.
                   2247: #     1        - Continue processing.
                   2248: #
                   2249: sub activity_log_handler {
                   2250:     my ($cmd, $tail, $client) = @_;
                   2251: 
                   2252: 
                   2253:     my $userinput= "$cmd:$tail";
                   2254: 
                   2255:     my ($udom,$uname,$what)=split(/:/,$tail);
                   2256:     chomp($what);
                   2257:     my $proname=&propath($udom,$uname);
                   2258:     my $now=time;
                   2259:     my $hfh;
                   2260:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   2261: 	print $hfh "$now:$clientname:$what\n";
                   2262: 	&Reply( $client, "ok\n", $userinput); 
                   2263:     } else {
                   2264: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   2265: 		 ."while attempting log\n", 
                   2266: 		 $userinput);
                   2267:     }
                   2268: 
                   2269:     return 1;
                   2270: }
1.263     albertel 2271: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     2272: 
                   2273: #
                   2274: #   Put a namespace entry in a user profile hash.
                   2275: #   My druthers would be for this to be an encrypted interaction too.
                   2276: #   anything that might be an inadvertent covert channel about either
                   2277: #   user authentication or user personal information....
                   2278: #
                   2279: # Parameters:
                   2280: #    $cmd      - The command that got us here.
                   2281: #    $tail     - Tail of the command (remaining parameters).
                   2282: #    $client   - File descriptor connected to client.
                   2283: # Returns
                   2284: #     0        - Requested to exit, caller should shut down.
                   2285: #     1        - Continue processing.
                   2286: #
                   2287: sub put_user_profile_entry {
                   2288:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     2289: 
1.230     foxr     2290:     my $userinput = "$cmd:$tail";
                   2291:     
1.242     raeburn  2292:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     2293:     if ($namespace ne 'roles') {
                   2294: 	chomp($what);
                   2295: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2296: 				  &GDBM_WRCREAT(),"P",$what);
                   2297: 	if($hashref) {
                   2298: 	    my @pairs=split(/\&/,$what);
                   2299: 	    foreach my $pair (@pairs) {
                   2300: 		my ($key,$value)=split(/=/,$pair);
                   2301: 		$hashref->{$key}=$value;
                   2302: 	    }
                   2303: 	    if (untie(%$hashref)) {
                   2304: 		&Reply( $client, "ok\n", $userinput);
                   2305: 	    } else {
                   2306: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2307: 			"while attempting put\n", 
                   2308: 			$userinput);
                   2309: 	    }
                   2310: 	} else {
                   2311: 	    &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
                   2312: 		     "while attempting put\n", $userinput);
                   2313: 	}
                   2314:     } else {
                   2315:         &Failure( $client, "refused\n", $userinput);
                   2316:     }
                   2317:     
                   2318:     return 1;
                   2319: }
                   2320: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   2321: 
                   2322: # 
                   2323: #   Increment a profile entry in the user history file.
                   2324: #   The history contains keyword value pairs.  In this case,
                   2325: #   The value itself is a pair of numbers.  The first, the current value
                   2326: #   the second an increment that this function applies to the current
                   2327: #   value.
                   2328: #
                   2329: # Parameters:
                   2330: #    $cmd      - The command that got us here.
                   2331: #    $tail     - Tail of the command (remaining parameters).
                   2332: #    $client   - File descriptor connected to client.
                   2333: # Returns
                   2334: #     0        - Requested to exit, caller should shut down.
                   2335: #     1        - Continue processing.
                   2336: #
                   2337: sub increment_user_value_handler {
                   2338:     my ($cmd, $tail, $client) = @_;
                   2339:     
                   2340:     my $userinput   = "$cmd:$tail";
                   2341:     
                   2342:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   2343:     if ($namespace ne 'roles') {
                   2344:         chomp($what);
                   2345: 	my $hashref = &tie_user_hash($udom, $uname,
                   2346: 				     $namespace, &GDBM_WRCREAT(),
                   2347: 				     "P",$what);
                   2348: 	if ($hashref) {
                   2349: 	    my @pairs=split(/\&/,$what);
                   2350: 	    foreach my $pair (@pairs) {
                   2351: 		my ($key,$value)=split(/=/,$pair);
                   2352: 		# We could check that we have a number...
                   2353: 		if (! defined($value) || $value eq '') {
                   2354: 		    $value = 1;
                   2355: 		}
                   2356: 		$hashref->{$key}+=$value;
                   2357: 	    }
                   2358: 	    if (untie(%$hashref)) {
                   2359: 		&Reply( $client, "ok\n", $userinput);
                   2360: 	    } else {
                   2361: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2362: 			 "while attempting inc\n", $userinput);
                   2363: 	    }
                   2364: 	} else {
                   2365: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2366: 		     "while attempting inc\n", $userinput);
                   2367: 	}
                   2368:     } else {
                   2369: 	&Failure($client, "refused\n", $userinput);
                   2370:     }
                   2371:     
                   2372:     return 1;
                   2373: }
                   2374: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   2375: 
                   2376: #
                   2377: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   2378: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   2379: #   for a person grants the permissions packaged with that role
                   2380: #   to that user when the role is selected.
                   2381: #
                   2382: # Parameters:
                   2383: #    $cmd       - The command string (rolesput).
                   2384: #    $tail      - The remainder of the request line.  For rolesput this
                   2385: #                 consists of a colon separated list that contains:
                   2386: #                 The domain and user that is granting the role (logged).
                   2387: #                 The domain and user that is getting the role.
                   2388: #                 The roles being granted as a set of & separated pairs.
                   2389: #                 each pair a key value pair.
                   2390: #    $client    - File descriptor connected to the client.
                   2391: # Returns:
                   2392: #     0         - If the daemon should exit
                   2393: #     1         - To continue processing.
                   2394: #
                   2395: #
                   2396: sub roles_put_handler {
                   2397:     my ($cmd, $tail, $client) = @_;
                   2398: 
                   2399:     my $userinput  = "$cmd:$tail";
                   2400: 
                   2401:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   2402:     
                   2403: 
                   2404:     my $namespace='roles';
                   2405:     chomp($what);
                   2406:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2407: 				 &GDBM_WRCREAT(), "P",
                   2408: 				 "$exedom:$exeuser:$what");
                   2409:     #
                   2410:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   2411:     #  handle is open for the minimal amount of time.  Since the flush
                   2412:     #  is done on close this improves the chances the log will be an un-
                   2413:     #  corrupted ordered thing.
                   2414:     if ($hashref) {
1.261     foxr     2415: 	my $pass_entry = &get_auth_type($udom, $uname);
                   2416: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   2417: 	$auth_type = $auth_type.":";
1.230     foxr     2418: 	my @pairs=split(/\&/,$what);
                   2419: 	foreach my $pair (@pairs) {
                   2420: 	    my ($key,$value)=split(/=/,$pair);
                   2421: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     2422: 			       $auth_type);
1.230     foxr     2423: 	    $hashref->{$key}=$value;
                   2424: 	}
                   2425: 	if (untie($hashref)) {
                   2426: 	    &Reply($client, "ok\n", $userinput);
                   2427: 	} else {
                   2428: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2429: 		     "while attempting rolesput\n", $userinput);
                   2430: 	}
                   2431:     } else {
                   2432: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2433: 		 "while attempting rolesput\n", $userinput);
                   2434:     }
                   2435:     return 1;
                   2436: }
                   2437: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   2438: 
                   2439: #
1.231     foxr     2440: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   2441: #  a permissions package associated with the role from the user's profile.
                   2442: #
                   2443: # Parameters:
                   2444: #     $cmd                 - The command (rolesdel)
                   2445: #     $tail                - The remainder of the request line. This consists
                   2446: #                             of:
                   2447: #                             The domain and user requesting the change (logged)
                   2448: #                             The domain and user being changed.
                   2449: #                             The roles being revoked.  These are shipped to us
                   2450: #                             as a bunch of & separated role name keywords.
                   2451: #     $client              - The file handle open on the client.
                   2452: # Returns:
                   2453: #     1                    - Continue processing
                   2454: #     0                    - Exit.
                   2455: #
                   2456: sub roles_delete_handler {
                   2457:     my ($cmd, $tail, $client)  = @_;
                   2458: 
                   2459:     my $userinput    = "$cmd:$tail";
                   2460:    
                   2461:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   2462:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   2463: 	   "what = ".$what);
                   2464:     my $namespace='roles';
                   2465:     chomp($what);
                   2466:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2467: 				 &GDBM_WRCREAT(), "D",
                   2468: 				 "$exedom:$exeuser:$what");
                   2469:     
                   2470:     if ($hashref) {
                   2471: 	my @rolekeys=split(/\&/,$what);
                   2472: 	
                   2473: 	foreach my $key (@rolekeys) {
                   2474: 	    delete $hashref->{$key};
                   2475: 	}
                   2476: 	if (untie(%$hashref)) {
                   2477: 	    &Reply($client, "ok\n", $userinput);
                   2478: 	} else {
                   2479: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2480: 		     "while attempting rolesdel\n", $userinput);
                   2481: 	}
                   2482:     } else {
                   2483:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2484: 		 "while attempting rolesdel\n", $userinput);
                   2485:     }
                   2486:     
                   2487:     return 1;
                   2488: }
                   2489: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   2490: 
                   2491: # Unencrypted get from a user's profile database.  See 
                   2492: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   2493: # This function retrieves a keyed item from a specific named database in the
                   2494: # user's directory.
                   2495: #
                   2496: # Parameters:
                   2497: #   $cmd             - Command request keyword (get).
                   2498: #   $tail            - Tail of the command.  This is a colon separated list
                   2499: #                      consisting of the domain and username that uniquely
                   2500: #                      identifies the profile,
                   2501: #                      The 'namespace' which selects the gdbm file to 
                   2502: #                      do the lookup in, 
                   2503: #                      & separated list of keys to lookup.  Note that
                   2504: #                      the values are returned as an & separated list too.
                   2505: #   $client          - File descriptor open on the client.
                   2506: # Returns:
                   2507: #   1       - Continue processing.
                   2508: #   0       - Exit.
                   2509: #
                   2510: sub get_profile_entry {
                   2511:     my ($cmd, $tail, $client) = @_;
                   2512: 
                   2513:     my $userinput= "$cmd:$tail";
                   2514:    
                   2515:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2516:     chomp($what);
1.255     foxr     2517: 
                   2518:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   2519:     my ($first) = split(/:/,$replystring);
                   2520:     if($first ne "error") {
                   2521: 	&Reply($client, "$replystring\n", $userinput);
1.231     foxr     2522:     } else {
1.255     foxr     2523: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     2524:     }
                   2525:     return 1;
1.255     foxr     2526: 
                   2527: 
1.231     foxr     2528: }
                   2529: &register_handler("get", \&get_profile_entry, 0,1,0);
                   2530: 
                   2531: #
                   2532: #  Process the encrypted get request.  Note that the request is sent
                   2533: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   2534: #  information about the sensitive keys is given to the snooper.  Just not
                   2535: #  information about the values of the sensitive key.  Hmm if I wanted to
                   2536: #  know these I'd snoop for the egets. Get the profile item names from them
                   2537: #  and then issue a get for them since there's no enforcement of the
                   2538: #  requirement of an encrypted get for particular profile items.  If I
                   2539: #  were re-doing this, I'd force the request to be encrypted as well as the
                   2540: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   2541: #  that would prevent any covert channel snooping.
                   2542: #
                   2543: #  Parameters:
                   2544: #     $cmd               - Command keyword of request (eget).
                   2545: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
                   2546: #     $client            - File open on the client.
                   2547: #  Returns:
                   2548: #     1      - Continue processing
                   2549: #     0      - server should exit.
                   2550: sub get_profile_entry_encrypted {
                   2551:     my ($cmd, $tail, $client) = @_;
                   2552: 
                   2553:     my $userinput = "$cmd:$tail";
                   2554:    
                   2555:     my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
                   2556:     chomp($what);
1.255     foxr     2557:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   2558:     my ($first) = split(/:/, $qresult);
                   2559:     if($first ne "error") {
                   2560: 	
                   2561: 	if ($cipher) {
                   2562: 	    my $cmdlength=length($qresult);
                   2563: 	    $qresult.="         ";
                   2564: 	    my $encqresult='';
                   2565: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   2566: 		$encqresult.= unpack("H16", 
                   2567: 				     $cipher->encrypt(substr($qresult,
                   2568: 							     $encidx,
                   2569: 							     8)));
                   2570: 	    }
                   2571: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   2572: 	} else {
1.231     foxr     2573: 		&Failure( $client, "error:no_key\n", $userinput);
                   2574: 	    }
                   2575:     } else {
1.255     foxr     2576: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   2577: 
1.231     foxr     2578:     }
                   2579:     
                   2580:     return 1;
                   2581: }
1.255     foxr     2582: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 2583: 
1.231     foxr     2584: #
                   2585: #   Deletes a key in a user profile database.
                   2586: #   
                   2587: #   Parameters:
                   2588: #       $cmd                  - Command keyword (del).
                   2589: #       $tail                 - Command tail.  IN this case a colon
                   2590: #                               separated list containing:
                   2591: #                               The domain and user that identifies uniquely
                   2592: #                               the identity of the user.
                   2593: #                               The profile namespace (name of the profile
                   2594: #                               database file).
                   2595: #                               & separated list of keywords to delete.
                   2596: #       $client              - File open on client socket.
                   2597: # Returns:
                   2598: #     1   - Continue processing
                   2599: #     0   - Exit server.
                   2600: #
                   2601: #
                   2602: sub delete_profile_entry {
                   2603:     my ($cmd, $tail, $client) = @_;
                   2604: 
                   2605:     my $userinput = "cmd:$tail";
                   2606: 
                   2607:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2608:     chomp($what);
                   2609:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2610: 				 &GDBM_WRCREAT(),
                   2611: 				 "D",$what);
                   2612:     if ($hashref) {
                   2613:         my @keys=split(/\&/,$what);
                   2614: 	foreach my $key (@keys) {
                   2615: 	    delete($hashref->{$key});
                   2616: 	}
                   2617: 	if (untie(%$hashref)) {
                   2618: 	    &Reply($client, "ok\n", $userinput);
                   2619: 	} else {
                   2620: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2621: 		    "while attempting del\n", $userinput);
                   2622: 	}
                   2623:     } else {
                   2624: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2625: 		 "while attempting del\n", $userinput);
                   2626:     }
                   2627:     return 1;
                   2628: }
                   2629: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 2630: 
1.231     foxr     2631: #
                   2632: #  List the set of keys that are defined in a profile database file.
                   2633: #  A successful reply from this will contain an & separated list of
                   2634: #  the keys. 
                   2635: # Parameters:
                   2636: #     $cmd              - Command request (keys).
                   2637: #     $tail             - Remainder of the request, a colon separated
                   2638: #                         list containing domain/user that identifies the
                   2639: #                         user being queried, and the database namespace
                   2640: #                         (database filename essentially).
                   2641: #     $client           - File open on the client.
                   2642: #  Returns:
                   2643: #    1    - Continue processing.
                   2644: #    0    - Exit the server.
                   2645: #
                   2646: sub get_profile_keys {
                   2647:     my ($cmd, $tail, $client) = @_;
                   2648: 
                   2649:     my $userinput = "$cmd:$tail";
                   2650: 
                   2651:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   2652:     my $qresult='';
                   2653:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2654: 				  &GDBM_READER());
                   2655:     if ($hashref) {
                   2656: 	foreach my $key (keys %$hashref) {
                   2657: 	    $qresult.="$key&";
                   2658: 	}
                   2659: 	if (untie(%$hashref)) {
                   2660: 	    $qresult=~s/\&$//;
                   2661: 	    &Reply($client, "$qresult\n", $userinput);
                   2662: 	} else {
                   2663: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2664: 		    "while attempting keys\n", $userinput);
                   2665: 	}
                   2666:     } else {
                   2667: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2668: 		 "while attempting keys\n", $userinput);
                   2669:     }
                   2670:    
                   2671:     return 1;
                   2672: }
                   2673: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   2674: 
                   2675: #
                   2676: #   Dump the contents of a user profile database.
                   2677: #   Note that this constitutes a very large covert channel too since
                   2678: #   the dump will return sensitive information that is not encrypted.
                   2679: #   The naive security assumption is that the session negotiation ensures
                   2680: #   our client is trusted and I don't believe that's assured at present.
                   2681: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   2682: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   2683: # 
                   2684: #  Parameters:
                   2685: #     $cmd           - The command request keyword (currentdump).
                   2686: #     $tail          - Remainder of the request, consisting of a colon
                   2687: #                      separated list that has the domain/username and
                   2688: #                      the namespace to dump (database file).
                   2689: #     $client        - file open on the remote client.
                   2690: # Returns:
                   2691: #     1    - Continue processing.
                   2692: #     0    - Exit the server.
                   2693: #
                   2694: sub dump_profile_database {
                   2695:     my ($cmd, $tail, $client) = @_;
                   2696: 
                   2697:     my $userinput = "$cmd:$tail";
                   2698:    
                   2699:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   2700:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2701: 				 &GDBM_READER());
                   2702:     if ($hashref) {
                   2703: 	# Structure of %data:
                   2704: 	# $data{$symb}->{$parameter}=$value;
                   2705: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   2706: 	# since $parameter will be unescaped, we do not
                   2707:  	# have to worry about silly parameter names...
                   2708: 	
                   2709:         my $qresult='';
                   2710: 	my %data = ();                     # A hash of anonymous hashes..
                   2711: 	while (my ($key,$value) = each(%$hashref)) {
                   2712: 	    my ($v,$symb,$param) = split(/:/,$key);
                   2713: 	    next if ($v eq 'version' || $symb eq 'keys');
                   2714: 	    next if (exists($data{$symb}) && 
                   2715: 		     exists($data{$symb}->{$param}) &&
                   2716: 		     $data{$symb}->{'v.'.$param} > $v);
                   2717: 	    $data{$symb}->{$param}=$value;
                   2718: 	    $data{$symb}->{'v.'.$param}=$v;
                   2719: 	}
                   2720: 	if (untie(%$hashref)) {
                   2721: 	    while (my ($symb,$param_hash) = each(%data)) {
                   2722: 		while(my ($param,$value) = each (%$param_hash)){
                   2723: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   2724: 		    #
                   2725: 		    #   Just dump the symb=value pairs separated by &
                   2726: 		    #
                   2727: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   2728: 		}
                   2729: 	    }
                   2730: 	    chop($qresult);
                   2731: 	    &Reply($client , "$qresult\n", $userinput);
                   2732: 	} else {
                   2733: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2734: 		     "while attempting currentdump\n", $userinput);
                   2735: 	}
                   2736:     } else {
                   2737: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2738: 		"while attempting currentdump\n", $userinput);
                   2739:     }
                   2740: 
                   2741:     return 1;
                   2742: }
                   2743: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   2744: 
                   2745: #
                   2746: #   Dump a profile database with an optional regular expression
                   2747: #   to match against the keys.  In this dump, no effort is made
                   2748: #   to separate symb from version information. Presumably the
                   2749: #   databases that are dumped by this command are of a different
                   2750: #   structure.  Need to look at this and improve the documentation of
                   2751: #   both this and the currentdump handler.
                   2752: # Parameters:
                   2753: #    $cmd                     - The command keyword.
                   2754: #    $tail                    - All of the characters after the $cmd:
                   2755: #                               These are expected to be a colon
                   2756: #                               separated list containing:
                   2757: #                               domain/user - identifying the user.
                   2758: #                               namespace   - identifying the database.
                   2759: #                               regexp      - optional regular expression
                   2760: #                                             that is matched against
                   2761: #                                             database keywords to do
                   2762: #                                             selective dumps.
                   2763: #   $client                   - Channel open on the client.
                   2764: # Returns:
                   2765: #    1    - Continue processing.
                   2766: # Side effects:
                   2767: #    response is written to $client.
                   2768: #
                   2769: sub dump_with_regexp {
                   2770:     my ($cmd, $tail, $client) = @_;
                   2771: 
                   2772: 
                   2773:     my $userinput = "$cmd:$tail";
                   2774: 
                   2775:     my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);
                   2776:     if (defined($regexp)) {
                   2777: 	$regexp=&unescape($regexp);
                   2778:     } else {
                   2779: 	$regexp='.';
                   2780:     }
                   2781:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2782: 				 &GDBM_READER());
                   2783:     if ($hashref) {
                   2784:         my $qresult='';
                   2785: 	while (my ($key,$value) = each(%$hashref)) {
                   2786: 	    if ($regexp eq '.') {
                   2787: 		$qresult.=$key.'='.$value.'&';
                   2788: 	    } else {
                   2789: 		my $unescapeKey = &unescape($key);
                   2790: 		if (eval('$unescapeKey=~/$regexp/')) {
                   2791: 		    $qresult.="$key=$value&";
                   2792: 		}
                   2793: 	    }
                   2794: 	}
                   2795: 	if (untie(%$hashref)) {
                   2796: 	    chop($qresult);
                   2797: 	    &Reply($client, "$qresult\n", $userinput);
                   2798: 	} else {
                   2799: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2800: 		     "while attempting dump\n", $userinput);
                   2801: 	}
                   2802:     } else {
                   2803: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2804: 		"while attempting dump\n", $userinput);
                   2805:     }
                   2806: 
                   2807:     return 1;
                   2808: }
                   2809: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   2810: 
                   2811: #  Store a set of key=value pairs associated with a versioned name.
                   2812: #
                   2813: #  Parameters:
                   2814: #    $cmd                - Request command keyword.
                   2815: #    $tail               - Tail of the request.  This is a colon
                   2816: #                          separated list containing:
                   2817: #                          domain/user - User and authentication domain.
                   2818: #                          namespace   - Name of the database being modified
                   2819: #                          rid         - Resource keyword to modify.
                   2820: #                          what        - new value associated with rid.
                   2821: #
                   2822: #    $client             - Socket open on the client.
                   2823: #
                   2824: #
                   2825: #  Returns:
                   2826: #      1 (keep on processing).
                   2827: #  Side-Effects:
                   2828: #    Writes to the client
                   2829: sub store_handler {
                   2830:     my ($cmd, $tail, $client) = @_;
                   2831:  
                   2832:     my $userinput = "$cmd:$tail";
                   2833: 
                   2834:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
                   2835:     if ($namespace ne 'roles') {
                   2836: 
                   2837: 	chomp($what);
                   2838: 	my @pairs=split(/\&/,$what);
                   2839: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 2840: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     2841: 				       "$rid:$what");
                   2842: 	if ($hashref) {
                   2843: 	    my $now = time;
                   2844: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
                   2845: 	    my $key;
                   2846: 	    $hashref->{"version:$rid"}++;
                   2847: 	    my $version=$hashref->{"version:$rid"};
                   2848: 	    my $allkeys=''; 
                   2849: 	    foreach my $pair (@pairs) {
                   2850: 		my ($key,$value)=split(/=/,$pair);
                   2851: 		$allkeys.=$key.':';
                   2852: 		$hashref->{"$version:$rid:$key"}=$value;
                   2853: 	    }
                   2854: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   2855: 	    $allkeys.='timestamp';
                   2856: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
                   2857: 	    if (untie($hashref)) {
                   2858: 		&Reply($client, "ok\n", $userinput);
                   2859: 	    } else {
                   2860: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2861: 			"while attempting store\n", $userinput);
                   2862: 	    }
                   2863: 	} else {
                   2864: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2865: 		     "while attempting store\n", $userinput);
                   2866: 	}
                   2867:     } else {
                   2868: 	&Failure($client, "refused\n", $userinput);
                   2869:     }
                   2870: 
                   2871:     return 1;
                   2872: }
                   2873: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 2874: 
1.231     foxr     2875: #
                   2876: #  Dump out all versions of a resource that has key=value pairs associated
                   2877: # with it for each version.  These resources are built up via the store
                   2878: # command.
                   2879: #
                   2880: #  Parameters:
                   2881: #     $cmd               - Command keyword.
                   2882: #     $tail              - Remainder of the request which consists of:
                   2883: #                          domain/user   - User and auth. domain.
                   2884: #                          namespace     - name of resource database.
                   2885: #                          rid           - Resource id.
                   2886: #    $client             - socket open on the client.
                   2887: #
                   2888: # Returns:
                   2889: #      1  indicating the caller should not yet exit.
                   2890: # Side-effects:
                   2891: #   Writes a reply to the client.
                   2892: #   The reply is a string of the following shape:
                   2893: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   2894: #    Where the 1 above represents version 1.
                   2895: #    this continues for all pairs of keys in all versions.
                   2896: #
                   2897: #
                   2898: #    
                   2899: #
                   2900: sub restore_handler {
                   2901:     my ($cmd, $tail, $client) = @_;
                   2902: 
                   2903:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
                   2904: 
                   2905:     my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
                   2906:     $namespace=~s/\//\_/g;
                   2907:     $namespace=~s/\W//g;
                   2908:     chomp($rid);
                   2909:     my $proname=&propath($udom,$uname);
                   2910:     my $qresult='';
                   2911:     my %hash;
                   2912:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
                   2913: 	    &GDBM_READER(),0640)) {
                   2914: 	my $version=$hash{"version:$rid"};
                   2915: 	$qresult.="version=$version&";
                   2916: 	my $scope;
                   2917: 	for ($scope=1;$scope<=$version;$scope++) {
                   2918: 	    my $vkeys=$hash{"$scope:keys:$rid"};
                   2919: 	    my @keys=split(/:/,$vkeys);
                   2920: 	    my $key;
                   2921: 	    $qresult.="$scope:keys=$vkeys&";
                   2922: 	    foreach $key (@keys) {
                   2923: 		$qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
                   2924: 	    }                                  
                   2925: 	}
                   2926: 	if (untie(%hash)) {
                   2927: 	    $qresult=~s/\&$//;
                   2928: 	    &Reply( $client, "$qresult\n", $userinput);
                   2929: 	} else {
                   2930: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2931: 		    "while attempting restore\n", $userinput);
                   2932: 	}
                   2933:     } else {
                   2934: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2935: 		"while attempting restore\n", $userinput);
                   2936:     }
                   2937:   
                   2938:     return 1;
                   2939: 
                   2940: 
                   2941: }
                   2942: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     2943: 
                   2944: #
                   2945: #   Add a chat message to to a discussion board.
                   2946: #
                   2947: # Parameters:
                   2948: #    $cmd                - Request keyword.
                   2949: #    $tail               - Tail of the command. A colon separated list
                   2950: #                          containing:
                   2951: #                          cdom    - Domain on which the chat board lives
                   2952: #                          cnum    - Identifier of the discussion group.
                   2953: #                          post    - Body of the posting.
                   2954: #   $client              - Socket open on the client.
                   2955: # Returns:
                   2956: #   1    - Indicating caller should keep on processing.
                   2957: #
                   2958: # Side-effects:
                   2959: #   writes a reply to the client.
                   2960: #
                   2961: #
                   2962: sub send_chat_handler {
                   2963:     my ($cmd, $tail, $client) = @_;
                   2964: 
                   2965:     
                   2966:     my $userinput = "$cmd:$tail";
                   2967: 
                   2968:     my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
                   2969:     &chat_add($cdom,$cnum,$newpost);
                   2970:     &Reply($client, "ok\n", $userinput);
                   2971: 
                   2972:     return 1;
                   2973: }
                   2974: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 2975: 
1.234     foxr     2976: #
                   2977: #   Retrieve the set of chat messagss from a discussion board.
                   2978: #
                   2979: #  Parameters:
                   2980: #    $cmd             - Command keyword that initiated the request.
                   2981: #    $tail            - Remainder of the request after the command
                   2982: #                       keyword.  In this case a colon separated list of
                   2983: #                       chat domain    - Which discussion board.
                   2984: #                       chat id        - Discussion thread(?)
                   2985: #                       domain/user    - Authentication domain and username
                   2986: #                                        of the requesting person.
                   2987: #   $client           - Socket open on the client program.
                   2988: # Returns:
                   2989: #    1     - continue processing
                   2990: # Side effects:
                   2991: #    Response is written to the client.
                   2992: #
                   2993: sub retrieve_chat_handler {
                   2994:     my ($cmd, $tail, $client) = @_;
                   2995: 
                   2996: 
                   2997:     my $userinput = "$cmd:$tail";
                   2998: 
                   2999:     my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
                   3000:     my $reply='';
                   3001:     foreach (&get_chat($cdom,$cnum,$udom,$uname)) {
                   3002: 	$reply.=&escape($_).':';
                   3003:     }
                   3004:     $reply=~s/\:$//;
                   3005:     &Reply($client, $reply."\n", $userinput);
                   3006: 
                   3007: 
                   3008:     return 1;
                   3009: }
                   3010: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3011: 
                   3012: #
                   3013: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3014: #  a file for later retrieval.  This prevents sql query results from
                   3015: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3016: #  less of an issue since multiple outstanding requests can be concurrently
                   3017: #  serviced.
                   3018: #
                   3019: #  Parameters:
                   3020: #     $cmd       - COmmand keyword that initiated the request.
                   3021: #     $tail      - Remainder of the command after the keyword.
                   3022: #                  For this function, this consists of a query and
                   3023: #                  3 arguments that are self-documentingly labelled
                   3024: #                  in the original arg1, arg2, arg3.
                   3025: #     $client    - Socket open on the client.
                   3026: # Return:
                   3027: #    1   - Indicating processing should continue.
                   3028: # Side-effects:
                   3029: #    a reply is written to $client.
                   3030: #
                   3031: sub send_query_handler {
                   3032:     my ($cmd, $tail, $client) = @_;
                   3033: 
                   3034: 
                   3035:     my $userinput = "$cmd:$tail";
                   3036: 
                   3037:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3038:     $query=~s/\n*$//g;
                   3039:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   3040: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   3041: 	  $userinput);
                   3042:     
                   3043:     return 1;
                   3044: }
                   3045: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   3046: 
                   3047: #
                   3048: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   3049: #   The query is submitted via a "querysend" transaction.
                   3050: #   There it is passed on to the lonsql daemon, queued and issued to
                   3051: #   mysql.
                   3052: #     This transaction is invoked when the sql transaction is complete
                   3053: #   it stores the query results in flie and indicates query completion.
                   3054: #   presumably local software then fetches this response... I'm guessing
                   3055: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   3056: #   lonsql on completion of the query interacts with the lond of our
                   3057: #   client to do a query reply storing two files:
                   3058: #    - id     - The results of the query.
                   3059: #    - id.end - Indicating the transaction completed. 
                   3060: #    NOTE: id is a unique id assigned to the query and querysend time.
                   3061: # Parameters:
                   3062: #    $cmd        - Command keyword that initiated this request.
                   3063: #    $tail       - Remainder of the tail.  In this case that's a colon
                   3064: #                  separated list containing the query Id and the 
                   3065: #                  results of the query.
                   3066: #    $client     - Socket open on the client.
                   3067: # Return:
                   3068: #    1           - Indicating that we should continue processing.
                   3069: # Side effects:
                   3070: #    ok written to the client.
                   3071: #
                   3072: sub reply_query_handler {
                   3073:     my ($cmd, $tail, $client) = @_;
                   3074: 
                   3075: 
                   3076:     my $userinput = "$cmd:$tail";
                   3077: 
                   3078:     my ($cmd,$id,$reply)=split(/:/,$userinput); 
                   3079:     my $store;
                   3080:     my $execdir=$perlvar{'lonDaemons'};
                   3081:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   3082: 	$reply=~s/\&/\n/g;
                   3083: 	print $store $reply;
                   3084: 	close $store;
                   3085: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   3086: 	print $store2 "done\n";
                   3087: 	close $store2;
                   3088: 	&Reply($client, "ok\n", $userinput);
                   3089:     } else {
                   3090: 	&Failure($client, "error: ".($!+0)
                   3091: 		." IO::File->new Failed ".
                   3092: 		"while attempting queryreply\n", $userinput);
                   3093:     }
                   3094:  
                   3095: 
                   3096:     return 1;
                   3097: }
                   3098: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   3099: 
                   3100: #
                   3101: #  Process the courseidput request.  Not quite sure what this means
                   3102: #  at the system level sense.  It appears a gdbm file in the 
                   3103: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   3104: #  a set of entries made in that database.
                   3105: #
                   3106: # Parameters:
                   3107: #   $cmd      - The command keyword that initiated this request.
                   3108: #   $tail     - Tail of the command.  In this case consists of a colon
                   3109: #               separated list contaning the domain to apply this to and
                   3110: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  3111: #               Each value is a colon separated list that includes:  
                   3112: #               description, institutional code and course owner.
                   3113: #               For backward compatibility with versions included
                   3114: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   3115: #               code and/or course owner are preserved from the existing 
                   3116: #               record when writing a new record in response to 1.1 or 
                   3117: #               1.2 implementations of lonnet::flushcourselogs().   
                   3118: #                      
1.234     foxr     3119: #   $client   - Socket open on the client.
                   3120: # Returns:
                   3121: #   1    - indicating that processing should continue
                   3122: #
                   3123: # Side effects:
                   3124: #   reply is written to the client.
                   3125: #
                   3126: sub put_course_id_handler {
                   3127:     my ($cmd, $tail, $client) = @_;
                   3128: 
                   3129: 
                   3130:     my $userinput = "$cmd:$tail";
                   3131: 
1.266     raeburn  3132:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     3133:     chomp($what);
                   3134:     my $now=time;
                   3135:     my @pairs=split(/\&/,$what);
                   3136: 
                   3137:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3138:     if ($hashref) {
                   3139: 	foreach my $pair (@pairs) {
1.271     raeburn  3140:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   3141:             $courseinfo =~ s/=/:/g;
1.272     raeburn  3142: 
1.273   ! albertel 3143:             my @current_items = split(/:/,$hashref->{$key});
        !          3144:             shift(@current_items); # remove description
        !          3145:             pop(@current_items);   # remove last access
1.272     raeburn  3146:             my $numcurrent = scalar(@current_items);
                   3147: 
1.273   ! albertel 3148:             my @new_items = split(/:/,$courseinfo);
1.272     raeburn  3149:             my $numnew = scalar(@new_items);
                   3150:             if ($numcurrent > 0) {
                   3151:                 if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
                   3152:                     $courseinfo .= ':'.join(':',@current_items);
                   3153:                 } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
                   3154:                     $courseinfo .= ':'.$current_items[$numcurrent-1];
                   3155:                 }
                   3156:             }
1.266     raeburn  3157: 	    $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     3158: 	}
                   3159: 	if (untie(%$hashref)) {
1.253     foxr     3160: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     3161: 	} else {
1.253     foxr     3162: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     3163: 		     ." untie(GDBM) Failed ".
                   3164: 		     "while attempting courseidput\n", $userinput);
                   3165: 	}
                   3166:     } else {
1.253     foxr     3167: 	&Failure($client, "error: ".($!+0)
1.234     foxr     3168: 		 ." tie(GDBM) Failed ".
                   3169: 		 "while attempting courseidput\n", $userinput);
                   3170:     }
1.253     foxr     3171:     
1.234     foxr     3172: 
                   3173:     return 1;
                   3174: }
                   3175: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   3176: 
                   3177: #  Retrieves the value of a course id resource keyword pattern
                   3178: #  defined since a starting date.  Both the starting date and the
                   3179: #  keyword pattern are optional.  If the starting date is not supplied it
                   3180: #  is treated as the beginning of time.  If the pattern is not found,
                   3181: #  it is treatred as "." matching everything.
                   3182: #
                   3183: #  Parameters:
                   3184: #     $cmd     - Command keyword that resulted in us being dispatched.
                   3185: #     $tail    - The remainder of the command that, in this case, consists
                   3186: #                of a colon separated list of:
                   3187: #                 domain   - The domain in which the course database is 
                   3188: #                            defined.
                   3189: #                 since    - Optional parameter describing the minimum
                   3190: #                            time of definition(?) of the resources that
                   3191: #                            will match the dump.
                   3192: #                 description - regular expression that is used to filter
                   3193: #                            the dump.  Only keywords matching this regexp
                   3194: #                            will be used.
1.272     raeburn  3195: #                 institutional code - optional supplied code to filter 
                   3196: #                            the dump. Only courses with an institutional code 
                   3197: #                            that match the supplied code will be returned.
                   3198: #                 owner    - optional supplied username of owner to filter
                   3199: #                            the dump.  Only courses for which the course 
                   3200: #                            owner matches the supplied username will be
                   3201: #                            returned. Implicit assumption that owner is a user
                   3202: #                            in the domain in which the course database is defined.        
1.234     foxr     3203: #     $client  - The socket open on the client.
                   3204: # Returns:
                   3205: #    1     - Continue processing.
                   3206: # Side Effects:
                   3207: #   a reply is written to $client.
                   3208: sub dump_course_id_handler {
                   3209:     my ($cmd, $tail, $client) = @_;
                   3210: 
                   3211:     my $userinput = "$cmd:$tail";
                   3212: 
1.266     raeburn  3213:     my ($udom,$since,$description,$instcodefilter,$ownerfilter) =split(/:/,$tail);
1.234     foxr     3214:     if (defined($description)) {
                   3215: 	$description=&unescape($description);
                   3216:     } else {
                   3217: 	$description='.';
                   3218:     }
1.266     raeburn  3219:     if (defined($instcodefilter)) {
                   3220:         $instcodefilter=&unescape($instcodefilter);
                   3221:     } else {
                   3222:         $instcodefilter='.';
                   3223:     }
                   3224:     if (defined($ownerfilter)) {
                   3225:         $ownerfilter=&unescape($ownerfilter);
                   3226:     } else {
                   3227:         $ownerfilter='.';
                   3228:     }
                   3229: 
1.234     foxr     3230:     unless (defined($since)) { $since=0; }
                   3231:     my $qresult='';
                   3232:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3233:     if ($hashref) {
                   3234: 	while (my ($key,$value) = each(%$hashref)) {
1.266     raeburn  3235: 	    my ($descr,$lasttime,$inst_code,$owner);
1.272     raeburn  3236:             my @courseitems = split/:/,$value;
                   3237:             $descr = shift @courseitems;
                   3238:             $lasttime = pop @courseitems;
                   3239:             if (@courseitems > 0) {
                   3240:                 $inst_code = shift @courseitems;
                   3241:             }
                   3242:             if (@courseitems > 0) {
                   3243:                 $owner = shift @courseitems;
                   3244:             }
1.234     foxr     3245: 	    if ($lasttime<$since) { next; }
1.266     raeburn  3246:             my $match = 1;
                   3247: 	    unless ($description eq '.') {
                   3248: 		my $unescapeDescr = &unescape($descr);
                   3249: 		unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
                   3250:                     $match = 0;
1.234     foxr     3251: 		}
1.266     raeburn  3252:             }
                   3253:             unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
                   3254:                 my $unescapeInstcode = &unescape($inst_code);
                   3255:                 unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
                   3256:                     $match = 0;
                   3257:                 }
1.234     foxr     3258: 	    }
1.266     raeburn  3259:             unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
                   3260:                 my $unescapeOwner = &unescape($owner);
                   3261:                 unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
                   3262:                     $match = 0;
                   3263:                 }
                   3264:             }
                   3265:             if ($match == 1) {
                   3266:                 $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
                   3267:             }
1.234     foxr     3268: 	}
                   3269: 	if (untie(%$hashref)) {
                   3270: 	    chop($qresult);
                   3271: 	    &Reply($client, "$qresult\n", $userinput);
                   3272: 	} else {
                   3273: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3274: 		    "while attempting courseiddump\n", $userinput);
                   3275: 	}
                   3276:     } else {
                   3277: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3278: 		"while attempting courseiddump\n", $userinput);
                   3279:     }
                   3280: 
                   3281: 
                   3282:     return 1;
                   3283: }
                   3284: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     3285: 
                   3286: #
                   3287: #  Puts an id to a domains id database. 
                   3288: #
                   3289: #  Parameters:
                   3290: #   $cmd     - The command that triggered us.
                   3291: #   $tail    - Remainder of the request other than the command. This is a 
                   3292: #              colon separated list containing:
                   3293: #              $domain  - The domain for which we are writing the id.
                   3294: #              $pairs  - The id info to write... this is and & separated list
                   3295: #                        of keyword=value.
                   3296: #   $client  - Socket open on the client.
                   3297: #  Returns:
                   3298: #    1   - Continue processing.
                   3299: #  Side effects:
                   3300: #     reply is written to $client.
                   3301: #
                   3302: sub put_id_handler {
                   3303:     my ($cmd,$tail,$client) = @_;
                   3304: 
                   3305: 
                   3306:     my $userinput = "$cmd:$tail";
                   3307: 
                   3308:     my ($udom,$what)=split(/:/,$tail);
                   3309:     chomp($what);
                   3310:     my @pairs=split(/\&/,$what);
                   3311:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   3312: 				   "P", $what);
                   3313:     if ($hashref) {
                   3314: 	foreach my $pair (@pairs) {
                   3315: 	    my ($key,$value)=split(/=/,$pair);
                   3316: 	    $hashref->{$key}=$value;
                   3317: 	}
                   3318: 	if (untie(%$hashref)) {
                   3319: 	    &Reply($client, "ok\n", $userinput);
                   3320: 	} else {
                   3321: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3322: 		     "while attempting idput\n", $userinput);
                   3323: 	}
                   3324:     } else {
                   3325: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3326: 		  "while attempting idput\n", $userinput);
                   3327:     }
                   3328: 
                   3329:     return 1;
                   3330: }
1.263     albertel 3331: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     3332: 
                   3333: #
                   3334: #  Retrieves a set of id values from the id database.
                   3335: #  Returns an & separated list of results, one for each requested id to the
                   3336: #  client.
                   3337: #
                   3338: # Parameters:
                   3339: #   $cmd       - Command keyword that caused us to be dispatched.
                   3340: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3341: #               domain - the domain whose id table we dump
                   3342: #               ids      Consists of an & separated list of
                   3343: #                        id keywords whose values will be fetched.
                   3344: #                        nonexisting keywords will have an empty value.
                   3345: #   $client    - Socket open on the client.
                   3346: #
                   3347: # Returns:
                   3348: #    1 - indicating processing should continue.
                   3349: # Side effects:
                   3350: #   An & separated list of results is written to $client.
                   3351: #
                   3352: sub get_id_handler {
                   3353:     my ($cmd, $tail, $client) = @_;
                   3354: 
                   3355:     
                   3356:     my $userinput = "$client:$tail";
                   3357:     
                   3358:     my ($udom,$what)=split(/:/,$tail);
                   3359:     chomp($what);
                   3360:     my @queries=split(/\&/,$what);
                   3361:     my $qresult='';
                   3362:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   3363:     if ($hashref) {
                   3364: 	for (my $i=0;$i<=$#queries;$i++) {
                   3365: 	    $qresult.="$hashref->{$queries[$i]}&";
                   3366: 	}
                   3367: 	if (untie(%$hashref)) {
                   3368: 	    $qresult=~s/\&$//;
                   3369: 	    &Reply($client, "$qresult\n", $userinput);
                   3370: 	} else {
                   3371: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3372: 		      "while attempting idget\n",$userinput);
                   3373: 	}
                   3374:     } else {
                   3375: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3376: 		 "while attempting idget\n",$userinput);
                   3377:     }
                   3378:     
                   3379:     return 1;
                   3380: }
1.263     albertel 3381: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     3382: 
                   3383: #
                   3384: #  Process the tmpput command I'm not sure what this does.. Seems to
                   3385: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   3386: # where Id is the client's ip concatenated with a sequence number.
                   3387: # The file will contain some value that is passed in.  Is this e.g.
                   3388: # a login token?
                   3389: #
                   3390: # Parameters:
                   3391: #    $cmd     - The command that got us dispatched.
                   3392: #    $tail    - The remainder of the request following $cmd:
                   3393: #               In this case this will be the contents of the file.
                   3394: #    $client  - Socket connected to the client.
                   3395: # Returns:
                   3396: #    1 indicating processing can continue.
                   3397: # Side effects:
                   3398: #   A file is created in the local filesystem.
                   3399: #   A reply is sent to the client.
                   3400: sub tmp_put_handler {
                   3401:     my ($cmd, $what, $client) = @_;
                   3402: 
                   3403:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   3404: 
                   3405: 
                   3406:     my $store;
                   3407:     $tmpsnum++;
                   3408:     my $id=$$.'_'.$clientip.'_'.$tmpsnum;
                   3409:     $id=~s/\W/\_/g;
                   3410:     $what=~s/\n//g;
                   3411:     my $execdir=$perlvar{'lonDaemons'};
                   3412:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
                   3413: 	print $store $what;
                   3414: 	close $store;
                   3415: 	&Reply($client, "$id\n", $userinput);
                   3416:     } else {
                   3417: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   3418: 		  "while attempting tmpput\n", $userinput);
                   3419:     }
                   3420:     return 1;
                   3421:   
                   3422: }
                   3423: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 3424: 
1.238     foxr     3425: #   Processes the tmpget command.  This command returns the contents
                   3426: #  of a temporary resource file(?) created via tmpput.
                   3427: #
                   3428: # Paramters:
                   3429: #    $cmd      - Command that got us dispatched.
                   3430: #    $id       - Tail of the command, contain the id of the resource
                   3431: #                we want to fetch.
                   3432: #    $client   - socket open on the client.
                   3433: # Return:
                   3434: #    1         - Inidcating processing can continue.
                   3435: # Side effects:
                   3436: #   A reply is sent to the client.
                   3437: #
                   3438: sub tmp_get_handler {
                   3439:     my ($cmd, $id, $client) = @_;
                   3440: 
                   3441:     my $userinput = "$cmd:$id"; 
                   3442:     
                   3443: 
                   3444:     $id=~s/\W/\_/g;
                   3445:     my $store;
                   3446:     my $execdir=$perlvar{'lonDaemons'};
                   3447:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   3448: 	my $reply=<$store>;
                   3449: 	&Reply( $client, "$reply\n", $userinput);
                   3450: 	close $store;
                   3451:     } else {
                   3452: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   3453: 		  "while attempting tmpget\n", $userinput);
                   3454:     }
                   3455: 
                   3456:     return 1;
                   3457: }
                   3458: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 3459: 
1.238     foxr     3460: #
                   3461: #  Process the tmpdel command.  This command deletes a temp resource
                   3462: #  created by the tmpput command.
                   3463: #
                   3464: # Parameters:
                   3465: #   $cmd      - Command that got us here.
                   3466: #   $id       - Id of the temporary resource created.
                   3467: #   $client   - socket open on the client process.
                   3468: #
                   3469: # Returns:
                   3470: #   1     - Indicating processing should continue.
                   3471: # Side Effects:
                   3472: #   A file is deleted
                   3473: #   A reply is sent to the client.
                   3474: sub tmp_del_handler {
                   3475:     my ($cmd, $id, $client) = @_;
                   3476:     
                   3477:     my $userinput= "$cmd:$id";
                   3478:     
                   3479:     chomp($id);
                   3480:     $id=~s/\W/\_/g;
                   3481:     my $execdir=$perlvar{'lonDaemons'};
                   3482:     if (unlink("$execdir/tmp/$id.tmp")) {
                   3483: 	&Reply($client, "ok\n", $userinput);
                   3484:     } else {
                   3485: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   3486: 		  "while attempting tmpdel\n", $userinput);
                   3487:     }
                   3488:     
                   3489:     return 1;
                   3490: 
                   3491: }
                   3492: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 3493: 
1.238     foxr     3494: #
1.246     foxr     3495: #   Processes the setannounce command.  This command
                   3496: #   creates a file named announce.txt in the top directory of
                   3497: #   the documentn root and sets its contents.  The announce.txt file is
                   3498: #   printed in its entirety at the LonCAPA login page.  Note:
                   3499: #   once the announcement.txt fileis created it cannot be deleted.
                   3500: #   However, setting the contents of the file to empty removes the
                   3501: #   announcement from the login page of loncapa so who cares.
                   3502: #
                   3503: # Parameters:
                   3504: #    $cmd          - The command that got us dispatched.
                   3505: #    $announcement - The text of the announcement.
                   3506: #    $client       - Socket open on the client process.
                   3507: # Retunrns:
                   3508: #   1             - Indicating request processing should continue
                   3509: # Side Effects:
                   3510: #   The file {DocRoot}/announcement.txt is created.
                   3511: #   A reply is sent to $client.
                   3512: #
                   3513: sub set_announce_handler {
                   3514:     my ($cmd, $announcement, $client) = @_;
                   3515:   
                   3516:     my $userinput    = "$cmd:$announcement";
                   3517: 
                   3518:     chomp($announcement);
                   3519:     $announcement=&unescape($announcement);
                   3520:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   3521: 				'/announcement.txt')) {
                   3522: 	print $store $announcement;
                   3523: 	close $store;
                   3524: 	&Reply($client, "ok\n", $userinput);
                   3525:     } else {
                   3526: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   3527:     }
                   3528: 
                   3529:     return 1;
                   3530: }
                   3531: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 3532: 
1.246     foxr     3533: #
                   3534: #  Return the version of the daemon.  This can be used to determine
                   3535: #  the compatibility of cross version installations or, alternatively to
                   3536: #  simply know who's out of date and who isn't.  Note that the version
                   3537: #  is returned concatenated with the tail.
                   3538: # Parameters:
                   3539: #   $cmd        - the request that dispatched to us.
                   3540: #   $tail       - Tail of the request (client's version?).
                   3541: #   $client     - Socket open on the client.
                   3542: #Returns:
                   3543: #   1 - continue processing requests.
                   3544: # Side Effects:
                   3545: #   Replies with version to $client.
                   3546: sub get_version_handler {
                   3547:     my ($cmd, $tail, $client) = @_;
                   3548: 
                   3549:     my $userinput  = $cmd.$tail;
                   3550:     
                   3551:     &Reply($client, &version($userinput)."\n", $userinput);
                   3552: 
                   3553: 
                   3554:     return 1;
                   3555: }
                   3556: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 3557: 
1.246     foxr     3558: #  Set the current host and domain.  This is used to support
                   3559: #  multihomed systems.  Each IP of the system, or even separate daemons
                   3560: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   3561: #  machine.  This command selects the virtual lonCAPA.  The client always
                   3562: #  knows the right one since it is lonc and it is selecting the domain/system
                   3563: #  from the hosts.tab file.
                   3564: # Parameters:
                   3565: #    $cmd      - Command that dispatched us.
                   3566: #    $tail     - Tail of the command (domain/host requested).
                   3567: #    $socket   - Socket open on the client.
                   3568: #
                   3569: # Returns:
                   3570: #     1   - Indicates the program should continue to process requests.
                   3571: # Side-effects:
                   3572: #     The default domain/system context is modified for this daemon.
                   3573: #     a reply is sent to the client.
                   3574: #
                   3575: sub set_virtual_host_handler {
                   3576:     my ($cmd, $tail, $socket) = @_;
                   3577:   
                   3578:     my $userinput  ="$cmd:$tail";
                   3579: 
                   3580:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   3581: 
                   3582: 
                   3583:     return 1;
                   3584: }
1.247     albertel 3585: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     3586: 
                   3587: #  Process a request to exit:
                   3588: #   - "bye" is sent to the client.
                   3589: #   - The client socket is shutdown and closed.
                   3590: #   - We indicate to the caller that we should exit.
                   3591: # Formal Parameters:
                   3592: #   $cmd                - The command that got us here.
                   3593: #   $tail               - Tail of the command (empty).
                   3594: #   $client             - Socket open on the tail.
                   3595: # Returns:
                   3596: #   0      - Indicating the program should exit!!
                   3597: #
                   3598: sub exit_handler {
                   3599:     my ($cmd, $tail, $client) = @_;
                   3600: 
                   3601:     my $userinput = "$cmd:$tail";
                   3602: 
                   3603:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   3604:     &Reply($client, "bye\n", $userinput);
                   3605:     $client->shutdown(2);        # shutdown the socket forcibly.
                   3606:     $client->close();
                   3607: 
                   3608:     return 0;
                   3609: }
1.248     foxr     3610: &register_handler("exit", \&exit_handler, 0,1,1);
                   3611: &register_handler("init", \&exit_handler, 0,1,1);
                   3612: &register_handler("quit", \&exit_handler, 0,1,1);
                   3613: 
                   3614: #  Determine if auto-enrollment is enabled.
                   3615: #  Note that the original had what I believe to be a defect.
                   3616: #  The original returned 0 if the requestor was not a registerd client.
                   3617: #  It should return "refused".
                   3618: # Formal Parameters:
                   3619: #   $cmd       - The command that invoked us.
                   3620: #   $tail      - The tail of the command (Extra command parameters.
                   3621: #   $client    - The socket open on the client that issued the request.
                   3622: # Returns:
                   3623: #    1         - Indicating processing should continue.
                   3624: #
                   3625: sub enrollment_enabled_handler {
                   3626:     my ($cmd, $tail, $client) = @_;
                   3627:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   3628: 
                   3629:     
                   3630:     my $cdom = split(/:/, $tail);   # Domain we're asking about.
                   3631:     my $outcome  = &localenroll::run($cdom);
                   3632:     &Reply($client, "$outcome\n", $userinput);
                   3633: 
                   3634:     return 1;
                   3635: }
                   3636: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   3637: 
                   3638: #   Get the official sections for which auto-enrollment is possible.
                   3639: #   Since the admin people won't know about 'unofficial sections' 
                   3640: #   we cannot auto-enroll on them.
                   3641: # Formal Parameters:
                   3642: #    $cmd     - The command request that got us dispatched here.
                   3643: #    $tail    - The remainder of the request.  In our case this
                   3644: #               will be split into:
                   3645: #               $coursecode   - The course name from the admin point of view.
                   3646: #               $cdom         - The course's domain(?).
                   3647: #    $client  - Socket open on the client.
                   3648: # Returns:
                   3649: #    1    - Indiciting processing should continue.
                   3650: #
                   3651: sub get_sections_handler {
                   3652:     my ($cmd, $tail, $client) = @_;
                   3653:     my $userinput = "$cmd:$tail";
                   3654: 
                   3655:     my ($coursecode, $cdom) = split(/:/, $tail);
                   3656:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   3657:     my $seclist = &escape(join(':',@secs));
                   3658: 
                   3659:     &Reply($client, "$seclist\n", $userinput);
                   3660:     
                   3661: 
                   3662:     return 1;
                   3663: }
                   3664: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   3665: 
                   3666: #   Validate the owner of a new course section.  
                   3667: #
                   3668: # Formal Parameters:
                   3669: #   $cmd      - Command that got us dispatched.
                   3670: #   $tail     - the remainder of the command.  For us this consists of a
                   3671: #               colon separated string containing:
                   3672: #                  $inst    - Course Id from the institutions point of view.
                   3673: #                  $owner   - Proposed owner of the course.
                   3674: #                  $cdom    - Domain of the course (from the institutions
                   3675: #                             point of view?)..
                   3676: #   $client   - Socket open on the client.
                   3677: #
                   3678: # Returns:
                   3679: #   1        - Processing should continue.
                   3680: #
                   3681: sub validate_course_owner_handler {
                   3682:     my ($cmd, $tail, $client)  = @_;
                   3683:     my $userinput = "$cmd:$tail";
                   3684:     my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
                   3685: 
                   3686:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
                   3687:     &Reply($client, "$outcome\n", $userinput);
                   3688: 
                   3689: 
                   3690: 
                   3691:     return 1;
                   3692: }
                   3693: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 3694: 
1.248     foxr     3695: #
                   3696: #   Validate a course section in the official schedule of classes
                   3697: #   from the institutions point of view (part of autoenrollment).
                   3698: #
                   3699: # Formal Parameters:
                   3700: #   $cmd          - The command request that got us dispatched.
                   3701: #   $tail         - The tail of the command.  In this case,
                   3702: #                   this is a colon separated set of words that will be split
                   3703: #                   into:
                   3704: #                        $inst_course_id - The course/section id from the
                   3705: #                                          institutions point of view.
                   3706: #                        $cdom           - The domain from the institutions
                   3707: #                                          point of view.
                   3708: #   $client       - Socket open on the client.
                   3709: # Returns:
                   3710: #    1           - Indicating processing should continue.
                   3711: #
                   3712: sub validate_course_section_handler {
                   3713:     my ($cmd, $tail, $client) = @_;
                   3714:     my $userinput = "$cmd:$tail";
                   3715:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   3716: 
                   3717:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
                   3718:     &Reply($client, "$outcome\n", $userinput);
                   3719: 
                   3720: 
                   3721:     return 1;
                   3722: }
                   3723: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   3724: 
                   3725: #
                   3726: #   Create a password for a new auto-enrollment user.
                   3727: #   I think/guess, this password allows access to the institutions 
                   3728: #   AIS class list server/services.  Stuart can correct this comment
                   3729: #   when he finds out how wrong I am.
                   3730: #
                   3731: # Formal Parameters:
                   3732: #    $cmd     - The command request that got us dispatched.
                   3733: #    $tail    - The tail of the command.   In this case this is a colon separated
                   3734: #               set of words that will be split into:
                   3735: #               $authparam - An authentication parameter (username??).
                   3736: #               $cdom      - The domain of the course from the institution's
                   3737: #                            point of view.
                   3738: #    $client  - The socket open on the client.
                   3739: # Returns:
                   3740: #    1 - continue processing.
                   3741: #
                   3742: sub create_auto_enroll_password_handler {
                   3743:     my ($cmd, $tail, $client) = @_;
                   3744:     my $userinput = "$cmd:$tail";
                   3745: 
                   3746:     my ($authparam, $cdom) = split(/:/, $userinput);
                   3747: 
                   3748:     my ($create_passwd,$authchk);
                   3749:     ($authparam,
                   3750:      $create_passwd,
                   3751:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   3752: 
                   3753:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   3754: 	   $userinput);
                   3755: 
                   3756: 
                   3757:     return 1;
                   3758: }
                   3759: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   3760: 		  0, 1, 0);
                   3761: 
                   3762: #   Retrieve and remove temporary files created by/during autoenrollment.
                   3763: #
                   3764: # Formal Parameters:
                   3765: #    $cmd      - The command that got us dispatched.
                   3766: #    $tail     - The tail of the command.  In our case this is a colon 
                   3767: #                separated list that will be split into:
                   3768: #                $filename - The name of the file to remove.
                   3769: #                            The filename is given as a path relative to
                   3770: #                            the LonCAPA temp file directory.
                   3771: #    $client   - Socket open on the client.
                   3772: #
                   3773: # Returns:
                   3774: #   1     - Continue processing.
                   3775: sub retrieve_auto_file_handler {
                   3776:     my ($cmd, $tail, $client)    = @_;
                   3777:     my $userinput                = "cmd:$tail";
                   3778: 
                   3779:     my ($filename)   = split(/:/, $tail);
                   3780: 
                   3781:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
                   3782:     if ( (-e $source) && ($filename ne '') ) {
                   3783: 	my $reply = '';
                   3784: 	if (open(my $fh,$source)) {
                   3785: 	    while (<$fh>) {
                   3786: 		chomp($_);
                   3787: 		$_ =~ s/^\s+//g;
                   3788: 		$_ =~ s/\s+$//g;
                   3789: 		$reply .= $_;
                   3790: 	    }
                   3791: 	    close($fh);
                   3792: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   3793: 
                   3794: #   Does this have to be uncommented??!?  (RF).
                   3795: #
                   3796: #                                unlink($source);
                   3797: 	} else {
                   3798: 	    &Failure($client, "error\n", $userinput);
                   3799: 	}
                   3800:     } else {
                   3801: 	&Failure($client, "error\n", $userinput);
                   3802:     }
                   3803:     
                   3804: 
                   3805:     return 1;
                   3806: }
                   3807: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   3808: 
                   3809: #
                   3810: #   Read and retrieve institutional code format (for support form).
                   3811: # Formal Parameters:
                   3812: #    $cmd        - Command that dispatched us.
                   3813: #    $tail       - Tail of the command.  In this case it conatins 
                   3814: #                  the course domain and the coursename.
                   3815: #    $client     - Socket open on the client.
                   3816: # Returns:
                   3817: #    1     - Continue processing.
                   3818: #
                   3819: sub get_institutional_code_format_handler {
                   3820:     my ($cmd, $tail, $client)   = @_;
                   3821:     my $userinput               = "$cmd:$tail";
                   3822: 
                   3823:     my $reply;
                   3824:     my($cdom,$course) = split(/:/,$tail);
                   3825:     my @pairs = split/\&/,$course;
                   3826:     my %instcodes = ();
                   3827:     my %codes = ();
                   3828:     my @codetitles = ();
                   3829:     my %cat_titles = ();
                   3830:     my %cat_order = ();
                   3831:     foreach (@pairs) {
                   3832: 	my ($key,$value) = split/=/,$_;
                   3833: 	$instcodes{&unescape($key)} = &unescape($value);
                   3834:     }
                   3835:     my $formatreply = &localenroll::instcode_format($cdom,
                   3836: 						    \%instcodes,
                   3837: 						    \%codes,
                   3838: 						    \@codetitles,
                   3839: 						    \%cat_titles,
                   3840: 						    \%cat_order);
                   3841:     if ($formatreply eq 'ok') {
                   3842: 	my $codes_str = &hash2str(%codes);
                   3843: 	my $codetitles_str = &array2str(@codetitles);
                   3844: 	my $cat_titles_str = &hash2str(%cat_titles);
                   3845: 	my $cat_order_str = &hash2str(%cat_order);
                   3846: 	&Reply($client,
                   3847: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   3848: 	       .$cat_order_str."\n",
                   3849: 	       $userinput);
                   3850:     } else {
                   3851: 	# this else branch added by RF since if not ok, lonc will
                   3852: 	# hang waiting on reply until timeout.
                   3853: 	#
                   3854: 	&Reply($client, "format_error\n", $userinput);
                   3855:     }
                   3856:     
                   3857:     return 1;
                   3858: }
1.265     albertel 3859: &register_handler("autoinstcodeformat",
                   3860: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     3861: 
1.265     albertel 3862: #
                   3863: # Gets a student's photo to exist (in the correct image type) in the user's 
                   3864: # directory.
                   3865: # Formal Parameters:
                   3866: #    $cmd     - The command request that got us dispatched.
                   3867: #    $tail    - A colon separated set of words that will be split into:
                   3868: #               $domain - student's domain
                   3869: #               $uname  - student username
                   3870: #               $type   - image type desired
                   3871: #    $client  - The socket open on the client.
                   3872: # Returns:
                   3873: #    1 - continue processing.
                   3874: sub student_photo_handler {
                   3875:     my ($cmd, $tail, $client) = @_;
                   3876:     my ($domain,$uname,$type) = split(/:/, $tail);
                   3877: 
                   3878:     my $path=&propath($domain,$uname).
                   3879: 	'/userfiles/internal/studentphoto.'.$type;
                   3880:     if (-e $path) {
                   3881: 	&Reply($client,"ok\n","$cmd:$tail");
                   3882: 	return 1;
                   3883:     }
                   3884:     &mkpath($path);
                   3885:     my $file=&localstudentphoto::fetch($domain,$uname);
                   3886:     if (!$file) {
                   3887: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   3888: 	return 1;
                   3889:     }
                   3890:     if (!-e $path) { &convert_photo($file,$path); }
                   3891:     if (-e $path) {
                   3892: 	&Reply($client,"ok\n","$cmd:$tail");
                   3893: 	return 1;
                   3894:     }
                   3895:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   3896:     return 1;
                   3897: }
                   3898: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     3899: 
1.264     albertel 3900: # mkpath makes all directories for a file, expects an absolute path with a
                   3901: # file or a trailing / if just a dir is passed
                   3902: # returns 1 on success 0 on failure
                   3903: sub mkpath {
                   3904:     my ($file)=@_;
                   3905:     my @parts=split(/\//,$file,-1);
                   3906:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   3907:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 3908: 	$now.='/'.$parts[$i]; 
1.264     albertel 3909: 	if (!-e $now) {
                   3910: 	    if  (!mkdir($now,0770)) { return 0; }
                   3911: 	}
                   3912:     }
                   3913:     return 1;
                   3914: }
                   3915: 
1.207     foxr     3916: #---------------------------------------------------------------
                   3917: #
                   3918: #   Getting, decoding and dispatching requests:
                   3919: #
                   3920: #
                   3921: #   Get a Request:
                   3922: #   Gets a Request message from the client.  The transaction
                   3923: #   is defined as a 'line' of text.  We remove the new line
                   3924: #   from the text line.  
1.226     foxr     3925: #
1.211     albertel 3926: sub get_request {
1.207     foxr     3927:     my $input = <$client>;
                   3928:     chomp($input);
1.226     foxr     3929: 
1.234     foxr     3930:     &Debug("get_request: Request = $input\n");
1.207     foxr     3931: 
                   3932:     &status('Processing '.$clientname.':'.$input);
                   3933: 
                   3934:     return $input;
                   3935: }
1.212     foxr     3936: #---------------------------------------------------------------
                   3937: #
                   3938: #  Process a request.  This sub should shrink as each action
                   3939: #  gets farmed out into a separat sub that is registered 
                   3940: #  with the dispatch hash.  
                   3941: #
                   3942: # Parameters:
                   3943: #    user_input   - The request received from the client (lonc).
                   3944: # Returns:
                   3945: #    true to keep processing, false if caller should exit.
                   3946: #
                   3947: sub process_request {
                   3948:     my ($userinput) = @_;      # Easier for now to break style than to
                   3949:                                 # fix all the userinput -> user_input.
                   3950:     my $wasenc    = 0;		# True if request was encrypted.
                   3951: # ------------------------------------------------------------ See if encrypted
                   3952:     if ($userinput =~ /^enc/) {
                   3953: 	$userinput = decipher($userinput);
                   3954: 	$wasenc=1;
                   3955: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     3956: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     3957: 	    return 0;
                   3958: 	}
                   3959:     }
                   3960:     Debug("process_request: $userinput\n");
                   3961:     
1.213     foxr     3962:     #  
                   3963:     #   The 'correct way' to add a command to lond is now to
                   3964:     #   write a sub to execute it and Add it to the command dispatch
                   3965:     #   hash via a call to register_handler..  The comments to that
                   3966:     #   sub should give you enough to go on to show how to do this
                   3967:     #   along with the examples that are building up as this code
                   3968:     #   is getting refactored.   Until all branches of the
                   3969:     #   if/elseif monster below have been factored out into
                   3970:     #   separate procesor subs, if the dispatch hash is missing
                   3971:     #   the command keyword, we will fall through to the remainder
                   3972:     #   of the if/else chain below in order to keep this thing in 
                   3973:     #   working order throughout the transmogrification.
                   3974: 
                   3975:     my ($command, $tail) = split(/:/, $userinput, 2);
                   3976:     chomp($command);
                   3977:     chomp($tail);
                   3978:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     3979:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   3980:     if(!$tail) {
                   3981: 	$tail ="";		# defined but blank.
                   3982:     }
1.213     foxr     3983: 
                   3984:     &Debug("Command received: $command, encoded = $wasenc");
                   3985: 
                   3986:     if(defined $Dispatcher{$command}) {
                   3987: 
                   3988: 	my $dispatch_info = $Dispatcher{$command};
                   3989: 	my $handler       = $$dispatch_info[0];
                   3990: 	my $need_encode   = $$dispatch_info[1];
                   3991: 	my $client_types  = $$dispatch_info[2];
                   3992: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   3993: 	      ."ClientType $client_types");
                   3994:       
                   3995: 	#  Validate the request:
                   3996:       
                   3997: 	my $ok = 1;
                   3998: 	my $requesterprivs = 0;
                   3999: 	if(&isClient()) {
                   4000: 	    $requesterprivs |= $CLIENT_OK;
                   4001: 	}
                   4002: 	if(&isManager()) {
                   4003: 	    $requesterprivs |= $MANAGER_OK;
                   4004: 	}
                   4005: 	if($need_encode && (!$wasenc)) {
                   4006: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   4007: 	    $ok = 0;
                   4008: 	}
                   4009: 	if(($client_types & $requesterprivs) == 0) {
                   4010: 	    Debug("Client not privileged to do this operation");
                   4011: 	    $ok = 0;
                   4012: 	}
                   4013: 
                   4014: 	if($ok) {
                   4015: 	    Debug("Dispatching to handler $command $tail");
                   4016: 	    my $keep_going = &$handler($command, $tail, $client);
                   4017: 	    return $keep_going;
                   4018: 	} else {
                   4019: 	    Debug("Refusing to dispatch because client did not match requirements");
                   4020: 	    Failure($client, "refused\n", $userinput);
                   4021: 	    return 1;
                   4022: 	}
                   4023: 
                   4024:     }    
                   4025: 
1.262     foxr     4026:     print $client "unknown_cmd\n";
1.212     foxr     4027: # -------------------------------------------------------------------- complete
                   4028:     Debug("process_request - returning 1");
                   4029:     return 1;
                   4030: }
1.207     foxr     4031: #
                   4032: #   Decipher encoded traffic
                   4033: #  Parameters:
                   4034: #     input      - Encoded data.
                   4035: #  Returns:
                   4036: #     Decoded data or undef if encryption key was not yet negotiated.
                   4037: #  Implicit input:
                   4038: #     cipher  - This global holds the negotiated encryption key.
                   4039: #
1.211     albertel 4040: sub decipher {
1.207     foxr     4041:     my ($input)  = @_;
                   4042:     my $output = '';
1.212     foxr     4043:     
                   4044:     
1.207     foxr     4045:     if($cipher) {
                   4046: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   4047: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   4048: 	    $output .= 
                   4049: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   4050: 	}
                   4051: 	return substr($output, 0, $enclength);
                   4052:     } else {
                   4053: 	return undef;
                   4054:     }
                   4055: }
                   4056: 
                   4057: #
                   4058: #   Register a command processor.  This function is invoked to register a sub
                   4059: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   4060: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   4061: #   as well:
                   4062: #    - Is the keyword recognized.
                   4063: #    - Is the proper client type attempting the request.
                   4064: #    - Is the request encrypted if it has to be.
                   4065: #   Parameters:
                   4066: #    $request_name         - Name of the request being registered.
                   4067: #                           This is the command request that will match
                   4068: #                           against the hash keywords to lookup the information
                   4069: #                           associated with the dispatch information.
                   4070: #    $procedure           - Reference to a sub to call to process the request.
                   4071: #                           All subs get called as follows:
                   4072: #                             Procedure($cmd, $tail, $replyfd, $key)
                   4073: #                             $cmd    - the actual keyword that invoked us.
                   4074: #                             $tail   - the tail of the request that invoked us.
                   4075: #                             $replyfd- File descriptor connected to the client
                   4076: #    $must_encode          - True if the request must be encoded to be good.
                   4077: #    $client_ok            - True if it's ok for a client to request this.
                   4078: #    $manager_ok           - True if it's ok for a manager to request this.
                   4079: # Side effects:
                   4080: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   4081: #      - On failure, the program will die as it's a bad internal bug to try to 
                   4082: #        register a duplicate command handler.
                   4083: #
1.211     albertel 4084: sub register_handler {
1.212     foxr     4085:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     4086: 
                   4087:     #  Don't allow duplication#
                   4088:    
                   4089:     if (defined $Dispatcher{$request_name}) {
                   4090: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   4091:     }
                   4092:     #   Build the client type mask:
                   4093:     
                   4094:     my $client_type_mask = 0;
                   4095:     if($client_ok) {
                   4096: 	$client_type_mask  |= $CLIENT_OK;
                   4097:     }
                   4098:     if($manager_ok) {
                   4099: 	$client_type_mask  |= $MANAGER_OK;
                   4100:     }
                   4101:    
                   4102:     #  Enter the hash:
                   4103:       
                   4104:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   4105:    
                   4106:     $Dispatcher{$request_name} = \@entry;
                   4107:    
                   4108: }
                   4109: 
                   4110: 
                   4111: #------------------------------------------------------------------
                   4112: 
                   4113: 
                   4114: 
                   4115: 
1.141     foxr     4116: #
1.96      foxr     4117: #  Convert an error return code from lcpasswd to a string value.
                   4118: #
                   4119: sub lcpasswdstrerror {
                   4120:     my $ErrorCode = shift;
1.97      foxr     4121:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     4122: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   4123:     } else {
1.98      foxr     4124: 	return $passwderrors[$ErrorCode];
1.96      foxr     4125:     }
                   4126: }
                   4127: 
1.97      foxr     4128: #
                   4129: # Convert an error return code from lcuseradd to a string value:
                   4130: #
                   4131: sub lcuseraddstrerror {
                   4132:     my $ErrorCode = shift;
                   4133:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
                   4134: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
                   4135:     } else {
1.98      foxr     4136: 	return $adderrors[$ErrorCode];
1.97      foxr     4137:     }
                   4138: }
                   4139: 
1.23      harris41 4140: # grabs exception and records it to log before exiting
                   4141: sub catchexception {
1.27      albertel 4142:     my ($error)=@_;
1.25      www      4143:     $SIG{'QUIT'}='DEFAULT';
                   4144:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 4145:     &status("Catching exception");
1.190     albertel 4146:     &logthis("<font color='red'>CRITICAL: "
1.134     albertel 4147:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27      albertel 4148:      ."a crash with this error msg->[$error]</font>");
1.57      www      4149:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 4150:     if ($client) { print $client "error: $error\n"; }
1.59      www      4151:     $server->close();
1.27      albertel 4152:     die($error);
1.23      harris41 4153: }
1.63      www      4154: sub timeout {
1.165     albertel 4155:     &status("Handling Timeout");
1.190     albertel 4156:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      4157:     &catchexception('Timeout');
                   4158: }
1.22      harris41 4159: # -------------------------------- Set signal handlers to record abnormal exits
                   4160: 
1.226     foxr     4161: 
1.22      harris41 4162: $SIG{'QUIT'}=\&catchexception;
                   4163: $SIG{__DIE__}=\&catchexception;
                   4164: 
1.81      matthew  4165: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 4166: &status("Read loncapa.conf and loncapa_apache.conf");
                   4167: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     4168: %perlvar=%{$perlvarref};
1.80      harris41 4169: undef $perlvarref;
1.19      www      4170: 
1.35      harris41 4171: # ----------------------------- Make sure this process is running from user=www
                   4172: my $wwwid=getpwnam('www');
                   4173: if ($wwwid!=$<) {
1.134     albertel 4174:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4175:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 4176:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 4177:  mailto $emailto -s '$subj' > /dev/null");
                   4178:    exit 1;
                   4179: }
                   4180: 
1.19      www      4181: # --------------------------------------------- Check if other instance running
                   4182: 
                   4183: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   4184: 
                   4185: if (-e $pidfile) {
                   4186:    my $lfh=IO::File->new("$pidfile");
                   4187:    my $pide=<$lfh>;
                   4188:    chomp($pide);
1.29      harris41 4189:    if (kill 0 => $pide) { die "already running"; }
1.19      www      4190: }
1.1       albertel 4191: 
                   4192: # ------------------------------------------------------------- Read hosts file
                   4193: 
                   4194: 
                   4195: 
                   4196: # establish SERVER socket, bind and listen.
                   4197: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   4198:                                 Type      => SOCK_STREAM,
                   4199:                                 Proto     => 'tcp',
                   4200:                                 Reuse     => 1,
                   4201:                                 Listen    => 10 )
1.29      harris41 4202:   or die "making socket: $@\n";
1.1       albertel 4203: 
                   4204: # --------------------------------------------------------- Do global variables
                   4205: 
                   4206: # global variables
                   4207: 
1.134     albertel 4208: my %children               = ();       # keys are current child process IDs
1.1       albertel 4209: 
                   4210: sub REAPER {                        # takes care of dead children
                   4211:     $SIG{CHLD} = \&REAPER;
1.165     albertel 4212:     &status("Handling child death");
1.178     foxr     4213:     my $pid;
                   4214:     do {
                   4215: 	$pid = waitpid(-1,&WNOHANG());
                   4216: 	if (defined($children{$pid})) {
                   4217: 	    &logthis("Child $pid died");
                   4218: 	    delete($children{$pid});
1.183     albertel 4219: 	} elsif ($pid > 0) {
1.178     foxr     4220: 	    &logthis("Unknown Child $pid died");
                   4221: 	}
                   4222:     } while ( $pid > 0 );
                   4223:     foreach my $child (keys(%children)) {
                   4224: 	$pid = waitpid($child,&WNOHANG());
                   4225: 	if ($pid > 0) {
                   4226: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   4227: 	    delete($children{$pid});
                   4228: 	}
1.176     albertel 4229:     }
1.165     albertel 4230:     &status("Finished Handling child death");
1.1       albertel 4231: }
                   4232: 
                   4233: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 4234:     &status("Killing children (INT)");
1.1       albertel 4235:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   4236:     kill 'INT' => keys %children;
1.59      www      4237:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 4238:     my $execdir=$perlvar{'lonDaemons'};
                   4239:     unlink("$execdir/logs/lond.pid");
1.190     albertel 4240:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 4241:     &status("Done killing children");
1.1       albertel 4242:     exit;                           # clean up with dignity
                   4243: }
                   4244: 
                   4245: sub HUPSMAN {                      # signal handler for SIGHUP
                   4246:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 4247:     &status("Killing children for restart (HUP)");
1.1       albertel 4248:     kill 'INT' => keys %children;
1.59      www      4249:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 4250:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 4251:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 4252:     unlink("$execdir/logs/lond.pid");
1.165     albertel 4253:     &status("Restarting self (HUP)");
1.1       albertel 4254:     exec("$execdir/lond");         # here we go again
                   4255: }
                   4256: 
1.144     foxr     4257: #
1.148     foxr     4258: #    Kill off hashes that describe the host table prior to re-reading it.
                   4259: #    Hashes affected are:
1.200     matthew  4260: #       %hostid, %hostdom %hostip %hostdns.
1.148     foxr     4261: #
                   4262: sub KillHostHashes {
                   4263:     foreach my $key (keys %hostid) {
                   4264: 	delete $hostid{$key};
                   4265:     }
                   4266:     foreach my $key (keys %hostdom) {
                   4267: 	delete $hostdom{$key};
                   4268:     }
                   4269:     foreach my $key (keys %hostip) {
                   4270: 	delete $hostip{$key};
                   4271:     }
1.200     matthew  4272:     foreach my $key (keys %hostdns) {
                   4273: 	delete $hostdns{$key};
                   4274:     }
1.148     foxr     4275: }
                   4276: #
                   4277: #   Read in the host table from file and distribute it into the various hashes:
                   4278: #
                   4279: #    - %hostid  -  Indexed by IP, the loncapa hostname.
                   4280: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
                   4281: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
                   4282: sub ReadHostTable {
                   4283: 
                   4284:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200     matthew  4285:     my $myloncapaname = $perlvar{'lonHostID'};
                   4286:     Debug("My loncapa name is : $myloncapaname");
1.148     foxr     4287:     while (my $configline=<CONFIG>) {
1.178     foxr     4288: 	if (!($configline =~ /^\s*\#/)) {
                   4289: 	    my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
                   4290: 	    chomp($ip); $ip=~s/\D+$//;
1.200     matthew  4291: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
                   4292: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
                   4293: 	    $hostip{$id}=$ip;	      # IP address of host.
                   4294: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
                   4295: 
                   4296: 	    if ($id eq $perlvar{'lonHostID'}) { 
                   4297: 		Debug("Found me in the host table: $name");
                   4298: 		$thisserver=$name; 
                   4299: 	    }
1.178     foxr     4300: 	}
1.148     foxr     4301:     }
                   4302:     close(CONFIG);
                   4303: }
                   4304: #
                   4305: #  Reload the Apache daemon's state.
1.150     foxr     4306: #  This is done by invoking /home/httpd/perl/apachereload
                   4307: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     4308: #
                   4309: sub ReloadApache {
1.150     foxr     4310:     my $execdir = $perlvar{'lonDaemons'};
                   4311:     my $script  = $execdir."/apachereload";
                   4312:     system($script);
1.148     foxr     4313: }
                   4314: 
                   4315: #
1.144     foxr     4316: #   Called in response to a USR2 signal.
                   4317: #   - Reread hosts.tab
                   4318: #   - All children connected to hosts that were removed from hosts.tab
                   4319: #     are killed via SIGINT
                   4320: #   - All children connected to previously existing hosts are sent SIGUSR1
                   4321: #   - Our internal hosts hash is updated to reflect the new contents of
                   4322: #     hosts.tab causing connections from hosts added to hosts.tab to
                   4323: #     now be honored.
                   4324: #
                   4325: sub UpdateHosts {
1.165     albertel 4326:     &status("Reload hosts.tab");
1.147     foxr     4327:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     4328:     #
                   4329:     #  The %children hash has the set of IP's we currently have children
                   4330:     #  on.  These need to be matched against records in the hosts.tab
                   4331:     #  Any ip's no longer in the table get killed off they correspond to
                   4332:     #  either dropped or changed hosts.  Note that the re-read of the table
                   4333:     #  will take care of new and changed hosts as connections come into being.
                   4334: 
                   4335: 
                   4336:     KillHostHashes;
                   4337:     ReadHostTable;
                   4338: 
                   4339:     foreach my $child (keys %children) {
                   4340: 	my $childip = $children{$child};
                   4341: 	if(!$hostid{$childip}) {
1.149     foxr     4342: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   4343: 		    ." $child for ip $childip </font>");
1.148     foxr     4344: 	    kill('INT', $child);
1.149     foxr     4345: 	} else {
                   4346: 	    logthis('<font color="green"> keeping child for ip '
                   4347: 		    ." $childip (pid=$child) </font>");
1.148     foxr     4348: 	}
                   4349:     }
                   4350:     ReloadApache;
1.165     albertel 4351:     &status("Finished reloading hosts.tab");
1.144     foxr     4352: }
                   4353: 
1.148     foxr     4354: 
1.57      www      4355: sub checkchildren {
1.165     albertel 4356:     &status("Checking on the children (sending signals)");
1.57      www      4357:     &initnewstatus();
                   4358:     &logstatus();
                   4359:     &logthis('Going to check on the children');
1.134     albertel 4360:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 4361:     foreach (sort keys %children) {
1.221     albertel 4362: 	#sleep 1;
1.57      www      4363:         unless (kill 'USR1' => $_) {
                   4364: 	    &logthis ('Child '.$_.' is dead');
                   4365:             &logstatus($$.' is dead');
1.221     albertel 4366: 	    delete($children{$_});
1.57      www      4367:         } 
1.61      harris41 4368:     }
1.63      www      4369:     sleep 5;
1.212     foxr     4370:     $SIG{ALRM} = sub { Debug("timeout"); 
                   4371: 		       die "timeout";  };
1.113     albertel 4372:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 4373:     &status("Checking on the children (waiting for reports)");
1.63      www      4374:     foreach (sort keys %children) {
                   4375:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 4376:           eval {
                   4377:             alarm(300);
1.63      www      4378: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 4379: 	    kill 9 => $_;
1.131     albertel 4380: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4381: 	    #$subj="LON: $currenthostid killed lond process $_";
                   4382: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   4383: 	    #$execdir=$perlvar{'lonDaemons'};
                   4384: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 4385: 	    delete($children{$_});
1.113     albertel 4386: 	    alarm(0);
                   4387: 	  }
1.63      www      4388:         }
                   4389:     }
1.113     albertel 4390:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 4391:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 4392:     &status("Finished checking children");
1.221     albertel 4393:     &logthis('Finished Checking children');
1.57      www      4394: }
                   4395: 
1.1       albertel 4396: # --------------------------------------------------------------------- Logging
                   4397: 
                   4398: sub logthis {
                   4399:     my $message=shift;
                   4400:     my $execdir=$perlvar{'lonDaemons'};
                   4401:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   4402:     my $now=time;
                   4403:     my $local=localtime($now);
1.58      www      4404:     $lastlog=$local.': '.$message;
1.1       albertel 4405:     print $fh "$local ($$): $message\n";
                   4406: }
                   4407: 
1.77      foxr     4408: # ------------------------- Conditional log if $DEBUG true.
                   4409: sub Debug {
                   4410:     my $message = shift;
                   4411:     if($DEBUG) {
                   4412: 	&logthis($message);
                   4413:     }
                   4414: }
1.161     foxr     4415: 
                   4416: #
                   4417: #   Sub to do replies to client.. this gives a hook for some
                   4418: #   debug tracing too:
                   4419: #  Parameters:
                   4420: #     fd      - File open on client.
                   4421: #     reply   - Text to send to client.
                   4422: #     request - Original request from client.
                   4423: #
                   4424: sub Reply {
1.192     foxr     4425:     my ($fd, $reply, $request) = @_;
1.161     foxr     4426:     print $fd $reply;
                   4427:     Debug("Request was $request  Reply was $reply");
                   4428: 
1.212     foxr     4429:     $Transactions++;
                   4430: 
                   4431: 
                   4432: }
                   4433: 
                   4434: 
                   4435: #
                   4436: #    Sub to report a failure.
                   4437: #    This function:
                   4438: #     -   Increments the failure statistic counters.
                   4439: #     -   Invokes Reply to send the error message to the client.
                   4440: # Parameters:
                   4441: #    fd       - File descriptor open on the client
                   4442: #    reply    - Reply text to emit.
                   4443: #    request  - The original request message (used by Reply
                   4444: #               to debug if that's enabled.
                   4445: # Implicit outputs:
                   4446: #    $Failures- The number of failures is incremented.
                   4447: #    Reply (invoked here) sends a message to the 
                   4448: #    client:
                   4449: #
                   4450: sub Failure {
                   4451:     my $fd      = shift;
                   4452:     my $reply   = shift;
                   4453:     my $request = shift;
                   4454:    
                   4455:     $Failures++;
                   4456:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     4457: }
1.57      www      4458: # ------------------------------------------------------------------ Log status
                   4459: 
                   4460: sub logstatus {
1.178     foxr     4461:     &status("Doing logging");
                   4462:     my $docdir=$perlvar{'lonDocRoot'};
                   4463:     {
                   4464: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  4465:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     4466:         $fh->close();
                   4467:     }
1.221     albertel 4468:     &status("Finished $$.txt");
                   4469:     {
                   4470: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   4471: 	flock(LOG,LOCK_EX);
                   4472: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   4473: 	    .$status."\t".$lastlog."\t $keymode\n";
                   4474: 	flock(DB,LOCK_UN);
                   4475: 	close(LOG);
                   4476:     }
1.178     foxr     4477:     &status("Finished logging");
1.57      www      4478: }
                   4479: 
                   4480: sub initnewstatus {
                   4481:     my $docdir=$perlvar{'lonDocRoot'};
                   4482:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
                   4483:     my $now=time;
                   4484:     my $local=localtime($now);
                   4485:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      4486:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 4487:     while (my $filename=readdir(DIR)) {
1.64      www      4488:         unlink("$docdir/lon-status/londchld/$filename");
                   4489:     }
                   4490:     closedir(DIR);
1.57      www      4491: }
                   4492: 
                   4493: # -------------------------------------------------------------- Status setting
                   4494: 
                   4495: sub status {
                   4496:     my $what=shift;
                   4497:     my $now=time;
                   4498:     my $local=localtime($now);
1.178     foxr     4499:     $status=$local.': '.$what;
                   4500:     $0='lond: '.$what.' '.$local;
1.57      www      4501: }
1.11      www      4502: 
                   4503: # -------------------------------------------------------- Escape Special Chars
                   4504: 
                   4505: sub escape {
                   4506:     my $str=shift;
                   4507:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   4508:     return $str;
                   4509: }
                   4510: 
                   4511: # ----------------------------------------------------- Un-Escape Special Chars
                   4512: 
                   4513: sub unescape {
                   4514:     my $str=shift;
                   4515:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   4516:     return $str;
                   4517: }
                   4518: 
1.1       albertel 4519: # ----------------------------------------------------------- Send USR1 to lonc
                   4520: 
                   4521: sub reconlonc {
                   4522:     my $peerfile=shift;
                   4523:     &logthis("Trying to reconnect for $peerfile");
                   4524:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                   4525:     if (my $fh=IO::File->new("$loncfile")) {
                   4526: 	my $loncpid=<$fh>;
                   4527:         chomp($loncpid);
                   4528:         if (kill 0 => $loncpid) {
                   4529: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                   4530:             kill USR1 => $loncpid;
                   4531:         } else {
1.9       www      4532: 	    &logthis(
1.190     albertel 4533:               "<font color='red'>CRITICAL: "
1.9       www      4534:              ."lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel 4535:         }
                   4536:     } else {
1.190     albertel 4537:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1       albertel 4538:     }
                   4539: }
                   4540: 
                   4541: # -------------------------------------------------- Non-critical communication
1.11      www      4542: 
1.1       albertel 4543: sub subreply {
                   4544:     my ($cmd,$server)=@_;
                   4545:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                   4546:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   4547:                                       Type    => SOCK_STREAM,
                   4548:                                       Timeout => 10)
                   4549:        or return "con_lost";
                   4550:     print $sclient "$cmd\n";
                   4551:     my $answer=<$sclient>;
                   4552:     chomp($answer);
                   4553:     if (!$answer) { $answer="con_lost"; }
                   4554:     return $answer;
                   4555: }
                   4556: 
                   4557: sub reply {
                   4558:   my ($cmd,$server)=@_;
                   4559:   my $answer;
1.115     albertel 4560:   if ($server ne $currenthostid) { 
1.1       albertel 4561:     $answer=subreply($cmd,$server);
                   4562:     if ($answer eq 'con_lost') {
                   4563: 	$answer=subreply("ping",$server);
                   4564:         if ($answer ne $server) {
1.115     albertel 4565: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1       albertel 4566:            &reconlonc("$perlvar{'lonSockDir'}/$server");
                   4567:         }
                   4568:         $answer=subreply($cmd,$server);
                   4569:     }
                   4570:   } else {
                   4571:     $answer='self_reply';
                   4572:   } 
                   4573:   return $answer;
                   4574: }
                   4575: 
1.13      www      4576: # -------------------------------------------------------------- Talk to lonsql
                   4577: 
1.234     foxr     4578: sub sql_reply {
1.12      harris41 4579:     my ($cmd)=@_;
1.234     foxr     4580:     my $answer=&sub_sql_reply($cmd);
                   4581:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 4582:     return $answer;
                   4583: }
                   4584: 
1.234     foxr     4585: sub sub_sql_reply {
1.12      harris41 4586:     my ($cmd)=@_;
                   4587:     my $unixsock="mysqlsock";
                   4588:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   4589:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   4590:                                       Type    => SOCK_STREAM,
                   4591:                                       Timeout => 10)
                   4592:        or return "con_lost";
                   4593:     print $sclient "$cmd\n";
                   4594:     my $answer=<$sclient>;
                   4595:     chomp($answer);
                   4596:     if (!$answer) { $answer="con_lost"; }
                   4597:     return $answer;
                   4598: }
                   4599: 
1.1       albertel 4600: # -------------------------------------------- Return path to profile directory
1.11      www      4601: 
1.1       albertel 4602: sub propath {
                   4603:     my ($udom,$uname)=@_;
                   4604:     $udom=~s/\W//g;
                   4605:     $uname=~s/\W//g;
1.16      www      4606:     my $subdir=$uname.'__';
1.1       albertel 4607:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4608:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   4609:     return $proname;
                   4610: } 
                   4611: 
                   4612: # --------------------------------------- Is this the home server of an author?
1.11      www      4613: 
1.1       albertel 4614: sub ishome {
                   4615:     my $author=shift;
                   4616:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   4617:     my ($udom,$uname)=split(/\//,$author);
                   4618:     my $proname=propath($udom,$uname);
                   4619:     if (-e $proname) {
                   4620: 	return 'owner';
                   4621:     } else {
                   4622:         return 'not_owner';
                   4623:     }
                   4624: }
                   4625: 
                   4626: # ======================================================= Continue main program
                   4627: # ---------------------------------------------------- Fork once and dissociate
                   4628: 
1.134     albertel 4629: my $fpid=fork;
1.1       albertel 4630: exit if $fpid;
1.29      harris41 4631: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 4632: 
1.29      harris41 4633: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 4634: 
                   4635: # ------------------------------------------------------- Write our PID on disk
                   4636: 
1.134     albertel 4637: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 4638: open (PIDSAVE,">$execdir/logs/lond.pid");
                   4639: print PIDSAVE "$$\n";
                   4640: close(PIDSAVE);
1.190     albertel 4641: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      4642: &status('Starting');
1.1       albertel 4643: 
1.106     foxr     4644: 
1.1       albertel 4645: 
                   4646: # ----------------------------------------------------- Install signal handlers
                   4647: 
1.57      www      4648: 
1.1       albertel 4649: $SIG{CHLD} = \&REAPER;
                   4650: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   4651: $SIG{HUP}  = \&HUPSMAN;
1.57      www      4652: $SIG{USR1} = \&checkchildren;
1.144     foxr     4653: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     4654: 
1.148     foxr     4655: #  Read the host hashes:
                   4656: 
                   4657: ReadHostTable;
1.106     foxr     4658: 
                   4659: # --------------------------------------------------------------
                   4660: #   Accept connections.  When a connection comes in, it is validated
                   4661: #   and if good, a child process is created to process transactions
                   4662: #   along the connection.
                   4663: 
1.1       albertel 4664: while (1) {
1.165     albertel 4665:     &status('Starting accept');
1.106     foxr     4666:     $client = $server->accept() or next;
1.165     albertel 4667:     &status('Accepted '.$client.' off to spawn');
1.106     foxr     4668:     make_new_child($client);
1.165     albertel 4669:     &status('Finished spawning');
1.1       albertel 4670: }
                   4671: 
1.212     foxr     4672: sub make_new_child {
                   4673:     my $pid;
                   4674: #    my $cipher;     # Now global
                   4675:     my $sigset;
1.178     foxr     4676: 
1.212     foxr     4677:     $client = shift;
                   4678:     &status('Starting new child '.$client);
                   4679:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   4680: 	     ")</font>");    
                   4681:     # block signal for fork
                   4682:     $sigset = POSIX::SigSet->new(SIGINT);
                   4683:     sigprocmask(SIG_BLOCK, $sigset)
                   4684:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     4685: 
1.212     foxr     4686:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     4687: 
1.212     foxr     4688:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   4689: 	                               # connection liveness.
1.178     foxr     4690: 
1.212     foxr     4691:     #
                   4692:     #  Figure out who we're talking to so we can record the peer in 
                   4693:     #  the pid hash.
                   4694:     #
                   4695:     my $caller = getpeername($client);
                   4696:     my ($port,$iaddr);
                   4697:     if (defined($caller) && length($caller) > 0) {
                   4698: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   4699:     } else {
                   4700: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   4701:     }
                   4702:     if (defined($iaddr)) {
                   4703: 	$clientip  = inet_ntoa($iaddr);
                   4704: 	Debug("Connected with $clientip");
                   4705: 	$clientdns = gethostbyaddr($iaddr, AF_INET);
                   4706: 	Debug("Connected with $clientdns by name");
                   4707:     } else {
                   4708: 	&logthis("Unable to determine clientip");
                   4709: 	$clientip='Unavailable';
                   4710:     }
                   4711:     
                   4712:     if ($pid) {
                   4713:         # Parent records the child's birth and returns.
                   4714:         sigprocmask(SIG_UNBLOCK, $sigset)
                   4715:             or die "Can't unblock SIGINT for fork: $!\n";
                   4716:         $children{$pid} = $clientip;
                   4717:         &status('Started child '.$pid);
                   4718:         return;
                   4719:     } else {
                   4720:         # Child can *not* return from this subroutine.
                   4721:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   4722:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   4723:                                 #don't get intercepted
                   4724:         $SIG{USR1}= \&logstatus;
                   4725:         $SIG{ALRM}= \&timeout;
                   4726:         $lastlog='Forked ';
                   4727:         $status='Forked';
1.178     foxr     4728: 
1.212     foxr     4729:         # unblock signals
                   4730:         sigprocmask(SIG_UNBLOCK, $sigset)
                   4731:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     4732: 
1.212     foxr     4733: #        my $tmpsnum=0;            # Now global
                   4734: #---------------------------------------------------- kerberos 5 initialization
                   4735:         &Authen::Krb5::init_context();
                   4736:         &Authen::Krb5::init_ets();
1.209     albertel 4737: 
1.212     foxr     4738: 	&status('Accepted connection');
                   4739: # =============================================================================
                   4740:             # do something with the connection
                   4741: # -----------------------------------------------------------------------------
                   4742: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     4743: 
1.212     foxr     4744: 	ReadManagerTable;	# May also be a manager!!
                   4745: 	
                   4746: 	my $clientrec=($hostid{$clientip}     ne undef);
                   4747: 	my $ismanager=($managers{$clientip}    ne undef);
                   4748: 	$clientname  = "[unknonwn]";
                   4749: 	if($clientrec) {	# Establish client type.
                   4750: 	    $ConnectionType = "client";
                   4751: 	    $clientname = $hostid{$clientip};
                   4752: 	    if($ismanager) {
                   4753: 		$ConnectionType = "both";
                   4754: 	    }
                   4755: 	} else {
                   4756: 	    $ConnectionType = "manager";
                   4757: 	    $clientname = $managers{$clientip};
                   4758: 	}
                   4759: 	my $clientok;
1.178     foxr     4760: 
1.212     foxr     4761: 	if ($clientrec || $ismanager) {
                   4762: 	    &status("Waiting for init from $clientip $clientname");
                   4763: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   4764: 		     $clientip.
                   4765: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   4766: 	    &status("Connecting $clientip  ($clientname))"); 
                   4767: 	    my $remotereq=<$client>;
                   4768: 	    chomp($remotereq);
                   4769: 	    Debug("Got init: $remotereq");
                   4770: 	    my $inikeyword = split(/:/, $remotereq);
                   4771: 	    if ($remotereq =~ /^init/) {
                   4772: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   4773: 		#
                   4774: 		#  If the remote is attempting a local init... give that a try:
                   4775: 		#
                   4776: 		my ($i, $inittype) = split(/:/, $remotereq);
1.209     albertel 4777: 
1.212     foxr     4778: 		# If the connection type is ssl, but I didn't get my
                   4779: 		# certificate files yet, then I'll drop  back to 
                   4780: 		# insecure (if allowed).
                   4781: 		
                   4782: 		if($inittype eq "ssl") {
                   4783: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   4784: 		    my $kfile       = lonssl::KeyFile;
                   4785: 		    if((!$ca)   || 
                   4786: 		       (!$cert) || 
                   4787: 		       (!$kfile)) {
                   4788: 			$inittype = ""; # This forces insecure attempt.
                   4789: 			&logthis("<font color=\"blue\"> Certificates not "
                   4790: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     4791: 		    } else {	# SSL certificates are in place so
1.212     foxr     4792: 		    }		# Leave the inittype alone.
                   4793: 		}
                   4794: 
                   4795: 		if($inittype eq "local") {
                   4796: 		    my $key = LocalConnection($client, $remotereq);
                   4797: 		    if($key) {
                   4798: 			Debug("Got local key $key");
                   4799: 			$clientok     = 1;
                   4800: 			my $cipherkey = pack("H32", $key);
                   4801: 			$cipher       = new IDEA($cipherkey);
                   4802: 			print $client "ok:local\n";
                   4803: 			&logthis('<font color="green"'
                   4804: 				 . "Successful local authentication </font>");
                   4805: 			$keymode = "local"
1.178     foxr     4806: 		    } else {
1.212     foxr     4807: 			Debug("Failed to get local key");
                   4808: 			$clientok = 0;
                   4809: 			shutdown($client, 3);
                   4810: 			close $client;
1.178     foxr     4811: 		    }
1.212     foxr     4812: 		} elsif ($inittype eq "ssl") {
                   4813: 		    my $key = SSLConnection($client);
                   4814: 		    if ($key) {
                   4815: 			$clientok = 1;
                   4816: 			my $cipherkey = pack("H32", $key);
                   4817: 			$cipher       = new IDEA($cipherkey);
                   4818: 			&logthis('<font color="green">'
                   4819: 				 ."Successfull ssl authentication with $clientname </font>");
                   4820: 			$keymode = "ssl";
                   4821: 	     
1.178     foxr     4822: 		    } else {
1.212     foxr     4823: 			$clientok = 0;
                   4824: 			close $client;
1.178     foxr     4825: 		    }
1.212     foxr     4826: 	   
                   4827: 		} else {
                   4828: 		    my $ok = InsecureConnection($client);
                   4829: 		    if($ok) {
                   4830: 			$clientok = 1;
                   4831: 			&logthis('<font color="green">'
                   4832: 				 ."Successful insecure authentication with $clientname </font>");
                   4833: 			print $client "ok\n";
                   4834: 			$keymode = "insecure";
1.178     foxr     4835: 		    } else {
1.212     foxr     4836: 			&logthis('<font color="yellow">'
                   4837: 				  ."Attempted insecure connection disallowed </font>");
                   4838: 			close $client;
                   4839: 			$clientok = 0;
1.178     foxr     4840: 			
                   4841: 		    }
                   4842: 		}
1.212     foxr     4843: 	    } else {
                   4844: 		&logthis(
                   4845: 			 "<font color='blue'>WARNING: "
                   4846: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   4847: 		&status('No init '.$clientip);
                   4848: 	    }
                   4849: 	    
                   4850: 	} else {
                   4851: 	    &logthis(
                   4852: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   4853: 	    &status('Hung up on '.$clientip);
                   4854: 	}
                   4855:  
                   4856: 	if ($clientok) {
                   4857: # ---------------- New known client connecting, could mean machine online again
                   4858: 	    
                   4859: 	    foreach my $id (keys(%hostip)) {
                   4860: 		if ($hostip{$id} ne $clientip ||
                   4861: 		    $hostip{$currenthostid} eq $clientip) {
                   4862: 		    # no need to try to do recon's to myself
                   4863: 		    next;
                   4864: 		}
                   4865: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
                   4866: 	    }
                   4867: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   4868: 	    &status('Will listen to '.$clientname);
                   4869: # ------------------------------------------------------------ Process requests
                   4870: 	    my $keep_going = 1;
                   4871: 	    my $user_input;
                   4872: 	    while(($user_input = get_request) && $keep_going) {
                   4873: 		alarm(120);
                   4874: 		Debug("Main: Got $user_input\n");
                   4875: 		$keep_going = &process_request($user_input);
1.178     foxr     4876: 		alarm(0);
1.212     foxr     4877: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     4878: 	    }
1.212     foxr     4879: 
1.59      www      4880: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     4881: 	}  else {
1.161     foxr     4882: 	    print $client "refused\n";
                   4883: 	    $client->close();
1.190     albertel 4884: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     4885: 		     ."Rejected client $clientip, closing connection</font>");
                   4886: 	}
1.212     foxr     4887:     }            
1.161     foxr     4888:     
1.1       albertel 4889: # =============================================================================
1.161     foxr     4890:     
1.190     albertel 4891:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     4892: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   4893:     
                   4894:     
                   4895:     # this exit is VERY important, otherwise the child will become
                   4896:     # a producer of more and more children, forking yourself into
                   4897:     # process death.
                   4898:     exit;
1.106     foxr     4899:     
1.78      foxr     4900: }
1.261     foxr     4901: #
                   4902: #   Determine if a user is an author for the indicated domain.
                   4903: #
                   4904: # Parameters:
                   4905: #    domain          - domain to check in .
                   4906: #    user            - Name of user to check.
                   4907: #
                   4908: # Return:
                   4909: #     1             - User is an author for domain.
                   4910: #     0             - User is not an author for domain.
                   4911: sub is_author {
                   4912:     my ($domain, $user) = @_;
                   4913: 
                   4914:     &Debug("is_author: $user @ $domain");
                   4915: 
                   4916:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   4917: 				 &GDBM_READER());
                   4918: 
                   4919:     #  Author role should show up as a key /domain/_au
1.78      foxr     4920: 
1.261     foxr     4921:     my $key   = "/$domain/_au";
                   4922:     my $value = $hashref->{$key};
1.78      foxr     4923: 
1.261     foxr     4924:     if(defined($value)) {
                   4925: 	&Debug("$user @ $domain is an author");
                   4926:     }
                   4927: 
                   4928:     return defined($value);
                   4929: }
1.78      foxr     4930: #
                   4931: #   Checks to see if the input roleput request was to set
                   4932: # an author role.  If so, invokes the lchtmldir script to set
                   4933: # up a correct public_html 
                   4934: # Parameters:
                   4935: #    request   - The request sent to the rolesput subchunk.
                   4936: #                We're looking for  /domain/_au
                   4937: #    domain    - The domain in which the user is having roles doctored.
                   4938: #    user      - Name of the user for which the role is being put.
                   4939: #    authtype  - The authentication type associated with the user.
                   4940: #
1.230     foxr     4941: sub manage_permissions
1.78      foxr     4942: {
1.192     foxr     4943: 
1.261     foxr     4944: 
1.192     foxr     4945:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     4946: 
1.261     foxr     4947:     &Debug("manage_permissions: $request $domain $user $authtype");
                   4948: 
1.78      foxr     4949:     # See if the request is of the form /$domain/_au
                   4950:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
                   4951: 	my $execdir = $perlvar{'lonDaemons'};
                   4952: 	my $userhome= "/home/$user" ;
1.134     albertel 4953: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261     foxr     4954: 	&Debug("Setting homedir permissions for $userhome");
1.78      foxr     4955: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   4956:     }
                   4957: }
1.222     foxr     4958: 
                   4959: 
                   4960: #
                   4961: #  Return the full path of a user password file, whether it exists or not.
                   4962: # Parameters:
                   4963: #   domain     - Domain in which the password file lives.
                   4964: #   user       - name of the user.
                   4965: # Returns:
                   4966: #    Full passwd path:
                   4967: #
                   4968: sub password_path {
                   4969:     my ($domain, $user) = @_;
1.264     albertel 4970:     return &propath($domain, $user).'/passwd';
1.222     foxr     4971: }
                   4972: 
                   4973: #   Password Filename
                   4974: #   Returns the path to a passwd file given domain and user... only if
                   4975: #  it exists.
                   4976: # Parameters:
                   4977: #   domain    - Domain in which to search.
                   4978: #   user      - username.
                   4979: # Returns:
                   4980: #   - If the password file exists returns its path.
                   4981: #   - If the password file does not exist, returns undefined.
                   4982: #
                   4983: sub password_filename {
                   4984:     my ($domain, $user) = @_;
                   4985: 
                   4986:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   4987: 
                   4988:     my $path  = &password_path($domain, $user);
                   4989:     Debug("PasswordFilename got path: $path");
                   4990:     if(-e $path) {
                   4991: 	return $path;
                   4992:     } else {
                   4993: 	return undef;
                   4994:     }
                   4995: }
                   4996: 
                   4997: #
                   4998: #   Rewrite the contents of the user's passwd file.
                   4999: #  Parameters:
                   5000: #    domain    - domain of the user.
                   5001: #    name      - User's name.
                   5002: #    contents  - New contents of the file.
                   5003: # Returns:
                   5004: #   0    - Failed.
                   5005: #   1    - Success.
                   5006: #
                   5007: sub rewrite_password_file {
                   5008:     my ($domain, $user, $contents) = @_;
                   5009: 
                   5010:     my $file = &password_filename($domain, $user);
                   5011:     if (defined $file) {
                   5012: 	my $pf = IO::File->new(">$file");
                   5013: 	if($pf) {
                   5014: 	    print $pf "$contents\n";
                   5015: 	    return 1;
                   5016: 	} else {
                   5017: 	    return 0;
                   5018: 	}
                   5019:     } else {
                   5020: 	return 0;
                   5021:     }
                   5022: 
                   5023: }
                   5024: 
1.78      foxr     5025: #
1.222     foxr     5026: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     5027: 
                   5028: #     Returns the authorization type or nouser if there is no such user.
                   5029: #
1.222     foxr     5030: sub get_auth_type 
1.78      foxr     5031: {
1.192     foxr     5032: 
                   5033:     my ($domain, $user)  = @_;
1.78      foxr     5034: 
1.222     foxr     5035:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     5036:     my $proname    = &propath($domain, $user); 
                   5037:     my $passwdfile = "$proname/passwd";
                   5038:     if( -e $passwdfile ) {
                   5039: 	my $pf = IO::File->new($passwdfile);
                   5040: 	my $realpassword = <$pf>;
                   5041: 	chomp($realpassword);
1.79      foxr     5042: 	Debug("Password info = $realpassword\n");
1.78      foxr     5043: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     5044: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  5045: 	return "$authtype:$contentpwd";     
1.224     foxr     5046:     } else {
1.79      foxr     5047: 	Debug("Returning nouser");
1.78      foxr     5048: 	return "nouser";
                   5049:     }
1.1       albertel 5050: }
                   5051: 
1.220     foxr     5052: #
                   5053: #  Validate a user given their domain, name and password.  This utility
                   5054: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   5055: #  to validate the login credentials of a user.
                   5056: # Parameters:
                   5057: #    $domain    - The domain being logged into (this is required due to
                   5058: #                 the capability for multihomed systems.
                   5059: #    $user      - The name of the user being validated.
                   5060: #    $password  - The user's propoposed password.
                   5061: #
                   5062: # Returns:
                   5063: #     1        - The domain,user,pasword triplet corresponds to a valid
                   5064: #                user.
                   5065: #     0        - The domain,user,password triplet is not a valid user.
                   5066: #
                   5067: sub validate_user {
                   5068:     my ($domain, $user, $password) = @_;
                   5069: 
                   5070: 
                   5071:     # Why negative ~pi you may well ask?  Well this function is about
                   5072:     # authentication, and therefore very important to get right.
                   5073:     # I've initialized the flag that determines whether or not I've 
                   5074:     # validated correctly to a value it's not supposed to get.
                   5075:     # At the end of this function. I'll ensure that it's not still that
                   5076:     # value so we don't just wind up returning some accidental value
                   5077:     # as a result of executing an unforseen code path that
1.249     foxr     5078:     # did not set $validated.  At the end of valid execution paths,
                   5079:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     5080: 
                   5081:     my $validated = -3.14159;
                   5082: 
                   5083:     #  How we authenticate is determined by the type of authentication
                   5084:     #  the user has been assigned.  If the authentication type is
                   5085:     #  "nouser", the user does not exist so we will return 0.
                   5086: 
1.222     foxr     5087:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     5088:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   5089: 
                   5090:     my $null = pack("C",0);	# Used by kerberos auth types.
                   5091: 
                   5092:     if ($howpwd ne 'nouser') {
                   5093: 
                   5094: 	if($howpwd eq "internal") { # Encrypted is in local password file.
                   5095: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
                   5096: 	}
                   5097: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   5098: 	    $contentpwd = (getpwnam($user))[1];
                   5099: 	    if($contentpwd) {
                   5100: 		if($contentpwd eq 'x') { # Shadow password file...
                   5101: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   5102: 		    open PWAUTH,  "|$pwauth_path" or
                   5103: 			die "Cannot invoke authentication";
                   5104: 		    print PWAUTH "$user\n$password\n";
                   5105: 		    close PWAUTH;
                   5106: 		    $validated = ! $?;
                   5107: 
                   5108: 		} else { 	         # Passwords in /etc/passwd. 
                   5109: 		    $validated = (crypt($password,
                   5110: 					$contentpwd) eq $contentpwd);
                   5111: 		}
                   5112: 	    } else {
                   5113: 		$validated = 0;
                   5114: 	    }
                   5115: 	}
                   5116: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   5117: 	    if(! ($password =~ /$null/) ) {
                   5118: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   5119: 							   "",
                   5120: 							   $contentpwd,,
                   5121: 							   'krbtgt',
                   5122: 							   $contentpwd,
                   5123: 							   1,
                   5124: 							   $password);
                   5125: 		if(!$k4error) {
                   5126: 		    $validated = 1;
1.224     foxr     5127: 		} else {
1.220     foxr     5128: 		    $validated = 0;
                   5129: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   5130: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   5131: 		}
1.224     foxr     5132: 	    } else {
1.220     foxr     5133: 		$validated = 0; # Password has a match with null.
                   5134: 	    }
1.224     foxr     5135: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220     foxr     5136: 	    if(!($password =~ /$null/)) { # Null password not allowed.
                   5137: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   5138: 							  .$contentpwd);
                   5139: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   5140: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   5141: 		my $credentials= &Authen::Krb5::cc_default();
                   5142: 		$credentials->initialize($krbclient);
1.270     matthew  5143: 		my $krbreturn  = &Authen::Krb5::get_in_tkt_with_password($krbclient,
1.220     foxr     5144: 									 $krbserver,
                   5145: 									 $password,
                   5146: 									 $credentials);
                   5147: 		$validated = ($krbreturn == 1);
1.224     foxr     5148: 	    } else {
1.220     foxr     5149: 		$validated = 0;
                   5150: 	    }
1.224     foxr     5151: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     5152: 	    #  Authenticate via installation specific authentcation method:
                   5153: 	    $validated = &localauth::localauth($user, 
                   5154: 					       $password, 
                   5155: 					       $contentpwd);
1.224     foxr     5156: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     5157: 	    $validated = 0;
                   5158: 	}
                   5159:     } else {
                   5160: 	$validated = 0;
                   5161:     }
                   5162:     #
                   5163:     #  $validated has the correct stat of the authentication:
                   5164:     #
                   5165: 
                   5166:     unless ($validated != -3.14159) {
1.249     foxr     5167: 	#  I >really really< want to know if this happens.
                   5168: 	#  since it indicates that user authentication is badly
                   5169: 	#  broken in some code path.
                   5170:         #
                   5171: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     5172:     }
                   5173:     return $validated;
                   5174: }
                   5175: 
                   5176: 
1.84      albertel 5177: sub addline {
                   5178:     my ($fname,$hostid,$ip,$newline)=@_;
                   5179:     my $contents;
                   5180:     my $found=0;
                   5181:     my $expr='^'.$hostid.':'.$ip.':';
                   5182:     $expr =~ s/\./\\\./g;
1.134     albertel 5183:     my $sh;
1.84      albertel 5184:     if ($sh=IO::File->new("$fname.subscription")) {
                   5185: 	while (my $subline=<$sh>) {
                   5186: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   5187: 	}
                   5188: 	$sh->close();
                   5189:     }
                   5190:     $sh=IO::File->new(">$fname.subscription");
                   5191:     if ($contents) { print $sh $contents; }
                   5192:     if ($newline) { print $sh $newline; }
                   5193:     $sh->close();
                   5194:     return $found;
1.86      www      5195: }
                   5196: 
1.234     foxr     5197: sub get_chat {
1.122     www      5198:     my ($cdom,$cname,$udom,$uname)=@_;
1.87      www      5199:     my %hash;
                   5200:     my $proname=&propath($cdom,$cname);
                   5201:     my @entries=();
1.88      albertel 5202:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   5203: 	    &GDBM_READER(),0640)) {
                   5204: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   5205: 	untie %hash;
1.123     www      5206:     }
1.124     www      5207:     my @participants=();
1.134     albertel 5208:     my $cutoff=time-60;
1.123     www      5209:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124     www      5210: 	    &GDBM_WRCREAT(),0640)) {
                   5211:         $hash{$uname.':'.$udom}=time;
1.123     www      5212:         foreach (sort keys %hash) {
                   5213: 	    if ($hash{$_}>$cutoff) {
1.124     www      5214: 		$participants[$#participants+1]='active_participant:'.$_;
1.123     www      5215:             }
                   5216:         }
                   5217:         untie %hash;
1.86      www      5218:     }
1.124     www      5219:     return (@participants,@entries);
1.86      www      5220: }
                   5221: 
1.234     foxr     5222: sub chat_add {
1.88      albertel 5223:     my ($cdom,$cname,$newchat)=@_;
                   5224:     my %hash;
                   5225:     my $proname=&propath($cdom,$cname);
                   5226:     my @entries=();
1.142     www      5227:     my $time=time;
1.88      albertel 5228:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   5229: 	    &GDBM_WRCREAT(),0640)) {
                   5230: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   5231: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   5232: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   5233: 	my $newid=$time.'_000000';
                   5234: 	if ($thentime==$time) {
                   5235: 	    $idnum=~s/^0+//;
                   5236: 	    $idnum++;
                   5237: 	    $idnum=substr('000000'.$idnum,-6,6);
                   5238: 	    $newid=$time.'_'.$idnum;
                   5239: 	}
                   5240: 	$hash{$newid}=$newchat;
                   5241: 	my $expired=$time-3600;
                   5242: 	foreach (keys %hash) {
                   5243: 	    my ($thistime)=($_=~/(\d+)\_/);
                   5244: 	    if ($thistime<$expired) {
1.89      www      5245: 		delete $hash{$_};
1.88      albertel 5246: 	    }
                   5247: 	}
                   5248: 	untie %hash;
1.142     www      5249:     }
                   5250:     {
                   5251: 	my $hfh;
                   5252: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
                   5253: 	    print $hfh "$time:".&unescape($newchat)."\n";
                   5254: 	}
1.86      www      5255:     }
1.84      albertel 5256: }
                   5257: 
                   5258: sub unsub {
                   5259:     my ($fname,$clientip)=@_;
                   5260:     my $result;
1.188     foxr     5261:     my $unsubs = 0;		# Number of successful unsubscribes:
                   5262: 
                   5263: 
                   5264:     # An old way subscriptions were handled was to have a 
                   5265:     # subscription marker file:
                   5266: 
                   5267:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     5268:     if (unlink("$fname.$clientname")) {
1.188     foxr     5269: 	$unsubs++;		# Successful unsub via marker file.
                   5270:     } 
                   5271: 
                   5272:     # The more modern way to do it is to have a subscription list
                   5273:     # file:
                   5274: 
1.84      albertel 5275:     if (-e "$fname.subscription") {
1.161     foxr     5276: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     5277: 	if ($found) { 
                   5278: 	    $unsubs++;
                   5279: 	}
                   5280:     } 
                   5281: 
                   5282:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   5283:     #  resource we can return ok:
                   5284: 
                   5285:     if($unsubs) {
                   5286: 	$result = "ok\n";
1.84      albertel 5287:     } else {
1.188     foxr     5288: 	$result = "not_subscribed\n";
1.84      albertel 5289:     }
1.188     foxr     5290: 
1.84      albertel 5291:     return $result;
                   5292: }
                   5293: 
1.101     www      5294: sub currentversion {
                   5295:     my $fname=shift;
                   5296:     my $version=-1;
                   5297:     my $ulsdir='';
                   5298:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   5299:        $ulsdir=$1;
                   5300:     }
1.114     albertel 5301:     my ($fnamere1,$fnamere2);
                   5302:     # remove version if already specified
1.101     www      5303:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 5304:     # get the bits that go before and after the version number
                   5305:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   5306: 	$fnamere1=$1;
                   5307: 	$fnamere2='.'.$2;
                   5308:     }
1.101     www      5309:     if (-e $fname) { $version=1; }
                   5310:     if (-e $ulsdir) {
1.134     albertel 5311: 	if(-d $ulsdir) {
                   5312: 	    if (opendir(LSDIR,$ulsdir)) {
                   5313: 		my $ulsfn;
                   5314: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      5315: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 5316: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   5317: 		    unless (-l $thisfile) {
1.160     www      5318: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 5319: 			    if ($1>$version) { $version=$1; }
                   5320: 			}
                   5321: 		    }
                   5322: 		}
                   5323: 		closedir(LSDIR);
                   5324: 		$version++;
                   5325: 	    }
                   5326: 	}
                   5327:     }
                   5328:     return $version;
1.101     www      5329: }
                   5330: 
                   5331: sub thisversion {
                   5332:     my $fname=shift;
                   5333:     my $version=-1;
                   5334:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   5335: 	$version=$1;
                   5336:     }
                   5337:     return $version;
                   5338: }
                   5339: 
1.84      albertel 5340: sub subscribe {
                   5341:     my ($userinput,$clientip)=@_;
                   5342:     my $result;
                   5343:     my ($cmd,$fname)=split(/:/,$userinput);
                   5344:     my $ownership=&ishome($fname);
                   5345:     if ($ownership eq 'owner') {
1.101     www      5346: # explitly asking for the current version?
                   5347:         unless (-e $fname) {
                   5348:             my $currentversion=&currentversion($fname);
                   5349: 	    if (&thisversion($fname)==$currentversion) {
                   5350:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   5351: 		    my $root=$1;
                   5352:                     my $extension=$2;
                   5353:                     symlink($root.'.'.$extension,
                   5354:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      5355:                     unless ($extension=~/\.meta$/) {
                   5356:                        symlink($root.'.'.$extension.'.meta',
                   5357:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   5358: 		    }
1.101     www      5359:                 }
                   5360:             }
                   5361:         }
1.84      albertel 5362: 	if (-e $fname) {
                   5363: 	    if (-d $fname) {
                   5364: 		$result="directory\n";
                   5365: 	    } else {
1.161     foxr     5366: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 5367: 		my $now=time;
1.161     foxr     5368: 		my $found=&addline($fname,$clientname,$clientip,
                   5369: 				   "$clientname:$clientip:$now\n");
1.84      albertel 5370: 		if ($found) { $result="$fname\n"; }
                   5371: 		# if they were subscribed to only meta data, delete that
                   5372:                 # subscription, when you subscribe to a file you also get
                   5373:                 # the metadata
                   5374: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   5375: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
                   5376: 		$fname="http://$thisserver/".$fname;
                   5377: 		$result="$fname\n";
                   5378: 	    }
                   5379: 	} else {
                   5380: 	    $result="not_found\n";
                   5381: 	}
                   5382:     } else {
                   5383: 	$result="rejected\n";
                   5384:     }
                   5385:     return $result;
                   5386: }
1.91      albertel 5387: 
                   5388: sub make_passwd_file {
1.98      foxr     5389:     my ($uname, $umode,$npass,$passfilename)=@_;
1.91      albertel 5390:     my $result="ok\n";
                   5391:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   5392: 	{
                   5393: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5394: 	    if ($pf) {
                   5395: 		print $pf "$umode:$npass\n";
                   5396: 	    } else {
                   5397: 		$result = "pass_file_failed_error";
                   5398: 	    }
1.91      albertel 5399: 	}
                   5400:     } elsif ($umode eq 'internal') {
                   5401: 	my $salt=time;
                   5402: 	$salt=substr($salt,6,2);
                   5403: 	my $ncpass=crypt($npass,$salt);
                   5404: 	{
                   5405: 	    &Debug("Creating internal auth");
                   5406: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5407: 	    if($pf) {
                   5408: 		print $pf "internal:$ncpass\n"; 
                   5409: 	    } else {
                   5410: 		$result = "pass_file_failed_error";
                   5411: 	    }
1.91      albertel 5412: 	}
                   5413:     } elsif ($umode eq 'localauth') {
                   5414: 	{
                   5415: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5416: 	    if($pf) {
                   5417: 		print $pf "localauth:$npass\n";
                   5418: 	    } else {
                   5419: 		$result = "pass_file_failed_error";
                   5420: 	    }
1.91      albertel 5421: 	}
                   5422:     } elsif ($umode eq 'unix') {
                   5423: 	{
1.186     foxr     5424: 	    #
                   5425: 	    #  Don't allow the creation of privileged accounts!!! that would
                   5426: 	    #  be real bad!!!
                   5427: 	    #
                   5428: 	    my $uid = getpwnam($uname);
                   5429: 	    if((defined $uid) && ($uid == 0)) {
                   5430: 		&logthis(">>>Attempted to create privilged account blocked");
                   5431: 		return "no_priv_account_error\n";
                   5432: 	    }
                   5433: 
1.223     foxr     5434: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224     foxr     5435: 
                   5436: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
1.91      albertel 5437: 	    {
                   5438: 		&Debug("Executing external: ".$execpath);
1.98      foxr     5439: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  5440: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 5441: 		print $se "$uname\n";
                   5442: 		print $se "$npass\n";
                   5443: 		print $se "$npass\n";
1.223     foxr     5444: 		print $se "$lc_error_file\n"; # Status -> unique file.
1.97      foxr     5445: 	    }
1.223     foxr     5446: 	    my $error = IO::File->new("< $lc_error_file");
                   5447: 	    my $useraddok = <$error>;
                   5448: 	    $error->close;
                   5449: 	    unlink($lc_error_file);
                   5450: 
                   5451: 	    chomp $useraddok;
                   5452: 
1.97      foxr     5453: 	    if($useraddok > 0) {
1.223     foxr     5454: 		my $error_text = &lcuseraddstrerror($useraddok);
                   5455: 		&logthis("Failed lcuseradd: $error_text");
                   5456: 		$result = "lcuseradd_failed:$error_text\n";
1.224     foxr     5457: 	    }  else {
1.223     foxr     5458: 		my $pf = IO::File->new(">$passfilename");
1.261     foxr     5459: 		if($pf) {
                   5460: 		    print $pf "unix:\n";
                   5461: 		} else {
                   5462: 		    $result = "pass_file_failed_error";
                   5463: 		}
1.91      albertel 5464: 	    }
                   5465: 	}
                   5466:     } elsif ($umode eq 'none') {
                   5467: 	{
1.223     foxr     5468: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     5469: 	    if($pf) {
                   5470: 		print $pf "none:\n";
                   5471: 	    } else {
                   5472: 		$result = "pass_file_failed_error";
                   5473: 	    }
1.91      albertel 5474: 	}
                   5475:     } else {
                   5476: 	$result="auth_mode_error\n";
                   5477:     }
                   5478:     return $result;
1.121     albertel 5479: }
                   5480: 
1.265     albertel 5481: sub convert_photo {
                   5482:     my ($start,$dest)=@_;
                   5483:     system("convert $start $dest");
                   5484: }
                   5485: 
1.121     albertel 5486: sub sethost {
                   5487:     my ($remotereq) = @_;
                   5488:     my (undef,$hostid)=split(/:/,$remotereq);
                   5489:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
                   5490:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200     matthew  5491: 	$currenthostid  =$hostid;
1.121     albertel 5492: 	$currentdomainid=$hostdom{$hostid};
                   5493: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
                   5494:     } else {
                   5495: 	&logthis("Requested host id $hostid not an alias of ".
                   5496: 		 $perlvar{'lonHostID'}." refusing connection");
                   5497: 	return 'unable_to_set';
                   5498:     }
                   5499:     return 'ok';
                   5500: }
                   5501: 
                   5502: sub version {
                   5503:     my ($userinput)=@_;
                   5504:     $remoteVERSION=(split(/:/,$userinput))[1];
                   5505:     return "version:$VERSION";
1.127     albertel 5506: }
1.178     foxr     5507: 
1.128     albertel 5508: #There is a copy of this in lonnet.pm
1.127     albertel 5509: sub userload {
                   5510:     my $numusers=0;
                   5511:     {
                   5512: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   5513: 	my $filename;
                   5514: 	my $curtime=time;
                   5515: 	while ($filename=readdir(LONIDS)) {
                   5516: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.138     albertel 5517: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159     albertel 5518: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.127     albertel 5519: 	}
                   5520: 	closedir(LONIDS);
                   5521:     }
                   5522:     my $userloadpercent=0;
                   5523:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   5524:     if ($maxuserload) {
1.129     albertel 5525: 	$userloadpercent=100*$numusers/$maxuserload;
1.127     albertel 5526:     }
1.130     albertel 5527:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127     albertel 5528:     return $userloadpercent;
1.91      albertel 5529: }
                   5530: 
1.205     raeburn  5531: # Routines for serializing arrays and hashes (copies from lonnet)
                   5532: 
                   5533: sub array2str {
                   5534:   my (@array) = @_;
                   5535:   my $result=&arrayref2str(\@array);
                   5536:   $result=~s/^__ARRAY_REF__//;
                   5537:   $result=~s/__END_ARRAY_REF__$//;
                   5538:   return $result;
                   5539: }
                   5540:                                                                                  
                   5541: sub arrayref2str {
                   5542:   my ($arrayref) = @_;
                   5543:   my $result='__ARRAY_REF__';
                   5544:   foreach my $elem (@$arrayref) {
                   5545:     if(ref($elem) eq 'ARRAY') {
                   5546:       $result.=&arrayref2str($elem).'&';
                   5547:     } elsif(ref($elem) eq 'HASH') {
                   5548:       $result.=&hashref2str($elem).'&';
                   5549:     } elsif(ref($elem)) {
                   5550:       #print("Got a ref of ".(ref($elem))." skipping.");
                   5551:     } else {
                   5552:       $result.=&escape($elem).'&';
                   5553:     }
                   5554:   }
                   5555:   $result=~s/\&$//;
                   5556:   $result .= '__END_ARRAY_REF__';
                   5557:   return $result;
                   5558: }
                   5559:                                                                                  
                   5560: sub hash2str {
                   5561:   my (%hash) = @_;
                   5562:   my $result=&hashref2str(\%hash);
                   5563:   $result=~s/^__HASH_REF__//;
                   5564:   $result=~s/__END_HASH_REF__$//;
                   5565:   return $result;
                   5566: }
                   5567:                                                                                  
                   5568: sub hashref2str {
                   5569:   my ($hashref)=@_;
                   5570:   my $result='__HASH_REF__';
                   5571:   foreach (sort(keys(%$hashref))) {
                   5572:     if (ref($_) eq 'ARRAY') {
                   5573:       $result.=&arrayref2str($_).'=';
                   5574:     } elsif (ref($_) eq 'HASH') {
                   5575:       $result.=&hashref2str($_).'=';
                   5576:     } elsif (ref($_)) {
                   5577:       $result.='=';
                   5578:       #print("Got a ref of ".(ref($_))." skipping.");
                   5579:     } else {
                   5580:         if ($_) {$result.=&escape($_).'=';} else { last; }
                   5581:     }
                   5582: 
                   5583:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   5584:       $result.=&arrayref2str($hashref->{$_}).'&';
                   5585:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   5586:       $result.=&hashref2str($hashref->{$_}).'&';
                   5587:     } elsif(ref($hashref->{$_})) {
                   5588:        $result.='&';
                   5589:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
                   5590:     } else {
                   5591:       $result.=&escape($hashref->{$_}).'&';
                   5592:     }
                   5593:   }
                   5594:   $result=~s/\&$//;
                   5595:   $result .= '__END_HASH_REF__';
                   5596:   return $result;
                   5597: }
1.200     matthew  5598: 
1.61      harris41 5599: # ----------------------------------- POD (plain old documentation, CPAN style)
                   5600: 
                   5601: =head1 NAME
                   5602: 
                   5603: lond - "LON Daemon" Server (port "LOND" 5663)
                   5604: 
                   5605: =head1 SYNOPSIS
                   5606: 
1.74      harris41 5607: Usage: B<lond>
                   5608: 
                   5609: Should only be run as user=www.  This is a command-line script which
                   5610: is invoked by B<loncron>.  There is no expectation that a typical user
                   5611: will manually start B<lond> from the command-line.  (In other words,
                   5612: DO NOT START B<lond> YOURSELF.)
1.61      harris41 5613: 
                   5614: =head1 DESCRIPTION
                   5615: 
1.74      harris41 5616: There are two characteristics associated with the running of B<lond>,
                   5617: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   5618: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   5619: subscriptions, etc).  These are described in two large
                   5620: sections below.
                   5621: 
                   5622: B<PROCESS MANAGEMENT>
                   5623: 
1.61      harris41 5624: Preforker - server who forks first. Runs as a daemon. HUPs.
                   5625: Uses IDEA encryption
                   5626: 
1.74      harris41 5627: B<lond> forks off children processes that correspond to the other servers
                   5628: in the network.  Management of these processes can be done at the
                   5629: parent process level or the child process level.
                   5630: 
                   5631: B<logs/lond.log> is the location of log messages.
                   5632: 
                   5633: The process management is now explained in terms of linux shell commands,
                   5634: subroutines internal to this code, and signal assignments:
                   5635: 
                   5636: =over 4
                   5637: 
                   5638: =item *
                   5639: 
                   5640: PID is stored in B<logs/lond.pid>
                   5641: 
                   5642: This is the process id number of the parent B<lond> process.
                   5643: 
                   5644: =item *
                   5645: 
                   5646: SIGTERM and SIGINT
                   5647: 
                   5648: Parent signal assignment:
                   5649:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   5650: 
                   5651: Child signal assignment:
                   5652:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   5653: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   5654:  to restart a new child.)
                   5655: 
                   5656: Command-line invocations:
                   5657:  B<kill> B<-s> SIGTERM I<PID>
                   5658:  B<kill> B<-s> SIGINT I<PID>
                   5659: 
                   5660: Subroutine B<HUNTSMAN>:
                   5661:  This is only invoked for the B<lond> parent I<PID>.
                   5662: This kills all the children, and then the parent.
                   5663: The B<lonc.pid> file is cleared.
                   5664: 
                   5665: =item *
                   5666: 
                   5667: SIGHUP
                   5668: 
                   5669: Current bug:
                   5670:  This signal can only be processed the first time
                   5671: on the parent process.  Subsequent SIGHUP signals
                   5672: have no effect.
                   5673: 
                   5674: Parent signal assignment:
                   5675:  $SIG{HUP}  = \&HUPSMAN;
                   5676: 
                   5677: Child signal assignment:
                   5678:  none (nothing happens)
                   5679: 
                   5680: Command-line invocations:
                   5681:  B<kill> B<-s> SIGHUP I<PID>
                   5682: 
                   5683: Subroutine B<HUPSMAN>:
                   5684:  This is only invoked for the B<lond> parent I<PID>,
                   5685: This kills all the children, and then the parent.
                   5686: The B<lond.pid> file is cleared.
                   5687: 
                   5688: =item *
                   5689: 
                   5690: SIGUSR1
                   5691: 
                   5692: Parent signal assignment:
                   5693:  $SIG{USR1} = \&USRMAN;
                   5694: 
                   5695: Child signal assignment:
                   5696:  $SIG{USR1}= \&logstatus;
                   5697: 
                   5698: Command-line invocations:
                   5699:  B<kill> B<-s> SIGUSR1 I<PID>
                   5700: 
                   5701: Subroutine B<USRMAN>:
                   5702:  When invoked for the B<lond> parent I<PID>,
                   5703: SIGUSR1 is sent to all the children, and the status of
                   5704: each connection is logged.
1.144     foxr     5705: 
                   5706: =item *
                   5707: 
                   5708: SIGUSR2
                   5709: 
                   5710: Parent Signal assignment:
                   5711:     $SIG{USR2} = \&UpdateHosts
                   5712: 
                   5713: Child signal assignment:
                   5714:     NONE
                   5715: 
1.74      harris41 5716: 
                   5717: =item *
                   5718: 
                   5719: SIGCHLD
                   5720: 
                   5721: Parent signal assignment:
                   5722:  $SIG{CHLD} = \&REAPER;
                   5723: 
                   5724: Child signal assignment:
                   5725:  none
                   5726: 
                   5727: Command-line invocations:
                   5728:  B<kill> B<-s> SIGCHLD I<PID>
                   5729: 
                   5730: Subroutine B<REAPER>:
                   5731:  This is only invoked for the B<lond> parent I<PID>.
                   5732: Information pertaining to the child is removed.
                   5733: The socket port is cleaned up.
                   5734: 
                   5735: =back
                   5736: 
                   5737: B<SERVER-SIDE ACTIVITIES>
                   5738: 
                   5739: Server-side information can be accepted in an encrypted or non-encrypted
                   5740: method.
                   5741: 
                   5742: =over 4
                   5743: 
                   5744: =item ping
                   5745: 
                   5746: Query a client in the hosts.tab table; "Are you there?"
                   5747: 
                   5748: =item pong
                   5749: 
                   5750: Respond to a ping query.
                   5751: 
                   5752: =item ekey
                   5753: 
                   5754: Read in encrypted key, make cipher.  Respond with a buildkey.
                   5755: 
                   5756: =item load
                   5757: 
                   5758: Respond with CPU load based on a computation upon /proc/loadavg.
                   5759: 
                   5760: =item currentauth
                   5761: 
                   5762: Reply with current authentication information (only over an
                   5763: encrypted channel).
                   5764: 
                   5765: =item auth
                   5766: 
                   5767: Only over an encrypted channel, reply as to whether a user's
                   5768: authentication information can be validated.
                   5769: 
                   5770: =item passwd
                   5771: 
                   5772: Allow for a password to be set.
                   5773: 
                   5774: =item makeuser
                   5775: 
                   5776: Make a user.
                   5777: 
                   5778: =item passwd
                   5779: 
                   5780: Allow for authentication mechanism and password to be changed.
                   5781: 
                   5782: =item home
1.61      harris41 5783: 
1.74      harris41 5784: Respond to a question "are you the home for a given user?"
                   5785: 
                   5786: =item update
                   5787: 
                   5788: Update contents of a subscribed resource.
                   5789: 
                   5790: =item unsubscribe
                   5791: 
                   5792: The server is unsubscribing from a resource.
                   5793: 
                   5794: =item subscribe
                   5795: 
                   5796: The server is subscribing to a resource.
                   5797: 
                   5798: =item log
                   5799: 
                   5800: Place in B<logs/lond.log>
                   5801: 
                   5802: =item put
                   5803: 
                   5804: stores hash in namespace
                   5805: 
1.230     foxr     5806: =item rolesputy
1.74      harris41 5807: 
                   5808: put a role into a user's environment
                   5809: 
                   5810: =item get
                   5811: 
                   5812: returns hash with keys from array
                   5813: reference filled in from namespace
                   5814: 
                   5815: =item eget
                   5816: 
                   5817: returns hash with keys from array
                   5818: reference filled in from namesp (encrypts the return communication)
                   5819: 
                   5820: =item rolesget
                   5821: 
                   5822: get a role from a user's environment
                   5823: 
                   5824: =item del
                   5825: 
                   5826: deletes keys out of array from namespace
                   5827: 
                   5828: =item keys
                   5829: 
                   5830: returns namespace keys
                   5831: 
                   5832: =item dump
                   5833: 
                   5834: dumps the complete (or key matching regexp) namespace into a hash
                   5835: 
                   5836: =item store
                   5837: 
                   5838: stores hash permanently
                   5839: for this url; hashref needs to be given and should be a \%hashname; the
                   5840: remaining args aren't required and if they aren't passed or are '' they will
                   5841: be derived from the ENV
                   5842: 
                   5843: =item restore
                   5844: 
                   5845: returns a hash for a given url
                   5846: 
                   5847: =item querysend
                   5848: 
                   5849: Tells client about the lonsql process that has been launched in response
                   5850: to a sent query.
                   5851: 
                   5852: =item queryreply
                   5853: 
                   5854: Accept information from lonsql and make appropriate storage in temporary
                   5855: file space.
                   5856: 
                   5857: =item idput
                   5858: 
                   5859: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   5860: for each student, defined perhaps by the institutional Registrar.)
                   5861: 
                   5862: =item idget
                   5863: 
                   5864: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   5865: for each student, defined perhaps by the institutional Registrar.)
                   5866: 
                   5867: =item tmpput
                   5868: 
                   5869: Accept and store information in temporary space.
                   5870: 
                   5871: =item tmpget
                   5872: 
                   5873: Send along temporarily stored information.
                   5874: 
                   5875: =item ls
                   5876: 
                   5877: List part of a user's directory.
                   5878: 
1.135     foxr     5879: =item pushtable
                   5880: 
                   5881: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   5882: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   5883: must be restored manually in case of a problem with the new table file.
                   5884: pushtable requires that the request be encrypted and validated via
                   5885: ValidateManager.  The form of the command is:
                   5886: enc:pushtable tablename <tablecontents> \n
                   5887: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   5888: cleartext newline.
                   5889: 
1.74      harris41 5890: =item Hanging up (exit or init)
                   5891: 
                   5892: What to do when a client tells the server that they (the client)
                   5893: are leaving the network.
                   5894: 
                   5895: =item unknown command
                   5896: 
                   5897: If B<lond> is sent an unknown command (not in the list above),
                   5898: it replys to the client "unknown_cmd".
1.135     foxr     5899: 
1.74      harris41 5900: 
                   5901: =item UNKNOWN CLIENT
                   5902: 
                   5903: If the anti-spoofing algorithm cannot verify the client,
                   5904: the client is rejected (with a "refused" message sent
                   5905: to the client, and the connection is closed.
                   5906: 
                   5907: =back
1.61      harris41 5908: 
                   5909: =head1 PREREQUISITES
                   5910: 
                   5911: IO::Socket
                   5912: IO::File
                   5913: Apache::File
                   5914: Symbol
                   5915: POSIX
                   5916: Crypt::IDEA
                   5917: LWP::UserAgent()
                   5918: GDBM_File
                   5919: Authen::Krb4
1.91      albertel 5920: Authen::Krb5
1.61      harris41 5921: 
                   5922: =head1 COREQUISITES
                   5923: 
                   5924: =head1 OSNAMES
                   5925: 
                   5926: linux
                   5927: 
                   5928: =head1 SCRIPT CATEGORIES
                   5929: 
                   5930: Server/Process
                   5931: 
                   5932: =cut

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