Annotation of loncom/lond, revision 1.380.2.1

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

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