Annotation of loncom/lond, revision 1.305.2.5

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.5! albertel    5: # $Id: lond,v 1.305.2.4 2006/02/10 09:48:17 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.5! albertel   64: my $VERSION='$Revision: 1.305.2.4 $'; #' 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.305.2.3  albertel 4321: # Get domain specific conditions for import of student photographs to a course
                   4322: #
                   4323: # Retrieves information from photo_permission subroutine in localenroll.
                   4324: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   4325: # required to accept conditions of use (yes/no).
                   4326: #
                   4327: #    
                   4328: sub photo_permission_handler {
                   4329:     my ($cmd, $tail, $client)   = @_;
                   4330:     my $userinput               = "$cmd:$tail";
                   4331:     my $cdom = $tail;
                   4332:     my ($perm_reqd,$conditions);
1.305.2.4  albertel 4333:     my $outcome;
                   4334:     eval {
                   4335: 	local($SIG{__DIE__})='DEFAULT';
                   4336: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   4337: 						  \$conditions);
                   4338:     };
                   4339:     if (!$@) {
                   4340: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   4341: 	       $userinput);
                   4342:     } else {
                   4343: 	&Failure($client,"unknown_cmd\n",$userinput);
                   4344:     }
                   4345:     return 1;
1.305.2.3  albertel 4346: }
                   4347: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   4348: 
                   4349: #
                   4350: # Checks if student photo is available for a user in the domain, in the user's
                   4351: # directory (in /userfiles/internal/studentphoto.jpg).
                   4352: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   4353: # the student's photo.   
                   4354: 
                   4355: sub photo_check_handler {
                   4356:     my ($cmd, $tail, $client)   = @_;
                   4357:     my $userinput               = "$cmd:$tail";
                   4358:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   4359:     $udom = &unescape($udom);
                   4360:     $uname = &unescape($uname);
                   4361:     $pid = &unescape($pid);
                   4362:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   4363:     if (!-e $path) {
                   4364:         &mkpath($path);
                   4365:     }
                   4366:     my $response;
                   4367:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   4368:     $result .= ':'.$response;
                   4369:     &Reply($client, &escape($result)."\n",$userinput);
1.305.2.4  albertel 4370:     return 1;
1.305.2.3  albertel 4371: }
                   4372: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   4373: 
                   4374: #
                   4375: # Retrieve information from localenroll about whether to provide a button     
                   4376: # for users who have enbled import of student photos to initiate an 
                   4377: # update of photo files for registered students. Also include 
                   4378: # comment to display alongside button.  
                   4379: 
                   4380: sub photo_choice_handler {
                   4381:     my ($cmd, $tail, $client) = @_;
                   4382:     my $userinput             = "$cmd:$tail";
                   4383:     my $cdom                  = &unescape($tail);
1.305.2.4  albertel 4384:     my ($update,$comment);
                   4385:     eval {
                   4386: 	local($SIG{__DIE__})='DEFAULT';
                   4387: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   4388:     };
                   4389:     if (!$@) {
                   4390: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   4391:     } else {
                   4392: 	&Failure($client,"unknown_cmd\n",$userinput);
                   4393:     }
                   4394:     return 1;
1.305.2.3  albertel 4395: }
                   4396: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   4397: 
1.265     albertel 4398: #
                   4399: # Gets a student's photo to exist (in the correct image type) in the user's 
                   4400: # directory.
                   4401: # Formal Parameters:
                   4402: #    $cmd     - The command request that got us dispatched.
                   4403: #    $tail    - A colon separated set of words that will be split into:
                   4404: #               $domain - student's domain
                   4405: #               $uname  - student username
                   4406: #               $type   - image type desired
                   4407: #    $client  - The socket open on the client.
                   4408: # Returns:
                   4409: #    1 - continue processing.
1.305.2.3  albertel 4410: 
1.265     albertel 4411: sub student_photo_handler {
                   4412:     my ($cmd, $tail, $client) = @_;
1.305.2.3  albertel 4413:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 4414: 
1.305.2.3  albertel 4415:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   4416:     my $filename = 'studentphoto.'.$ext;
                   4417:     if ($type eq 'thumbnail') {
                   4418:         $filename = 'studentphoto_tn.'.$ext;
                   4419:     }
                   4420:     if (-e $path.$filename) {
1.265     albertel 4421: 	&Reply($client,"ok\n","$cmd:$tail");
                   4422: 	return 1;
                   4423:     }
                   4424:     &mkpath($path);
1.305.2.3  albertel 4425:     my $file;
                   4426:     if ($type eq 'thumbnail') {
1.305.2.4  albertel 4427: 	eval {
                   4428: 	    local($SIG{__DIE__})='DEFAULT';
                   4429: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   4430: 	};
1.305.2.3  albertel 4431:     } else {
                   4432:         $file=&localstudentphoto::fetch($domain,$uname);
                   4433:     }
1.265     albertel 4434:     if (!$file) {
                   4435: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   4436: 	return 1;
                   4437:     }
1.305.2.3  albertel 4438:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   4439:     if (-e $path.$filename) {
1.265     albertel 4440: 	&Reply($client,"ok\n","$cmd:$tail");
                   4441: 	return 1;
                   4442:     }
                   4443:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   4444:     return 1;
                   4445: }
                   4446: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     4447: 
1.264     albertel 4448: # mkpath makes all directories for a file, expects an absolute path with a
                   4449: # file or a trailing / if just a dir is passed
                   4450: # returns 1 on success 0 on failure
                   4451: sub mkpath {
                   4452:     my ($file)=@_;
                   4453:     my @parts=split(/\//,$file,-1);
                   4454:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   4455:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 4456: 	$now.='/'.$parts[$i]; 
1.264     albertel 4457: 	if (!-e $now) {
                   4458: 	    if  (!mkdir($now,0770)) { return 0; }
                   4459: 	}
                   4460:     }
                   4461:     return 1;
                   4462: }
                   4463: 
1.207     foxr     4464: #---------------------------------------------------------------
                   4465: #
                   4466: #   Getting, decoding and dispatching requests:
                   4467: #
                   4468: #
                   4469: #   Get a Request:
                   4470: #   Gets a Request message from the client.  The transaction
                   4471: #   is defined as a 'line' of text.  We remove the new line
                   4472: #   from the text line.  
1.226     foxr     4473: #
1.211     albertel 4474: sub get_request {
1.207     foxr     4475:     my $input = <$client>;
                   4476:     chomp($input);
1.226     foxr     4477: 
1.234     foxr     4478:     &Debug("get_request: Request = $input\n");
1.207     foxr     4479: 
                   4480:     &status('Processing '.$clientname.':'.$input);
                   4481: 
                   4482:     return $input;
                   4483: }
1.212     foxr     4484: #---------------------------------------------------------------
                   4485: #
                   4486: #  Process a request.  This sub should shrink as each action
                   4487: #  gets farmed out into a separat sub that is registered 
                   4488: #  with the dispatch hash.  
                   4489: #
                   4490: # Parameters:
                   4491: #    user_input   - The request received from the client (lonc).
                   4492: # Returns:
                   4493: #    true to keep processing, false if caller should exit.
                   4494: #
                   4495: sub process_request {
                   4496:     my ($userinput) = @_;      # Easier for now to break style than to
                   4497:                                 # fix all the userinput -> user_input.
                   4498:     my $wasenc    = 0;		# True if request was encrypted.
                   4499: # ------------------------------------------------------------ See if encrypted
                   4500:     if ($userinput =~ /^enc/) {
                   4501: 	$userinput = decipher($userinput);
                   4502: 	$wasenc=1;
                   4503: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     4504: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     4505: 	    return 0;
                   4506: 	}
                   4507:     }
                   4508:     Debug("process_request: $userinput\n");
                   4509:     
1.213     foxr     4510:     #  
                   4511:     #   The 'correct way' to add a command to lond is now to
                   4512:     #   write a sub to execute it and Add it to the command dispatch
                   4513:     #   hash via a call to register_handler..  The comments to that
                   4514:     #   sub should give you enough to go on to show how to do this
                   4515:     #   along with the examples that are building up as this code
                   4516:     #   is getting refactored.   Until all branches of the
                   4517:     #   if/elseif monster below have been factored out into
                   4518:     #   separate procesor subs, if the dispatch hash is missing
                   4519:     #   the command keyword, we will fall through to the remainder
                   4520:     #   of the if/else chain below in order to keep this thing in 
                   4521:     #   working order throughout the transmogrification.
                   4522: 
                   4523:     my ($command, $tail) = split(/:/, $userinput, 2);
                   4524:     chomp($command);
                   4525:     chomp($tail);
                   4526:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     4527:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   4528:     if(!$tail) {
                   4529: 	$tail ="";		# defined but blank.
                   4530:     }
1.213     foxr     4531: 
                   4532:     &Debug("Command received: $command, encoded = $wasenc");
                   4533: 
                   4534:     if(defined $Dispatcher{$command}) {
                   4535: 
                   4536: 	my $dispatch_info = $Dispatcher{$command};
                   4537: 	my $handler       = $$dispatch_info[0];
                   4538: 	my $need_encode   = $$dispatch_info[1];
                   4539: 	my $client_types  = $$dispatch_info[2];
                   4540: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   4541: 	      ."ClientType $client_types");
                   4542:       
                   4543: 	#  Validate the request:
                   4544:       
                   4545: 	my $ok = 1;
                   4546: 	my $requesterprivs = 0;
                   4547: 	if(&isClient()) {
                   4548: 	    $requesterprivs |= $CLIENT_OK;
                   4549: 	}
                   4550: 	if(&isManager()) {
                   4551: 	    $requesterprivs |= $MANAGER_OK;
                   4552: 	}
                   4553: 	if($need_encode && (!$wasenc)) {
                   4554: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   4555: 	    $ok = 0;
                   4556: 	}
                   4557: 	if(($client_types & $requesterprivs) == 0) {
                   4558: 	    Debug("Client not privileged to do this operation");
                   4559: 	    $ok = 0;
                   4560: 	}
                   4561: 
                   4562: 	if($ok) {
                   4563: 	    Debug("Dispatching to handler $command $tail");
                   4564: 	    my $keep_going = &$handler($command, $tail, $client);
                   4565: 	    return $keep_going;
                   4566: 	} else {
                   4567: 	    Debug("Refusing to dispatch because client did not match requirements");
                   4568: 	    Failure($client, "refused\n", $userinput);
                   4569: 	    return 1;
                   4570: 	}
                   4571: 
                   4572:     }    
                   4573: 
1.262     foxr     4574:     print $client "unknown_cmd\n";
1.212     foxr     4575: # -------------------------------------------------------------------- complete
                   4576:     Debug("process_request - returning 1");
                   4577:     return 1;
                   4578: }
