Annotation of loncom/lond, revision 1.305.2.2

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

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