Annotation of loncom/lond, revision 1.254

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

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