1.207     foxr     4579: #
                   4580: #   Decipher encoded traffic
                   4581: #  Parameters:
                   4582: #     input      - Encoded data.
                   4583: #  Returns:
                   4584: #     Decoded data or undef if encryption key was not yet negotiated.
                   4585: #  Implicit input:
                   4586: #     cipher  - This global holds the negotiated encryption key.
                   4587: #
1.211     albertel 4588: sub decipher {
1.207     foxr     4589:     my ($input)  = @_;
                   4590:     my $output = '';
1.212     foxr     4591:     
                   4592:     
1.207     foxr     4593:     if($cipher) {
                   4594: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   4595: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   4596: 	    $output .= 
                   4597: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   4598: 	}
                   4599: 	return substr($output, 0, $enclength);
                   4600:     } else {
                   4601: 	return undef;
                   4602:     }
                   4603: }
                   4604: 
                   4605: #
                   4606: #   Register a command processor.  This function is invoked to register a sub
                   4607: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   4608: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   4609: #   as well:
                   4610: #    - Is the keyword recognized.
                   4611: #    - Is the proper client type attempting the request.
                   4612: #    - Is the request encrypted if it has to be.
                   4613: #   Parameters:
                   4614: #    $request_name         - Name of the request being registered.
                   4615: #                           This is the command request that will match
                   4616: #                           against the hash keywords to lookup the information
                   4617: #                           associated with the dispatch information.
                   4618: #    $procedure           - Reference to a sub to call to process the request.
                   4619: #                           All subs get called as follows:
                   4620: #                             Procedure($cmd, $tail, $replyfd, $key)
                   4621: #                             $cmd    - the actual keyword that invoked us.
                   4622: #                             $tail   - the tail of the request that invoked us.
                   4623: #                             $replyfd- File descriptor connected to the client
                   4624: #    $must_encode          - True if the request must be encoded to be good.
                   4625: #    $client_ok            - True if it's ok for a client to request this.
                   4626: #    $manager_ok           - True if it's ok for a manager to request this.
                   4627: # Side effects:
                   4628: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   4629: #      - On failure, the program will die as it's a bad internal bug to try to 
                   4630: #        register a duplicate command handler.
                   4631: #
1.211     albertel 4632: sub register_handler {
1.212     foxr     4633:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     4634: 
                   4635:     #  Don't allow duplication#
                   4636:    
                   4637:     if (defined $Dispatcher{$request_name}) {
                   4638: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   4639:     }
                   4640:     #   Build the client type mask:
                   4641:     
                   4642:     my $client_type_mask = 0;
                   4643:     if($client_ok) {
                   4644: 	$client_type_mask  |= $CLIENT_OK;
                   4645:     }
                   4646:     if($manager_ok) {
                   4647: 	$client_type_mask  |= $MANAGER_OK;
                   4648:     }
                   4649:    
                   4650:     #  Enter the hash:
                   4651:       
                   4652:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   4653:    
                   4654:     $Dispatcher{$request_name} = \@entry;
                   4655:    
                   4656: }
                   4657: 
                   4658: 
                   4659: #------------------------------------------------------------------
                   4660: 
                   4661: 
                   4662: 
                   4663: 
1.141     foxr     4664: #
1.96      foxr     4665: #  Convert an error return code from lcpasswd to a string value.
                   4666: #
                   4667: sub lcpasswdstrerror {
                   4668:     my $ErrorCode = shift;
1.97      foxr     4669:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     4670: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   4671:     } else {
1.98      foxr     4672: 	return $passwderrors[$ErrorCode];
1.96      foxr     4673:     }
                   4674: }
                   4675: 
1.97      foxr     4676: #
                   4677: # Convert an error return code from lcuseradd to a string value:
                   4678: #
                   4679: sub lcuseraddstrerror {
                   4680:     my $ErrorCode = shift;
                   4681:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
                   4682: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
                   4683:     } else {
1.98      foxr     4684: 	return $adderrors[$ErrorCode];
1.97      foxr     4685:     }
                   4686: }
                   4687: 
1.23      harris41 4688: # grabs exception and records it to log before exiting
                   4689: sub catchexception {
1.27      albertel 4690:     my ($error)=@_;
1.25      www      4691:     $SIG{'QUIT'}='DEFAULT';
                   4692:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 4693:     &status("Catching exception");
1.190     albertel 4694:     &logthis("<font color='red'>CRITICAL: "
1.134     albertel 4695:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27      albertel 4696:      ."a crash with this error msg->[$error]</font>");
1.57      www      4697:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 4698:     if ($client) { print $client "error: $error\n"; }
1.59      www      4699:     $server->close();
1.27      albertel 4700:     die($error);
1.23      harris41 4701: }
1.63      www      4702: sub timeout {
1.165     albertel 4703:     &status("Handling Timeout");
1.190     albertel 4704:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      4705:     &catchexception('Timeout');
                   4706: }
1.22      harris41 4707: # -------------------------------- Set signal handlers to record abnormal exits
                   4708: 
1.226     foxr     4709: 
1.22      harris41 4710: $SIG{'QUIT'}=\&catchexception;
                   4711: $SIG{__DIE__}=\&catchexception;
                   4712: 
1.81      matthew  4713: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 4714: &status("Read loncapa.conf and loncapa_apache.conf");
                   4715: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     4716: %perlvar=%{$perlvarref};
1.80      harris41 4717: undef $perlvarref;
1.19      www      4718: 
1.35      harris41 4719: # ----------------------------- Make sure this process is running from user=www
                   4720: my $wwwid=getpwnam('www');
                   4721: if ($wwwid!=$<) {
1.134     albertel 4722:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4723:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 4724:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 4725:  mailto $emailto -s '$subj' > /dev/null");
                   4726:    exit 1;
                   4727: }
                   4728: 
1.19      www      4729: # --------------------------------------------- Check if other instance running
                   4730: 
                   4731: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   4732: 
                   4733: if (-e $pidfile) {
                   4734:    my $lfh=IO::File->new("$pidfile");
                   4735:    my $pide=<$lfh>;
                   4736:    chomp($pide);
1.29      harris41 4737:    if (kill 0 => $pide) { die "already running"; }
1.19      www      4738: }
1.1       albertel 4739: 
                   4740: # ------------------------------------------------------------- Read hosts file
                   4741: 
                   4742: 
                   4743: 
                   4744: # establish SERVER socket, bind and listen.
                   4745: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   4746:                                 Type      => SOCK_STREAM,
                   4747:                                 Proto     => 'tcp',
                   4748:                                 Reuse     => 1,
                   4749:                                 Listen    => 10 )
1.29      harris41 4750:   or die "making socket: $@\n";
1.1       albertel 4751: 
                   4752: # --------------------------------------------------------- Do global variables
                   4753: 
                   4754: # global variables
                   4755: 
1.134     albertel 4756: my %children               = ();       # keys are current child process IDs
1.1       albertel 4757: 
                   4758: sub REAPER {                        # takes care of dead children
                   4759:     $SIG{CHLD} = \&REAPER;
1.165     albertel 4760:     &status("Handling child death");
1.178     foxr     4761:     my $pid;
                   4762:     do {
                   4763: 	$pid = waitpid(-1,&WNOHANG());
                   4764: 	if (defined($children{$pid})) {
                   4765: 	    &logthis("Child $pid died");
                   4766: 	    delete($children{$pid});
1.183     albertel 4767: 	} elsif ($pid > 0) {
1.178     foxr     4768: 	    &logthis("Unknown Child $pid died");
                   4769: 	}
                   4770:     } while ( $pid > 0 );
                   4771:     foreach my $child (keys(%children)) {
                   4772: 	$pid = waitpid($child,&WNOHANG());
                   4773: 	if ($pid > 0) {
                   4774: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   4775: 	    delete($children{$pid});
                   4776: 	}
1.176     albertel 4777:     }
1.165     albertel 4778:     &status("Finished Handling child death");
1.1       albertel 4779: }
                   4780: 
                   4781: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 4782:     &status("Killing children (INT)");
1.1       albertel 4783:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   4784:     kill 'INT' => keys %children;
1.59      www      4785:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 4786:     my $execdir=$perlvar{'lonDaemons'};
                   4787:     unlink("$execdir/logs/lond.pid");
1.190     albertel 4788:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 4789:     &status("Done killing children");
1.1       albertel 4790:     exit;                           # clean up with dignity
                   4791: }
                   4792: 
                   4793: sub HUPSMAN {                      # signal handler for SIGHUP
                   4794:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 4795:     &status("Killing children for restart (HUP)");
1.1       albertel 4796:     kill 'INT' => keys %children;
1.59      www      4797:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 4798:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 4799:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 4800:     unlink("$execdir/logs/lond.pid");
1.165     albertel 4801:     &status("Restarting self (HUP)");
1.1       albertel 4802:     exec("$execdir/lond");         # here we go again
                   4803: }
                   4804: 
1.144     foxr     4805: #
1.148     foxr     4806: #    Kill off hashes that describe the host table prior to re-reading it.
                   4807: #    Hashes affected are:
1.200     matthew  4808: #       %hostid, %hostdom %hostip %hostdns.
1.148     foxr     4809: #
                   4810: sub KillHostHashes {
                   4811:     foreach my $key (keys %hostid) {
                   4812: 	delete $hostid{$key};
                   4813:     }
                   4814:     foreach my $key (keys %hostdom) {
                   4815: 	delete $hostdom{$key};
                   4816:     }
                   4817:     foreach my $key (keys %hostip) {
                   4818: 	delete $hostip{$key};
                   4819:     }
1.200     matthew  4820:     foreach my $key (keys %hostdns) {
                   4821: 	delete $hostdns{$key};
                   4822:     }
1.148     foxr     4823: }
                   4824: #
                   4825: #   Read in the host table from file and distribute it into the various hashes:
                   4826: #
                   4827: #    - %hostid  -  Indexed by IP, the loncapa hostname.
                   4828: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
                   4829: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
                   4830: sub ReadHostTable {
                   4831: 
                   4832:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200     matthew  4833:     my $myloncapaname = $perlvar{'lonHostID'};
                   4834:     Debug("My loncapa name is : $myloncapaname");
1.296     albertel 4835:     my %name_to_ip;
1.148     foxr     4836:     while (my $configline=<CONFIG>) {
1.277     albertel 4837: 	if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
                   4838: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   4839: 	    $name=~s/\s//g;
1.296     albertel 4840: 	    my $ip;
                   4841: 	    if (!exists($name_to_ip{$name})) {
                   4842: 		$ip = gethostbyname($name);
                   4843: 		if (!$ip || length($ip) ne 4) {
                   4844: 		    &logthis("Skipping host $id name $name no IP found\n");
                   4845: 		    next;
                   4846: 		}
                   4847: 		$ip=inet_ntoa($ip);
                   4848: 		$name_to_ip{$name} = $ip;
                   4849: 	    } else {
                   4850: 		$ip = $name_to_ip{$name};
1.277     albertel 4851: 	    }
1.200     matthew  4852: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
                   4853: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
1.277     albertel 4854: 	    $hostip{$id}=$ip;         # IP address of host.
1.200     matthew  4855: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
                   4856: 
                   4857: 	    if ($id eq $perlvar{'lonHostID'}) { 
                   4858: 		Debug("Found me in the host table: $name");
                   4859: 		$thisserver=$name; 
                   4860: 	    }
1.178     foxr     4861: 	}
1.148     foxr     4862:     }
                   4863:     close(CONFIG);
                   4864: }
                   4865: #
                   4866: #  Reload the Apache daemon's state.
