Annotation of loncom/lond, revision 1.274

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>
500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.