Annotation of loncom/lond, revision 1.265

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

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