1.150     foxr     4867: #  This is done by invoking /home/httpd/perl/apachereload
                   4868: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     4869: #
                   4870: sub ReloadApache {
1.150     foxr     4871:     my $execdir = $perlvar{'lonDaemons'};
                   4872:     my $script  = $execdir."/apachereload";
                   4873:     system($script);
1.148     foxr     4874: }
                   4875: 
                   4876: #
1.144     foxr     4877: #   Called in response to a USR2 signal.
                   4878: #   - Reread hosts.tab
                   4879: #   - All children connected to hosts that were removed from hosts.tab
                   4880: #     are killed via SIGINT
                   4881: #   - All children connected to previously existing hosts are sent SIGUSR1
                   4882: #   - Our internal hosts hash is updated to reflect the new contents of
                   4883: #     hosts.tab causing connections from hosts added to hosts.tab to
                   4884: #     now be honored.
                   4885: #
                   4886: sub UpdateHosts {
1.165     albertel 4887:     &status("Reload hosts.tab");
1.147     foxr     4888:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     4889:     #
                   4890:     #  The %children hash has the set of IP's we currently have children
                   4891:     #  on.  These need to be matched against records in the hosts.tab
                   4892:     #  Any ip's no longer in the table get killed off they correspond to
                   4893:     #  either dropped or changed hosts.  Note that the re-read of the table
                   4894:     #  will take care of new and changed hosts as connections come into being.
                   4895: 
                   4896: 
                   4897:     KillHostHashes;
                   4898:     ReadHostTable;
                   4899: 
                   4900:     foreach my $child (keys %children) {
                   4901: 	my $childip = $children{$child};
                   4902: 	if(!$hostid{$childip}) {
1.149     foxr     4903: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   4904: 		    ." $child for ip $childip </font>");
1.148     foxr     4905: 	    kill('INT', $child);
1.149     foxr     4906: 	} else {
                   4907: 	    logthis('<font color="green"> keeping child for ip '
                   4908: 		    ." $childip (pid=$child) </font>");
1.148     foxr     4909: 	}
                   4910:     }
                   4911:     ReloadApache;
1.165     albertel 4912:     &status("Finished reloading hosts.tab");
1.144     foxr     4913: }
                   4914: 
1.148     foxr     4915: 
1.57      www      4916: sub checkchildren {
1.165     albertel 4917:     &status("Checking on the children (sending signals)");
1.57      www      4918:     &initnewstatus();
                   4919:     &logstatus();
                   4920:     &logthis('Going to check on the children');
1.134     albertel 4921:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 4922:     foreach (sort keys %children) {
1.221     albertel 4923: 	#sleep 1;
1.57      www      4924:         unless (kill 'USR1' => $_) {
                   4925: 	    &logthis ('Child '.$_.' is dead');
                   4926:             &logstatus($$.' is dead');
1.221     albertel 4927: 	    delete($children{$_});
1.57      www      4928:         } 
1.61      harris41 4929:     }
1.63      www      4930:     sleep 5;
1.212     foxr     4931:     $SIG{ALRM} = sub { Debug("timeout"); 
                   4932: 		       die "timeout";  };
1.113     albertel 4933:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 4934:     &status("Checking on the children (waiting for reports)");
1.63      www      4935:     foreach (sort keys %children) {
                   4936:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 4937:           eval {
                   4938:             alarm(300);
1.63      www      4939: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 4940: 	    kill 9 => $_;
1.131     albertel 4941: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4942: 	    #$subj="LON: $currenthostid killed lond process $_";
                   4943: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   4944: 	    #$execdir=$perlvar{'lonDaemons'};
                   4945: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 4946: 	    delete($children{$_});
1.113     albertel 4947: 	    alarm(0);
                   4948: 	  }
1.63      www      4949:         }
                   4950:     }
1.113     albertel 4951:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 4952:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 4953:     &status("Finished checking children");
1.221     albertel 4954:     &logthis('Finished Checking children');
1.57      www      4955: }
                   4956: 
1.1       albertel 4957: # --------------------------------------------------------------------- Logging
                   4958: 
                   4959: sub logthis {
                   4960:     my $message=shift;
                   4961:     my $execdir=$perlvar{'lonDaemons'};
                   4962:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   4963:     my $now=time;
                   4964:     my $local=localtime($now);
1.58      www      4965:     $lastlog=$local.': '.$message;
1.1       albertel 4966:     print $fh "$local ($$): $message\n";
                   4967: }
                   4968: 
1.77      foxr     4969: # ------------------------- Conditional log if $DEBUG true.
                   4970: sub Debug {
                   4971:     my $message = shift;
                   4972:     if($DEBUG) {
                   4973: 	&logthis($message);
                   4974:     }
                   4975: }
1.161     foxr     4976: 
                   4977: #
                   4978: #   Sub to do replies to client.. this gives a hook for some
                   4979: #   debug tracing too:
                   4980: #  Parameters:
                   4981: #     fd      - File open on client.
                   4982: #     reply   - Text to send to client.
                   4983: #     request - Original request from client.
                   4984: #
                   4985: sub Reply {
1.192     foxr     4986:     my ($fd, $reply, $request) = @_;
1.161     foxr     4987:     print $fd $reply;
                   4988:     Debug("Request was $request  Reply was $reply");
                   4989: 
1.212     foxr     4990:     $Transactions++;
                   4991: }
                   4992: 
                   4993: 
                   4994: #
                   4995: #    Sub to report a failure.
                   4996: #    This function:
                   4997: #     -   Increments the failure statistic counters.
                   4998: #     -   Invokes Reply to send the error message to the client.
                   4999: # Parameters:
                   5000: #    fd       - File descriptor open on the client
                   5001: #    reply    - Reply text to emit.
                   5002: #    request  - The original request message (used by Reply
                   5003: #               to debug if that's enabled.
                   5004: # Implicit outputs:
                   5005: #    $Failures- The number of failures is incremented.
                   5006: #    Reply (invoked here) sends a message to the 
                   5007: #    client:
                   5008: #
                   5009: sub Failure {
                   5010:     my $fd      = shift;
                   5011:     my $reply   = shift;
                   5012:     my $request = shift;
                   5013:    
                   5014:     $Failures++;
                   5015:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     5016: }
1.57      www      5017: # ------------------------------------------------------------------ Log status
                   5018: 
                   5019: sub logstatus {
1.178     foxr     5020:     &status("Doing logging");
                   5021:     my $docdir=$perlvar{'lonDocRoot'};
                   5022:     {
                   5023: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  5024:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     5025:         $fh->close();
                   5026:     }
1.221     albertel 5027:     &status("Finished $$.txt");
                   5028:     {
                   5029: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   5030: 	flock(LOG,LOCK_EX);
                   5031: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   5032: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 5033: 	flock(LOG,LOCK_UN);
1.221     albertel 5034: 	close(LOG);
                   5035:     }
1.178     foxr     5036:     &status("Finished logging");
1.57      www      5037: }
                   5038: 
                   5039: sub initnewstatus {
                   5040:     my $docdir=$perlvar{'lonDocRoot'};
                   5041:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
                   5042:     my $now=time;
                   5043:     my $local=localtime($now);
                   5044:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      5045:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 5046:     while (my $filename=readdir(DIR)) {
1.64      www      5047:         unlink("$docdir/lon-status/londchld/$filename");
                   5048:     }
                   5049:     closedir(DIR);
1.57      www      5050: }
                   5051: 
                   5052: # -------------------------------------------------------------- Status setting
                   5053: 
                   5054: sub status {
                   5055:     my $what=shift;
                   5056:     my $now=time;
                   5057:     my $local=localtime($now);
1.178     foxr     5058:     $status=$local.': '.$what;
                   5059:     $0='lond: '.$what.' '.$local;
1.57      www      5060: }
1.11      www      5061: 
                   5062: # -------------------------------------------------------- Escape Special Chars
                   5063: 
                   5064: sub escape {
                   5065:     my $str=shift;
                   5066:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   5067:     return $str;
                   5068: }
                   5069: 
                   5070: # ----------------------------------------------------- Un-Escape Special Chars
                   5071: 
                   5072: sub unescape {
                   5073:     my $str=shift;
                   5074:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   5075:     return $str;
                   5076: }
                   5077: 
1.1       albertel 5078: # ----------------------------------------------------------- Send USR1 to lonc
                   5079: 
                   5080: sub reconlonc {
                   5081:     my $peerfile=shift;
                   5082:     &logthis("Trying to reconnect for $peerfile");
                   5083:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                   5084:     if (my $fh=IO::File->new("$loncfile")) {
                   5085: 	my $loncpid=<$fh>;
                   5086:         chomp($loncpid);
                   5087:         if (kill 0 => $loncpid) {
                   5088: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                   5089:             kill USR1 => $loncpid;
                   5090:         } else {
1.9       www      5091: 	    &logthis(
1.190     albertel 5092:               "<font color='red'>CRITICAL: "
1.9       www      5093:              ."lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel 5094:         }
                   5095:     } else {
1.190     albertel 5096:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1       albertel 5097:     }
                   5098: }
                   5099: 
                   5100: # -------------------------------------------------- Non-critical communication
1.11      www      5101: 
1.1       albertel 5102: sub subreply {
                   5103:     my ($cmd,$server)=@_;
                   5104:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                   5105:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   5106:                                       Type    => SOCK_STREAM,
                   5107:                                       Timeout => 10)
                   5108:        or return "con_lost";
                   5109:     print $sclient "$cmd\n";
                   5110:     my $answer=<$sclient>;
                   5111:     chomp($answer);
                   5112:     if (!$answer) { $answer="con_lost"; }
                   5113:     return $answer;
                   5114: }
                   5115: 
                   5116: sub reply {
                   5117:   my ($cmd,$server)=@_;
                   5118:   my $answer;
1.115     albertel 5119:   if ($server ne $currenthostid) { 
1.1       albertel 5120:     $answer=subreply($cmd,$server);
                   5121:     if ($answer eq 'con_lost') {
                   5122: 	$answer=subreply("ping",$server);
                   5123:         if ($answer ne $server) {
1.115     albertel 5124: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1       albertel 5125:            &reconlonc("$perlvar{'lonSockDir'}/$server");
                   5126:         }
                   5127:         $answer=subreply($cmd,$server);
                   5128:     }
                   5129:   } else {
                   5130:     $answer='self_reply';
                   5131:   } 
                   5132:   return $answer;
                   5133: }
                   5134: 
1.13      www      5135: # -------------------------------------------------------------- Talk to lonsql
                   5136: 
1.234     foxr     5137: sub sql_reply {
1.12      harris41 5138:     my ($cmd)=@_;
1.234     foxr     5139:     my $answer=&sub_sql_reply($cmd);
                   5140:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 5141:     return $answer;
                   5142: }
                   5143: 
1.234     foxr     5144: sub sub_sql_reply {
1.12      harris41 5145:     my ($cmd)=@_;
                   5146:     my $unixsock="mysqlsock";
                   5147:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   5148:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   5149:                                       Type    => SOCK_STREAM,
                   5150:                                       Timeout => 10)
                   5151:        or return "con_lost";
1.305.2.5! albertel 5152:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 5153:     my $answer=<$sclient>;
                   5154:     chomp($answer);
                   5155:     if (!$answer) { $answer="con_lost"; }
                   5156:     return $answer;
                   5157: }
                   5158: 
