Annotation of loncom/lond, revision 1.264

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

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