1.1       albertel 5159: # -------------------------------------------- Return path to profile directory
1.11      www      5160: 
1.1       albertel 5161: sub propath {
                   5162:     my ($udom,$uname)=@_;
                   5163:     $udom=~s/\W//g;
                   5164:     $uname=~s/\W//g;
1.16      www      5165:     my $subdir=$uname.'__';
1.1       albertel 5166:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5167:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   5168:     return $proname;
                   5169: } 
                   5170: 
                   5171: # --------------------------------------- Is this the home server of an author?
1.11      www      5172: 
1.1       albertel 5173: sub ishome {
                   5174:     my $author=shift;
                   5175:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   5176:     my ($udom,$uname)=split(/\//,$author);
                   5177:     my $proname=propath($udom,$uname);
                   5178:     if (-e $proname) {
                   5179: 	return 'owner';
                   5180:     } else {
                   5181:         return 'not_owner';
                   5182:     }
                   5183: }
                   5184: 
                   5185: # ======================================================= Continue main program
                   5186: # ---------------------------------------------------- Fork once and dissociate
                   5187: 
1.134     albertel 5188: my $fpid=fork;
1.1       albertel 5189: exit if $fpid;
1.29      harris41 5190: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 5191: 
1.29      harris41 5192: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 5193: 
                   5194: # ------------------------------------------------------- Write our PID on disk
                   5195: 
1.134     albertel 5196: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 5197: open (PIDSAVE,">$execdir/logs/lond.pid");
                   5198: print PIDSAVE "$$\n";
                   5199: close(PIDSAVE);
1.190     albertel 5200: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      5201: &status('Starting');
1.1       albertel 5202: 
1.106     foxr     5203: 
1.1       albertel 5204: 
                   5205: # ----------------------------------------------------- Install signal handlers
                   5206: 
1.57      www      5207: 
1.1       albertel 5208: $SIG{CHLD} = \&REAPER;
                   5209: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   5210: $SIG{HUP}  = \&HUPSMAN;
1.57      www      5211: $SIG{USR1} = \&checkchildren;
1.144     foxr     5212: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     5213: 
1.148     foxr     5214: #  Read the host hashes:
                   5215: 
                   5216: ReadHostTable;
1.106     foxr     5217: 
1.286     albertel 5218: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
                   5219: 
1.106     foxr     5220: # --------------------------------------------------------------
                   5221: #   Accept connections.  When a connection comes in, it is validated
                   5222: #   and if good, a child process is created to process transactions
                   5223: #   along the connection.
                   5224: 
1.1       albertel 5225: while (1) {
1.165     albertel 5226:     &status('Starting accept');
1.106     foxr     5227:     $client = $server->accept() or next;
1.165     albertel 5228:     &status('Accepted '.$client.' off to spawn');
1.106     foxr     5229:     make_new_child($client);
1.165     albertel 5230:     &status('Finished spawning');
1.1       albertel 5231: }
                   5232: 
1.212     foxr     5233: sub make_new_child {
                   5234:     my $pid;
                   5235: #    my $cipher;     # Now global
                   5236:     my $sigset;
1.178     foxr     5237: 
1.212     foxr     5238:     $client = shift;
                   5239:     &status('Starting new child '.$client);
                   5240:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   5241: 	     ")</font>");    
                   5242:     # block signal for fork
                   5243:     $sigset = POSIX::SigSet->new(SIGINT);
                   5244:     sigprocmask(SIG_BLOCK, $sigset)
                   5245:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     5246: 
1.212     foxr     5247:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     5248: 
1.212     foxr     5249:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   5250: 	                               # connection liveness.
1.178     foxr     5251: 
1.212     foxr     5252:     #
                   5253:     #  Figure out who we're talking to so we can record the peer in 
                   5254:     #  the pid hash.
                   5255:     #
                   5256:     my $caller = getpeername($client);
                   5257:     my ($port,$iaddr);
                   5258:     if (defined($caller) && length($caller) > 0) {
                   5259: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   5260:     } else {
                   5261: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   5262:     }
                   5263:     if (defined($iaddr)) {
                   5264: 	$clientip  = inet_ntoa($iaddr);
                   5265: 	Debug("Connected with $clientip");
                   5266:     } else {
                   5267: 	&logthis("Unable to determine clientip");
                   5268: 	$clientip='Unavailable';
                   5269:     }
                   5270:     
                   5271:     if ($pid) {
                   5272:         # Parent records the child's birth and returns.
                   5273:         sigprocmask(SIG_UNBLOCK, $sigset)
                   5274:             or die "Can't unblock SIGINT for fork: $!\n";
                   5275:         $children{$pid} = $clientip;
                   5276:         &status('Started child '.$pid);
                   5277:         return;
                   5278:     } else {
                   5279:         # Child can *not* return from this subroutine.
                   5280:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   5281:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   5282:                                 #don't get intercepted
                   5283:         $SIG{USR1}= \&logstatus;
                   5284:         $SIG{ALRM}= \&timeout;
                   5285:         $lastlog='Forked ';
                   5286:         $status='Forked';
1.178     foxr     5287: 
1.212     foxr     5288:         # unblock signals
                   5289:         sigprocmask(SIG_UNBLOCK, $sigset)
                   5290:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     5291: 
1.212     foxr     5292: #        my $tmpsnum=0;            # Now global
                   5293: #---------------------------------------------------- kerberos 5 initialization
                   5294:         &Authen::Krb5::init_context();
1.297     raeburn  5295: 	unless (($dist eq 'fedora4') || ($dist eq 'suse9.3')) {
1.286     albertel 5296: 	    &Authen::Krb5::init_ets();
                   5297: 	}
1.209     albertel 5298: 
1.212     foxr     5299: 	&status('Accepted connection');
                   5300: # =============================================================================
                   5301:             # do something with the connection
                   5302: # -----------------------------------------------------------------------------
                   5303: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     5304: 
1.212     foxr     5305: 	ReadManagerTable;	# May also be a manager!!
                   5306: 	
1.278     albertel 5307: 	my $outsideip=$clientip;
                   5308: 	if ($clientip eq '127.0.0.1') {
                   5309: 	    $outsideip=$hostip{$perlvar{'lonHostID'}};
                   5310: 	}
                   5311: 
                   5312: 	my $clientrec=($hostid{$outsideip}     ne undef);
                   5313: 	my $ismanager=($managers{$outsideip}    ne undef);
1.212     foxr     5314: 	$clientname  = "[unknonwn]";
                   5315: 	if($clientrec) {	# Establish client type.
                   5316: 	    $ConnectionType = "client";
1.278     albertel 5317: 	    $clientname = $hostid{$outsideip};
1.212     foxr     5318: 	    if($ismanager) {
                   5319: 		$ConnectionType = "both";
                   5320: 	    }
                   5321: 	} else {
                   5322: 	    $ConnectionType = "manager";
1.278     albertel 5323: 	    $clientname = $managers{$outsideip};
1.212     foxr     5324: 	}
                   5325: 	my $clientok;
1.178     foxr     5326: 
1.212     foxr     5327: 	if ($clientrec || $ismanager) {
                   5328: 	    &status("Waiting for init from $clientip $clientname");
                   5329: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   5330: 		     $clientip.
                   5331: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   5332: 	    &status("Connecting $clientip  ($clientname))"); 
                   5333: 	    my $remotereq=<$client>;
                   5334: 	    chomp($remotereq);
                   5335: 	    Debug("Got init: $remotereq");
                   5336: 	    my $inikeyword = split(/:/, $remotereq);
                   5337: 	    if ($remotereq =~ /^init/) {
                   5338: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   5339: 		#
                   5340: 		#  If the remote is attempting a local init... give that a try:
                   5341: 		#
                   5342: 		my ($i, $inittype) = split(/:/, $remotereq);
1.209     albertel 5343: 
1.212     foxr     5344: 		# If the connection type is ssl, but I didn't get my
                   5345: 		# certificate files yet, then I'll drop  back to 
                   5346: 		# insecure (if allowed).
                   5347: 		
                   5348: 		if($inittype eq "ssl") {
                   5349: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   5350: 		    my $kfile       = lonssl::KeyFile;
                   5351: 		    if((!$ca)   || 
                   5352: 		       (!$cert) || 
                   5353: 		       (!$kfile)) {
                   5354: 			$inittype = ""; # This forces insecure attempt.
                   5355: 			&logthis("<font color=\"blue\"> Certificates not "
                   5356: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     5357: 		    } else {	# SSL certificates are in place so
1.212     foxr     5358: 		    }		# Leave the inittype alone.
                   5359: 		}
                   5360: 
                   5361: 		if($inittype eq "local") {
                   5362: 		    my $key = LocalConnection($client, $remotereq);
                   5363: 		    if($key) {
                   5364: 			Debug("Got local key $key");
                   5365: 			$clientok     = 1;
                   5366: 			my $cipherkey = pack("H32", $key);
                   5367: 			$cipher       = new IDEA($cipherkey);
                   5368: 			print $client "ok:local\n";
                   5369: 			&logthis('<font color="green"'
                   5370: 				 . "Successful local authentication </font>");
                   5371: 			$keymode = "local"
1.178     foxr     5372: 		    } else {
1.212     foxr     5373: 			Debug("Failed to get local key");
                   5374: 			$clientok = 0;
                   5375: 			shutdown($client, 3);
                   5376: 			close $client;
1.178     foxr     5377: 		    }
1.212     foxr     5378: 		} elsif ($inittype eq "ssl") {
                   5379: 		    my $key = SSLConnection($client);
                   5380: 		    if ($key) {
                   5381: 			$clientok = 1;
                   5382: 			my $cipherkey = pack("H32", $key);
                   5383: 			$cipher       = new IDEA($cipherkey);
                   5384: 			&logthis('<font color="green">'
                   5385: 				 ."Successfull ssl authentication with $clientname </font>");
                   5386: 			$keymode = "ssl";
                   5387: 	     
1.178     foxr     5388: 		    } else {
1.212     foxr     5389: 			$clientok = 0;
                   5390: 			close $client;
1.178     foxr     5391: 		    }
1.212     foxr     5392: 	   
                   5393: 		} else {
                   5394: 		    my $ok = InsecureConnection($client);
                   5395: 		    if($ok) {
                   5396: 			$clientok = 1;
                   5397: 			&logthis('<font color="green">'
                   5398: 				 ."Successful insecure authentication with $clientname </font>");
                   5399: 			print $client "ok\n";
                   5400: 			$keymode = "insecure";
1.178     foxr     5401: 		    } else {
1.212     foxr     5402: 			&logthis('<font color="yellow">'
                   5403: 				  ."Attempted insecure connection disallowed </font>");
                   5404: 			close $client;
                   5405: 			$clientok = 0;
1.178     foxr     5406: 			
                   5407: 		    }
                   5408: 		}
1.212     foxr     5409: 	    } else {
                   5410: 		&logthis(
                   5411: 			 "<font color='blue'>WARNING: "
                   5412: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   5413: 		&status('No init '.$clientip);
                   5414: 	    }
                   5415: 	    
                   5416: 	} else {
                   5417: 	    &logthis(
                   5418: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   5419: 	    &status('Hung up on '.$clientip);
                   5420: 	}
                   5421:  
                   5422: 	if ($clientok) {
                   5423: # ---------------- New known client connecting, could mean machine online again
                   5424: 	    
                   5425: 	    foreach my $id (keys(%hostip)) {
                   5426: 		if ($hostip{$id} ne $clientip ||
                   5427: 		    $hostip{$currenthostid} eq $clientip) {
                   5428: 		    # no need to try to do recon's to myself
                   5429: 		    next;
                   5430: 		}
                   5431: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
                   5432: 	    }
                   5433: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   5434: 	    &status('Will listen to '.$clientname);
                   5435: # ------------------------------------------------------------ Process requests
                   5436: 	    my $keep_going = 1;
                   5437: 	    my $user_input;
                   5438: 	    while(($user_input = get_request) && $keep_going) {
                   5439: 		alarm(120);
                   5440: 		Debug("Main: Got $user_input\n");
                   5441: 		$keep_going = &process_request($user_input);
1.178     foxr     5442: 		alarm(0);
1.212     foxr     5443: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     5444: 	    }
1.212     foxr     5445: 
1.59      www      5446: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     5447: 	}  else {
1.161     foxr     5448: 	    print $client "refused\n";
                   5449: 	    $client->close();
1.190     albertel 5450: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     5451: 		     ."Rejected client $clientip, closing connection</font>");
                   5452: 	}
1.212     foxr     5453:     }            
1.161     foxr     5454:     
1.1       albertel 5455: # =============================================================================
1.161     foxr     5456:     
1.190     albertel 5457:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     5458: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   5459:     
                   5460:     
                   5461:     # this exit is VERY important, otherwise the child will become
                   5462:     # a producer of more and more children, forking yourself into
                   5463:     # process death.
                   5464:     exit;
1.106     foxr     5465:     
1.78      foxr     5466: }
1.261     foxr     5467: #
                   5468: #   Determine if a user is an author for the indicated domain.
                   5469: #
                   5470: # Parameters:
                   5471: #    domain          - domain to check in .
                   5472: #    user            - Name of user to check.
                   5473: #
                   5474: # Return:
                   5475: #     1             - User is an author for domain.
                   5476: #     0             - User is not an author for domain.
                   5477: sub is_author {
                   5478:     my ($domain, $user) = @_;
                   5479: 
                   5480:     &Debug("is_author: $user @ $domain");
                   5481: 
                   5482:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   5483: 				 &GDBM_READER());
                   5484: 
                   5485:     #  Author role should show up as a key /domain/_au
1.78      foxr     5486: 
1.261     foxr     5487:     my $key   = "/$domain/_au";
                   5488:     my $value = $hashref->{$key};
1.78      foxr     5489: 
1.261     foxr     5490:     if(defined($value)) {
                   5491: 	&Debug("$user @ $domain is an author");
                   5492:     }
                   5493: 
                   5494:     return defined($value);
                   5495: }
1.78      foxr     5496: #
                   5497: #   Checks to see if the input roleput request was to set
                   5498: # an author role.  If so, invokes the lchtmldir script to set
                   5499: # up a correct public_html 
                   5500: # Parameters:
                   5501: #    request   - The request sent to the rolesput subchunk.
                   5502: #                We're looking for  /domain/_au
                   5503: #    domain    - The domain in which the user is having roles doctored.
                   5504: #    user      - Name of the user for which the role is being put.
                   5505: #    authtype  - The authentication type associated with the user.
                   5506: #
1.289     albertel 5507: sub manage_permissions {
1.192     foxr     5508:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     5509: 
1.261     foxr     5510:     &Debug("manage_permissions: $request $domain $user $authtype");
                   5511: 
1.78      foxr     5512:     # See if the request is of the form /$domain/_au
1.289     albertel 5513:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.78      foxr     5514: 	my $execdir = $perlvar{'lonDaemons'};
                   5515: 	my $userhome= "/home/$user" ;
1.134     albertel 5516: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261     foxr     5517: 	&Debug("Setting homedir permissions for $userhome");
1.78      foxr     5518: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   5519:     }
                   5520: }
1.222     foxr     5521: 
                   5522: 
                   5523: #
                   5524: #  Return the full path of a user password file, whether it exists or not.
                   5525: # Parameters:
                   5526: #   domain     - Domain in which the password file lives.
                   5527: #   user       - name of the user.
                   5528: # Returns:
                   5529: #    Full passwd path:
                   5530: #
                   5531: sub password_path {
                   5532:     my ($domain, $user) = @_;
1.264     albertel 5533:     return &propath($domain, $user).'/passwd';
1.222     foxr     5534: }
                   5535: 
                   5536: #   Password Filename
                   5537: #   Returns the path to a passwd file given domain and user... only if
                   5538: #  it exists.
                   5539: # Parameters:
                   5540: #   domain    - Domain in which to search.
                   5541: #   user      - username.
                   5542: # Returns:
                   5543: #   - If the password file exists returns its path.
                   5544: #   - If the password file does not exist, returns undefined.
                   5545: #
                   5546: sub password_filename {
                   5547:     my ($domain, $user) = @_;
                   5548: 
                   5549:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   5550: 
                   5551:     my $path  = &password_path($domain, $user);
                   5552:     Debug("PasswordFilename got path: $path");
                   5553:     if(-e $path) {
                   5554: 	return $path;
                   5555:     } else {
                   5556: 	return undef;
                   5557:     }
                   5558: }
                   5559: 
                   5560: #
                   5561: #   Rewrite the contents of the user's passwd file.
                   5562: #  Parameters:
                   5563: #    domain    - domain of the user.
                   5564: #    name      - User's name.
                   5565: #    contents  - New contents of the file.
                   5566: # Returns:
                   5567: #   0    - Failed.
                   5568: #   1    - Success.
                   5569: #
                   5570: sub rewrite_password_file {
                   5571:     my ($domain, $user, $contents) = @_;
                   5572: 
                   5573:     my $file = &password_filename($domain, $user);
                   5574:     if (defined $file) {
                   5575: 	my $pf = IO::File->new(">$file");
                   5576: 	if($pf) {
                   5577: 	    print $pf "$contents\n";
                   5578: 	    return 1;
                   5579: 	} else {
                   5580: 	    return 0;
                   5581: 	}
                   5582:     } else {
                   5583: 	return 0;
                   5584:     }
                   5585: 
                   5586: }
                   5587: 
1.78      foxr     5588: #
1.222     foxr     5589: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     5590: 
                   5591: #     Returns the authorization type or nouser if there is no such user.
                   5592: #
1.222     foxr     5593: sub get_auth_type 
1.78      foxr     5594: {
1.192     foxr     5595: 
                   5596:     my ($domain, $user)  = @_;
1.78      foxr     5597: 
1.222     foxr     5598:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     5599:     my $proname    = &propath($domain, $user); 
                   5600:     my $passwdfile = "$proname/passwd";
                   5601:     if( -e $passwdfile ) {
                   5602: 	my $pf = IO::File->new($passwdfile);
                   5603: 	my $realpassword = <$pf>;
                   5604: 	chomp($realpassword);
1.79      foxr     5605: 	Debug("Password info = $realpassword\n");
1.78      foxr     5606: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     5607: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  5608: 	return "$authtype:$contentpwd";     
1.224     foxr     5609:     } else {
1.79      foxr     5610: 	Debug("Returning nouser");
1.78      foxr     5611: 	return "nouser";
                   5612:     }
1.1       albertel 5613: }
                   5614: 
1.220     foxr     5615: #
                   5616: #  Validate a user given their domain, name and password.  This utility
                   5617: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   5618: #  to validate the login credentials of a user.
                   5619: # Parameters:
                   5620: #    $domain    - The domain being logged into (this is required due to
                   5621: #                 the capability for multihomed systems.
                   5622: #    $user      - The name of the user being validated.
                   5623: #    $password  - The user's propoposed password.
                   5624: #
                   5625: # Returns:
                   5626: #     1        - The domain,user,pasword triplet corresponds to a valid
                   5627: #                user.
                   5628: #     0        - The domain,user,password triplet is not a valid user.
                   5629: #
                   5630: sub validate_user {
                   5631:     my ($domain, $user, $password) = @_;
                   5632: 
                   5633: 
                   5634:     # Why negative ~pi you may well ask?  Well this function is about
                   5635:     # authentication, and therefore very important to get right.
                   5636:     # I've initialized the flag that determines whether or not I've 
                   5637:     # validated correctly to a value it's not supposed to get.
                   5638:     # At the end of this function. I'll ensure that it's not still that
                   5639:     # value so we don't just wind up returning some accidental value
                   5640:     # as a result of executing an unforseen code path that
1.249     foxr     5641:     # did not set $validated.  At the end of valid execution paths,
                   5642:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     5643: 
                   5644:     my $validated = -3.14159;
                   5645: 
                   5646:     #  How we authenticate is determined by the type of authentication
                   5647:     #  the user has been assigned.  If the authentication type is
                   5648:     #  "nouser", the user does not exist so we will return 0.
                   5649: 
1.222     foxr     5650:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     5651:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   5652: 
                   5653:     my $null = pack("C",0);	# Used by kerberos auth types.
                   5654: 
                   5655:     if ($howpwd ne 'nouser') {
                   5656: 
                   5657: 	if($howpwd eq "internal") { # Encrypted is in local password file.
                   5658: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
                   5659: 	}
                   5660: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   5661: 	    $contentpwd = (getpwnam($user))[1];
                   5662: 	    if($contentpwd) {
                   5663: 		if($contentpwd eq 'x') { # Shadow password file...
                   5664: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   5665: 		    open PWAUTH,  "|$pwauth_path" or
                   5666: 			die "Cannot invoke authentication";
                   5667: 		    print PWAUTH "$user\n$password\n";
                   5668: 		    close PWAUTH;
                   5669: 		    $validated = ! $?;
                   5670: 
                   5671: 		} else { 	         # Passwords in /etc/passwd. 
                   5672: 		    $validated = (crypt($password,
                   5673: 					$contentpwd) eq $contentpwd);
                   5674: 		}
                   5675: 	    } else {
                   5676: 		$validated = 0;
                   5677: 	    }
                   5678: 	}
                   5679: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   5680: 	    if(! ($password =~ /$null/) ) {
                   5681: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   5682: 							   "",
                   5683: 							   $contentpwd,,
                   5684: 							   'krbtgt',
                   5685: 							   $contentpwd,
                   5686: 							   1,
                   5687: 							   $password);
                   5688: 		if(!$k4error) {
                   5689: 		    $validated = 1;
1.224     foxr     5690: 		} else {
1.220     foxr     5691: 		    $validated = 0;
                   5692: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   5693: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   5694: 		}
1.224     foxr     5695: 	    } else {
1.220     foxr     5696: 		$validated = 0; # Password has a match with null.
                   5697: 	    }
1.224     foxr     5698: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220     foxr     5699: 	    if(!($password =~ /$null/)) { # Null password not allowed.
                   5700: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   5701: 							  .$contentpwd);
                   5702: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   5703: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   5704: 		my $credentials= &Authen::Krb5::cc_default();
                   5705: 		$credentials->initialize($krbclient);
1.270     matthew  5706: 		my $krbreturn  = &Authen::Krb5::get_in_tkt_with_password($krbclient,
1.220     foxr     5707: 									 $krbserver,
                   5708: 									 $password,
                   5709: 									 $credentials);
                   5710: 		$validated = ($krbreturn == 1);
1.224     foxr     5711: 	    } else {
1.220     foxr     5712: 		$validated = 0;
                   5713: 	    }
1.224     foxr     5714: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     5715: 	    #  Authenticate via installation specific authentcation method:
                   5716: 	    $validated = &localauth::localauth($user, 
                   5717: 					       $password, 
                   5718: 					       $contentpwd);
1.224     foxr     5719: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     5720: 	    $validated = 0;
                   5721: 	}
                   5722:     } else {
                   5723: 	$validated = 0;
                   5724:     }
                   5725:     #
                   5726:     #  $validated has the correct stat of the authentication:
                   5727:     #
                   5728: 
                   5729:     unless ($validated != -3.14159) {
1.249     foxr     5730: 	#  I >really really< want to know if this happens.
                   5731: 	#  since it indicates that user authentication is badly
                   5732: 	#  broken in some code path.
                   5733:         #
                   5734: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     5735:     }
                   5736:     return $validated;
                   5737: }
                   5738: 
                   5739: 
1.84      albertel 5740: sub addline {
                   5741:     my ($fname,$hostid,$ip,$newline)=@_;
                   5742:     my $contents;
                   5743:     my $found=0;
                   5744:     my $expr='^'.$hostid.':'.$ip.':';
                   5745:     $expr =~ s/\./\\\./g;
1.134     albertel 5746:     my $sh;
1.84      albertel 5747:     if ($sh=IO::File->new("$fname.subscription")) {
                   5748: 	while (my $subline=<$sh>) {
                   5749: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   5750: 	}
                   5751: 	$sh->close();
                   5752:     }
                   5753:     $sh=IO::File->new(">$fname.subscription");
                   5754:     if ($contents) { print $sh $contents; }
                   5755:     if ($newline) { print $sh $newline; }
                   5756:     $sh->close();
                   5757:     return $found;
1.86      www      5758: }
                   5759: 
1.234     foxr     5760: sub get_chat {
1.122     www      5761:     my ($cdom,$cname,$udom,$uname)=@_;
1.305.2.2  albertel 5762: 
1.87      www      5763:     my @entries=();
1.305.2.2  albertel 5764:     my $hashref = &tie_user_hash($cdom, $cname, 'nohist_chatroom',
                   5765: 				 &GDBM_READER());
                   5766:     if ($hashref) {
                   5767: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
                   5768: 	&untie_user_hash($hashref);
1.123     www      5769:     }
1.124     www      5770:     my @participants=();
1.134     albertel 5771:     my $cutoff=time-60;
1.305.2.2  albertel 5772:     $hashref = &tie_user_hash($cdom, $cname, 'nohist_inchatroom',
                   5773: 			      &GDBM_WRCREAT());
                   5774:     if ($hashref) {
                   5775:         $hashref->{$uname.':'.$udom}=time;
                   5776:         foreach my $user (sort(keys(%$hashref))) {
                   5777: 	    if ($hashref->{$user}>$cutoff) {
                   5778: 		push(@participants, 'active_participant:'.$user);
1.123     www      5779:             }
                   5780:         }
1.305.2.2  albertel 5781:         &untie_user_hash($hashref);
1.86      www      5782:     }
1.124     www      5783:     return (@participants,@entries);
1.86      www      5784: }
                   5785: 
1.234     foxr     5786: sub chat_add {
1.88      albertel 5787:     my ($cdom,$cname,$newchat)=@_;
                   5788:     my @entries=();
1.142     www      5789:     my $time=time;
1.305.2.2  albertel 5790:     my $hashref = &tie_user_hash($cdom, $cname, 'nohist_chatroom',
                   5791: 				 &GDBM_WRCREAT());
                   5792:     if ($hashref) {
                   5793: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 5794: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   5795: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   5796: 	my $newid=$time.'_000000';
                   5797: 	if ($thentime==$time) {
                   5798: 	    $idnum=~s/^0+//;
                   5799: 	    $idnum++;
                   5800: 	    $idnum=substr('000000'.$idnum,-6,6);
                   5801: 	    $newid=$time.'_'.$idnum;
                   5802: 	}
1.305.2.2  albertel 5803: 	$hashref->{$newid}=$newchat;
1.88      albertel 5804: 	my $expired=$time-3600;
1.305.2.2  albertel 5805: 	foreach my $comment (keys(%$hashref)) {
                   5806: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 5807: 	    if ($thistime<$expired) {
1.305.2.2  albertel 5808: 		delete $hashref->{$comment};
1.88      albertel 5809: 	    }
                   5810: 	}
1.305.2.2  albertel 5811: 	{
                   5812: 	    my $proname=&propath($cdom,$cname);
                   5813: 	    if (open(CHATLOG,">>$proname/chatroom.log")) { 
                   5814: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   5815: 	    }
                   5816: 	    close(CHATLOG);
1.142     www      5817: 	}
1.305.2.2  albertel 5818: 	&untie_user_hash($hashref);
1.86      www      5819:     }
1.84      albertel 5820: }
                   5821: 
                   5822: sub unsub {
                   5823:     my ($fname,$clientip)=@_;
                   5824:     my $result;
1.188     foxr     5825:     my $unsubs = 0;		# Number of successful unsubscribes:
                   5826: 
                   5827: 
                   5828:     # An old way subscriptions were handled was to have a 
                   5829:     # subscription marker file:
                   5830: 
                   5831:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     5832:     if (unlink("$fname.$clientname")) {
1.188     foxr     5833: 	$unsubs++;		# Successful unsub via marker file.
                   5834:     } 
                   5835: 
                   5836:     # The more modern way to do it is to have a subscription list
                   5837:     # file:
                   5838: 
1.84      albertel 5839:     if (-e "$fname.subscription") {
1.161     foxr     5840: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     5841: 	if ($found) { 
                   5842: 	    $unsubs++;
                   5843: 	}
                   5844:     } 
                   5845: 
                   5846:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   5847:     #  resource we can return ok:
                   5848: 
                   5849:     if($unsubs) {
                   5850: 	$result = "ok\n";
1.84      albertel 5851:     } else {
1.188     foxr     5852: 	$result = "not_subscribed\n";
1.84      albertel 5853:     }
1.188     foxr     5854: 
1.84      albertel 5855:     return $result;
                   5856: }
                   5857: 
1.101     www      5858: sub currentversion {
                   5859:     my $fname=shift;
                   5860:     my $version=-1;
                   5861:     my $ulsdir='';
                   5862:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   5863:        $ulsdir=$1;
                   5864:     }
1.114     albertel 5865:     my ($fnamere1,$fnamere2);
                   5866:     # remove version if already specified
1.101     www      5867:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 5868:     # get the bits that go before and after the version number
                   5869:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   5870: 	$fnamere1=$1;
                   5871: 	$fnamere2='.'.$2;
                   5872:     }
1.101     www      5873:     if (-e $fname) { $version=1; }
                   5874:     if (-e $ulsdir) {
1.134     albertel 5875: 	if(-d $ulsdir) {
                   5876: 	    if (opendir(LSDIR,$ulsdir)) {
                   5877: 		my $ulsfn;
                   5878: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      5879: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 5880: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   5881: 		    unless (-l $thisfile) {
1.160     www      5882: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 5883: 			    if ($1>$version) { $version=$1; }
                   5884: 			}
                   5885: 		    }
                   5886: 		}
                   5887: 		closedir(LSDIR);
                   5888: 		$version++;
                   5889: 	    }
                   5890: 	}
                   5891:     }
                   5892:     return $version;
1.101     www      5893: }
                   5894: 
                   5895: sub thisversion {
                   5896:     my $fname=shift;
                   5897:     my $version=-1;
                   5898:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   5899: 	$version=$1;
                   5900:     }
                   5901:     return $version;
                   5902: }
                   5903: 
1.84      albertel 5904: sub subscribe {
                   5905:     my ($userinput,$clientip)=@_;
                   5906:     my $result;
1.293     albertel 5907:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 5908:     my $ownership=&ishome($fname);
                   5909:     if ($ownership eq 'owner') {
1.101     www      5910: # explitly asking for the current version?
                   5911:         unless (-e $fname) {
                   5912:             my $currentversion=&currentversion($fname);
                   5913: 	    if (&thisversion($fname)==$currentversion) {
                   5914:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   5915: 		    my $root=$1;
                   5916:                     my $extension=$2;
                   5917:                     symlink($root.'.'.$extension,
                   5918:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      5919:                     unless ($extension=~/\.meta$/) {
                   5920:                        symlink($root.'.'.$extension.'.meta',
                   5921:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   5922: 		    }
1.101     www      5923:                 }
                   5924:             }
                   5925:         }
1.84      albertel 5926: 	if (-e $fname) {
                   5927: 	    if (-d $fname) {
                   5928: 		$result="directory\n";
                   5929: 	    } else {
1.161     foxr     5930: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 5931: 		my $now=time;
1.161     foxr     5932: 		my $found=&addline($fname,$clientname,$clientip,
                   5933: 				   "$clientname:$clientip:$now\n");
1.84      albertel 5934: 		if ($found) { $result="$fname\n"; }
                   5935: 		# if they were subscribed to only meta data, delete that
                   5936:                 # subscription, when you subscribe to a file you also get
                   5937:                 # the metadata
                   5938: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   5939: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
                   5940: 		$fname="http://$thisserver/".$fname;
                   5941: 		$result="$fname\n";
                   5942: 	    }
                   5943: 	} else {
                   5944: 	    $result="not_found\n";
                   5945: 	}
                   5946:     } else {
                   5947: 	$result="rejected\n";
                   5948:     }
                   5949:     return $result;
                   5950: }
1.287     foxr     5951: #  Change the passwd of a unix user.  The caller must have
                   5952: #  first verified that the user is a loncapa user.
                   5953: #
                   5954: # Parameters:
                   5955: #    user      - Unix user name to change.
                   5956: #    pass      - New password for the user.
                   5957: # Returns:
                   5958: #    ok    - if success
                   5959: #    other - Some meaningfule error message string.
                   5960: # NOTE:
                   5961: #    invokes a setuid script to change the passwd.
                   5962: sub change_unix_password {
                   5963:     my ($user, $pass) = @_;
                   5964: 
                   5965:     &Debug("change_unix_password");
                   5966:     my $execdir=$perlvar{'lonDaemons'};
                   5967:     &Debug("Opening lcpasswd pipeline");
                   5968:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   5969: 			   ."$perlvar{'lonDaemons'}"
                   5970: 			   ."/logs/lcpasswd.log");
                   5971:     print $pf "$user\n$pass\n$pass\n";
                   5972:     close $pf;
                   5973:     my $err = $?;
                   5974:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   5975: 	"pwchange_falure - unknown error";
                   5976: 
                   5977:     
                   5978: }
                   5979: 
1.91      albertel 5980: 
                   5981: sub make_passwd_file {
1.98      foxr     5982:     my ($uname, $umode,$npass,$passfilename)=@_;
1.91      albertel 5983:     my $result="ok\n";
                   5984:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   5985: 	{
                   5986: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5987: 	    if ($pf) {
                   5988: 		print $pf "$umode:$npass\n";
                   5989: 	    } else {
                   5990: 		$result = "pass_file_failed_error";
                   5991: 	    }
1.91      albertel 5992: 	}
                   5993:     } elsif ($umode eq 'internal') {
                   5994: 	my $salt=time;
                   5995: 	$salt=substr($salt,6,2);
                   5996: 	my $ncpass=crypt($npass,$salt);
                   5997: 	{
                   5998: 	    &Debug("Creating internal auth");
                   5999: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     6000: 	    if($pf) {
                   6001: 		print $pf "internal:$ncpass\n"; 
                   6002: 	    } else {
                   6003: 		$result = "pass_file_failed_error";
                   6004: 	    }
1.91      albertel 6005: 	}
                   6006:     } elsif ($umode eq 'localauth') {
                   6007: 	{
                   6008: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     6009: 	    if($pf) {
                   6010: 		print $pf "localauth:$npass\n";
                   6011: 	    } else {
                   6012: 		$result = "pass_file_failed_error";
                   6013: 	    }
1.91      albertel 6014: 	}
                   6015:     } elsif ($umode eq 'unix') {
                   6016: 	{
1.186     foxr     6017: 	    #
                   6018: 	    #  Don't allow the creation of privileged accounts!!! that would
                   6019: 	    #  be real bad!!!
                   6020: 	    #
                   6021: 	    my $uid = getpwnam($uname);
                   6022: 	    if((defined $uid) && ($uid == 0)) {
                   6023: 		&logthis(">>>Attempted to create privilged account blocked");
                   6024: 		return "no_priv_account_error\n";
                   6025: 	    }
                   6026: 
1.223     foxr     6027: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224     foxr     6028: 
                   6029: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
1.91      albertel 6030: 	    {
                   6031: 		&Debug("Executing external: ".$execpath);
1.98      foxr     6032: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  6033: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 6034: 		print $se "$uname\n";
                   6035: 		print $se "$npass\n";
                   6036: 		print $se "$npass\n";
1.223     foxr     6037: 		print $se "$lc_error_file\n"; # Status -> unique file.
1.97      foxr     6038: 	    }
1.285     foxr     6039: 	    if (-r $lc_error_file) {
                   6040: 		&Debug("Opening error file: $lc_error_file");
                   6041: 		my $error = IO::File->new("< $lc_error_file");
                   6042: 		my $useraddok = <$error>;
                   6043: 		$error->close;
                   6044: 		unlink($lc_error_file);
                   6045: 		
                   6046: 		chomp $useraddok;
                   6047: 	
                   6048: 		if($useraddok > 0) {
                   6049: 		    my $error_text = &lcuseraddstrerror($useraddok);
                   6050: 		    &logthis("Failed lcuseradd: $error_text");
                   6051: 		    $result = "lcuseradd_failed:$error_text\n";
                   6052: 		}  else {
                   6053: 		    my $pf = IO::File->new(">$passfilename");
                   6054: 		    if($pf) {
                   6055: 			print $pf "unix:\n";
                   6056: 		    } else {
                   6057: 			$result = "pass_file_failed_error";
                   6058: 		    }
                   6059: 		}
1.224     foxr     6060: 	    }  else {
1.285     foxr     6061: 		&Debug("Could not locate lcuseradd error: $lc_error_file");
                   6062: 		$result="bug_lcuseradd_no_output_file";
1.91      albertel 6063: 	    }
                   6064: 	}
                   6065:     } elsif ($umode eq 'none') {
                   6066: 	{
1.223     foxr     6067: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     6068: 	    if($pf) {
                   6069: 		print $pf "none:\n";
                   6070: 	    } else {
                   6071: 		$result = "pass_file_failed_error";
                   6072: 	    }
1.91      albertel 6073: 	}
                   6074:     } else {
                   6075: 	$result="auth_mode_error\n";
                   6076:     }
                   6077:     return $result;
1.121     albertel 6078: }
                   6079: 
1.265     albertel 6080: sub convert_photo {
                   6081:     my ($start,$dest)=@_;
                   6082:     system("convert $start $dest");
                   6083: }
                   6084: 
1.121     albertel 6085: sub sethost {
                   6086:     my ($remotereq) = @_;
                   6087:     my (undef,$hostid)=split(/:/,$remotereq);
                   6088:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
                   6089:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200     matthew  6090: 	$currenthostid  =$hostid;
1.121     albertel 6091: 	$currentdomainid=$hostdom{$hostid};
                   6092: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
                   6093:     } else {
                   6094: 	&logthis("Requested host id $hostid not an alias of ".
                   6095: 		 $perlvar{'lonHostID'}." refusing connection");
                   6096: 	return 'unable_to_set';
                   6097:     }
                   6098:     return 'ok';
                   6099: }
                   6100: 
                   6101: sub version {
                   6102:     my ($userinput)=@_;
                   6103:     $remoteVERSION=(split(/:/,$userinput))[1];
                   6104:     return "version:$VERSION";
1.127     albertel 6105: }
1.178     foxr     6106: 
1.128     albertel 6107: #There is a copy of this in lonnet.pm
1.127     albertel 6108: sub userload {
                   6109:     my $numusers=0;
                   6110:     {
                   6111: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   6112: 	my $filename;
                   6113: 	my $curtime=time;
                   6114: 	while ($filename=readdir(LONIDS)) {
                   6115: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.138     albertel 6116: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159     albertel 6117: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.127     albertel 6118: 	}
                   6119: 	closedir(LONIDS);
                   6120:     }
                   6121:     my $userloadpercent=0;
                   6122:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   6123:     if ($maxuserload) {
1.129     albertel 6124: 	$userloadpercent=100*$numusers/$maxuserload;
1.127     albertel 6125:     }
1.130     albertel 6126:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127     albertel 6127:     return $userloadpercent;
1.91      albertel 6128: }
                   6129: 
1.205     raeburn  6130: # Routines for serializing arrays and hashes (copies from lonnet)
                   6131: 
                   6132: sub array2str {
                   6133:   my (@array) = @_;
                   6134:   my $result=&arrayref2str(\@array);
                   6135:   $result=~s/^__ARRAY_REF__//;
                   6136:   $result=~s/__END_ARRAY_REF__$//;
                   6137:   return $result;
                   6138: }
                   6139:                                                                                  
                   6140: sub arrayref2str {
                   6141:   my ($arrayref) = @_;
                   6142:   my $result='__ARRAY_REF__';
                   6143:   foreach my $elem (@$arrayref) {
                   6144:     if(ref($elem) eq 'ARRAY') {
                   6145:       $result.=&arrayref2str($elem).'&';
                   6146:     } elsif(ref($elem) eq 'HASH') {
                   6147:       $result.=&hashref2str($elem).'&';
                   6148:     } elsif(ref($elem)) {
                   6149:       #print("Got a ref of ".(ref($elem))." skipping.");
                   6150:     } else {
                   6151:       $result.=&escape($elem).'&';
                   6152:     }
                   6153:   }
                   6154:   $result=~s/\&$//;
                   6155:   $result .= '__END_ARRAY_REF__';
                   6156:   return $result;
                   6157: }
                   6158:                                                                                  
                   6159: sub hash2str {
                   6160:   my (%hash) = @_;
                   6161:   my $result=&hashref2str(\%hash);
                   6162:   $result=~s/^__HASH_REF__//;
                   6163:   $result=~s/__END_HASH_REF__$//;
                   6164:   return $result;
                   6165: }
                   6166:                                                                                  
                   6167: sub hashref2str {
                   6168:   my ($hashref)=@_;
                   6169:   my $result='__HASH_REF__';
                   6170:   foreach (sort(keys(%$hashref))) {
                   6171:     if (ref($_) eq 'ARRAY') {
                   6172:       $result.=&arrayref2str($_).'=';
                   6173:     } elsif (ref($_) eq 'HASH') {
                   6174:       $result.=&hashref2str($_).'=';
                   6175:     } elsif (ref($_)) {
                   6176:       $result.='=';
                   6177:       #print("Got a ref of ".(ref($_))." skipping.");
                   6178:     } else {
                   6179:         if ($_) {$result.=&escape($_).'=';} else { last; }
                   6180:     }
                   6181: 
                   6182:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   6183:       $result.=&arrayref2str($hashref->{$_}).'&';
                   6184:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   6185:       $result.=&hashref2str($hashref->{$_}).'&';
                   6186:     } elsif(ref($hashref->{$_})) {
                   6187:        $result.='&';
                   6188:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
                   6189:     } else {
                   6190:       $result.=&escape($hashref->{$_}).'&';
                   6191:     }
                   6192:   }
                   6193:   $result=~s/\&$//;
                   6194:   $result .= '__END_HASH_REF__';
                   6195:   return $result;
                   6196: }
1.200     matthew  6197: 
1.61      harris41 6198: # ----------------------------------- POD (plain old documentation, CPAN style)
                   6199: 
                   6200: =head1 NAME
                   6201: 
                   6202: lond - "LON Daemon" Server (port "LOND" 5663)
                   6203: 
                   6204: =head1 SYNOPSIS
                   6205: 
1.74      harris41 6206: Usage: B<lond>
                   6207: 
                   6208: Should only be run as user=www.  This is a command-line script which
                   6209: is invoked by B<loncron>.  There is no expectation that a typical user
                   6210: will manually start B<lond> from the command-line.  (In other words,
                   6211: DO NOT START B<lond> YOURSELF.)
1.61      harris41 6212: 
                   6213: =head1 DESCRIPTION
                   6214: 
1.74      harris41 6215: There are two characteristics associated with the running of B<lond>,
                   6216: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   6217: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   6218: subscriptions, etc).  These are described in two large
                   6219: sections below.
                   6220: 
                   6221: B<PROCESS MANAGEMENT>
                   6222: 
1.61      harris41 6223: Preforker - server who forks first. Runs as a daemon. HUPs.
                   6224: Uses IDEA encryption
                   6225: 
1.74      harris41 6226: B<lond> forks off children processes that correspond to the other servers
                   6227: in the network.  Management of these processes can be done at the
                   6228: parent process level or the child process level.
                   6229: 
                   6230: B<logs/lond.log> is the location of log messages.
                   6231: 
                   6232: The process management is now explained in terms of linux shell commands,
                   6233: subroutines internal to this code, and signal assignments:
                   6234: 
                   6235: =over 4
                   6236: 
                   6237: =item *
                   6238: 
                   6239: PID is stored in B<logs/lond.pid>
                   6240: 
                   6241: This is the process id number of the parent B<lond> process.
                   6242: 
                   6243: =item *
                   6244: 
                   6245: SIGTERM and SIGINT
                   6246: 
                   6247: Parent signal assignment:
                   6248:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   6249: 
                   6250: Child signal assignment:
                   6251:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   6252: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   6253:  to restart a new child.)
                   6254: 
                   6255: Command-line invocations:
                   6256:  B<kill> B<-s> SIGTERM I<PID>
                   6257:  B<kill> B<-s> SIGINT I<PID>
                   6258: 
                   6259: Subroutine B<HUNTSMAN>:
                   6260:  This is only invoked for the B<lond> parent I<PID>.
                   6261: This kills all the children, and then the parent.
                   6262: The B<lonc.pid> file is cleared.
                   6263: 
                   6264: =item *
                   6265: 
                   6266: SIGHUP
                   6267: 
                   6268: Current bug:
                   6269:  This signal can only be processed the first time
                   6270: on the parent process.  Subsequent SIGHUP signals
                   6271: have no effect.
                   6272: 
                   6273: Parent signal assignment:
                   6274:  $SIG{HUP}  = \&HUPSMAN;
                   6275: 
                   6276: Child signal assignment:
                   6277:  none (nothing happens)
                   6278: 
                   6279: Command-line invocations:
                   6280:  B<kill> B<-s> SIGHUP I<PID>
                   6281: 
                   6282: Subroutine B<HUPSMAN>:
                   6283:  This is only invoked for the B<lond> parent I<PID>,
                   6284: This kills all the children, and then the parent.
                   6285: The B<lond.pid> file is cleared.
                   6286: 
                   6287: =item *
                   6288: 
                   6289: SIGUSR1
                   6290: 
                   6291: Parent signal assignment:
                   6292:  $SIG{USR1} = \&USRMAN;
                   6293: 
                   6294: Child signal assignment:
                   6295:  $SIG{USR1}= \&logstatus;
                   6296: 
                   6297: Command-line invocations:
                   6298:  B<kill> B<-s> SIGUSR1 I<PID>
                   6299: 
                   6300: Subroutine B<USRMAN>:
                   6301:  When invoked for the B<lond> parent I<PID>,
                   6302: SIGUSR1 is sent to all the children, and the status of
                   6303: each connection is logged.
1.144     foxr     6304: 
                   6305: =item *
                   6306: 
                   6307: SIGUSR2
                   6308: 
                   6309: Parent Signal assignment:
                   6310:     $SIG{USR2} = \&UpdateHosts
                   6311: 
                   6312: Child signal assignment:
                   6313:     NONE
                   6314: 
1.74      harris41 6315: 
                   6316: =item *
                   6317: 
                   6318: SIGCHLD
                   6319: 
                   6320: Parent signal assignment:
                   6321:  $SIG{CHLD} = \&REAPER;
                   6322: 
                   6323: Child signal assignment:
                   6324:  none
                   6325: 
                   6326: Command-line invocations:
                   6327:  B<kill> B<-s> SIGCHLD I<PID>
                   6328: 
                   6329: Subroutine B<REAPER>:
                   6330:  This is only invoked for the B<lond> parent I<PID>.
                   6331: Information pertaining to the child is removed.
                   6332: The socket port is cleaned up.
                   6333: 
                   6334: =back
                   6335: 
                   6336: B<SERVER-SIDE ACTIVITIES>
                   6337: 
                   6338: Server-side information can be accepted in an encrypted or non-encrypted
                   6339: method.
                   6340: 
                   6341: =over 4
                   6342: 
                   6343: =item ping
                   6344: 
                   6345: Query a client in the hosts.tab table; "Are you there?"
                   6346: 
                   6347: =item pong
                   6348: 
                   6349: Respond to a ping query.
                   6350: 
                   6351: =item ekey
                   6352: 
                   6353: Read in encrypted key, make cipher.  Respond with a buildkey.
                   6354: 
                   6355: =item load
                   6356: 
                   6357: Respond with CPU load based on a computation upon /proc/loadavg.
                   6358: 
                   6359: =item currentauth
                   6360: 
                   6361: Reply with current authentication information (only over an
                   6362: encrypted channel).
                   6363: 
                   6364: =item auth
                   6365: 
                   6366: Only over an encrypted channel, reply as to whether a user's
                   6367: authentication information can be validated.
                   6368: 
                   6369: =item passwd
                   6370: 
                   6371: Allow for a password to be set.
                   6372: 
                   6373: =item makeuser
                   6374: 
                   6375: Make a user.
                   6376: 
                   6377: =item passwd
                   6378: 
                   6379: Allow for authentication mechanism and password to be changed.
                   6380: 
                   6381: =item home
1.61      harris41 6382: 
1.74      harris41 6383: Respond to a question "are you the home for a given user?"
                   6384: 
                   6385: =item update
                   6386: 
                   6387: Update contents of a subscribed resource.
                   6388: 
                   6389: =item unsubscribe
                   6390: 
                   6391: The server is unsubscribing from a resource.
                   6392: 
                   6393: =item subscribe
                   6394: 
                   6395: The server is subscribing to a resource.
                   6396: 
                   6397: =item log
                   6398: 
                   6399: Place in B<logs/lond.log>
                   6400: 
                   6401: =item put
                   6402: 
                   6403: stores hash in namespace
                   6404: 
1.230     foxr     6405: =item rolesputy
1.74      harris41 6406: 
                   6407: put a role into a user's environment
                   6408: 
                   6409: =item get
                   6410: 
                   6411: returns hash with keys from array
                   6412: reference filled in from namespace
                   6413: 
                   6414: =item eget
                   6415: 
                   6416: returns hash with keys from array
                   6417: reference filled in from namesp (encrypts the return communication)
                   6418: 
                   6419: =item rolesget
                   6420: 
                   6421: get a role from a user's environment
                   6422: 
                   6423: =item del
                   6424: 
                   6425: deletes keys out of array from namespace
                   6426: 
                   6427: =item keys
                   6428: 
                   6429: returns namespace keys
                   6430: 
                   6431: =item dump
                   6432: 
                   6433: dumps the complete (or key matching regexp) namespace into a hash
                   6434: 
                   6435: =item store
                   6436: 
                   6437: stores hash permanently
                   6438: for this url; hashref needs to be given and should be a \%hashname; the
                   6439: remaining args aren't required and if they aren't passed or are '' they will
                   6440: be derived from the ENV
                   6441: 
                   6442: =item restore
                   6443: 
                   6444: returns a hash for a given url
                   6445: 
                   6446: =item querysend
                   6447: 
                   6448: Tells client about the lonsql process that has been launched in response
                   6449: to a sent query.
                   6450: 
                   6451: =item queryreply
                   6452: 
                   6453: Accept information from lonsql and make appropriate storage in temporary
                   6454: file space.
                   6455: 
                   6456: =item idput
                   6457: 
                   6458: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   6459: for each student, defined perhaps by the institutional Registrar.)
                   6460: 
                   6461: =item idget
                   6462: 
                   6463: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   6464: for each student, defined perhaps by the institutional Registrar.)
                   6465: 
                   6466: =item tmpput
                   6467: 
                   6468: Accept and store information in temporary space.
                   6469: 
                   6470: =item tmpget
                   6471: 
                   6472: Send along temporarily stored information.
                   6473: 
                   6474: =item ls
                   6475: 
                   6476: List part of a user's directory.
                   6477: 
1.135     foxr     6478: =item pushtable
                   6479: 
                   6480: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   6481: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   6482: must be restored manually in case of a problem with the new table file.
                   6483: pushtable requires that the request be encrypted and validated via
                   6484: ValidateManager.  The form of the command is:
                   6485: enc:pushtable tablename <tablecontents> \n
                   6486: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   6487: cleartext newline.
                   6488: 
1.74      harris41 6489: =item Hanging up (exit or init)
                   6490: 
                   6491: What to do when a client tells the server that they (the client)
                   6492: are leaving the network.
                   6493: 
                   6494: =item unknown command
                   6495: 
                   6496: If B<lond> is sent an unknown command (not in the list above),
                   6497: it replys to the client "unknown_cmd".
1.135     foxr     6498: 
1.74      harris41 6499: 
                   6500: =item UNKNOWN CLIENT
                   6501: 
                   6502: If the anti-spoofing algorithm cannot verify the client,
                   6503: the client is rejected (with a "refused" message sent
                   6504: to the client, and the connection is closed.
                   6505: 
                   6506: =back
1.61      harris41 6507: 
                   6508: =head1 PREREQUISITES
                   6509: 
                   6510: IO::Socket
                   6511: IO::File
                   6512: Apache::File
                   6513: Symbol
                   6514: POSIX
                   6515: Crypt::IDEA
                   6516: LWP::UserAgent()
                   6517: GDBM_File
                   6518: Authen::Krb4
1.91      albertel 6519: Authen::Krb5
1.61      harris41 6520: 
                   6521: =head1 COREQUISITES
                   6522: 
                   6523: =head1 OSNAMES
                   6524: 
                   6525: linux
                   6526: 
                   6527: =head1 SCRIPT CATEGORIES
                   6528: 
                   6529: Server/Process
                   6530: 
                   6531: =cut

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