Annotation of loncom/lond, revision 1.410.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.410.2.1! raeburn     5: # $Id: lond,v 1.410 2009/01/02 23:07:45 raeburn 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;
                     36: 
1.1       albertel   37: use IO::Socket;
                     38: use IO::File;
1.126     albertel   39: #use Apache::File;
1.1       albertel   40: use POSIX;
                     41: use Crypt::IDEA;
                     42: use LWP::UserAgent();
1.347     raeburn    43: use Digest::MD5 qw(md5_hex);
1.3       www        44: use GDBM_File;
                     45: use Authen::Krb4;
1.91      albertel   46: use Authen::Krb5;
1.49      albertel   47: use localauth;
1.193     raeburn    48: use localenroll;
1.265     albertel   49: use localstudentphoto;
1.143     foxr       50: use File::Copy;
1.292     albertel   51: use File::Find;
1.200     matthew    52: use LONCAPA::lonlocal;
                     53: use LONCAPA::lonssl;
1.221     albertel   54: use Fcntl qw(:flock);
1.383     raeburn    55: use Apache::lonnet;
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.410.2.1! raeburn    62: my $VERSION='$Revision: 1.410 $'; #' 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:    
1.387     albertel  999:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     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;
1.387     albertel 1069:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     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: 
1.387     albertel 1106:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     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.387     albertel 1136:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     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:         }
1.387     albertel 1179: 	&Reply( $replyfd, \$type, $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);
1.387     albertel 1215: 	&Reply($client, \$reply, $userinput);
1.218     foxr     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.399     raeburn  1224: # The du_handler routine should be considered obsolete and is retained
                   1225: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1226: #
1.399     raeburn  1227: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1228: #    
                   1229: #   note: stolen code from the ls file handler
                   1230: #   under construction by Rick Banghart 
                   1231: #    .
                   1232: # Parameters:
                   1233: #    $cmd        - The command that dispatched us (du).
                   1234: #    $ududir     - The directory path to list... I'm not sure what this
                   1235: #                  is relative as things like ls:. return e.g.
                   1236: #                  no_such_dir.
                   1237: #    $client     - Socket open on the client.
                   1238: # Returns:
                   1239: #     1 - indicating that the daemon should not disconnect.
                   1240: # Side Effects:
                   1241: #   The reply is written to  $client.
                   1242: #
                   1243: sub du_handler {
                   1244:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1245:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1246:     my $userinput = "$cmd:$ududir";
                   1247: 
1.245     albertel 1248:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1249: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1250: 	return 1;
                   1251:     }
1.249     foxr     1252:     #  Since $ududir could have some nasties in it,
                   1253:     #  we will require that ududir is a valid
                   1254:     #  directory.  Just in case someone tries to
                   1255:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1256:     #  etc.
                   1257:     #
                   1258:     if (-d $ududir) {
1.292     albertel 1259: 	my $total_size=0;
                   1260: 	my $code=sub { 
                   1261: 	    if ($_=~/\.\d+\./) { return;} 
                   1262: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1263: 	    if (-d $_)         { return;}
1.292     albertel 1264: 	    $total_size+=(stat($_))[7];
                   1265: 	};
1.295     raeburn  1266: 	chdir($ududir);
1.292     albertel 1267: 	find($code,$ududir);
                   1268: 	$total_size=int($total_size/1024);
1.387     albertel 1269: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1270:     } else {
1.251     foxr     1271: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1272:     }
1.243     banghart 1273:     return 1;
                   1274: }
                   1275: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1276: 
1.399     raeburn  1277: # Please also see the du_handler, which is obsoleted by du2. 
                   1278: # du2_handler differs from du_handler in that required path to directory
                   1279: # provided by &propath() is prepended in the handler instead of on the 
                   1280: # client side.
1.239     foxr     1281: #
1.399     raeburn  1282: #   du2  - list the disk usage of a directory recursively.
                   1283: #
                   1284: # Parameters:
                   1285: #    $cmd        - The command that dispatched us (du).
                   1286: #    $tail       - The tail of the request that invoked us.
                   1287: #                  $tail is a : separated list of the following:
                   1288: #                   - $ududir - directory path to list (before prepending)
                   1289: #                   - $getpropath = 1 if &propath() should prepend
                   1290: #                   - $uname - username to use for &propath or user dir
                   1291: #                   - $udom - domain to use for &propath or user dir
                   1292: #                   All are escaped.
                   1293: #    $client     - Socket open on the client.
                   1294: # Returns:
                   1295: #     1 - indicating that the daemon should not disconnect.
                   1296: # Side Effects:
                   1297: #   The reply is written to $client.
                   1298: #
                   1299: 
                   1300: sub du2_handler {
                   1301:     my ($cmd, $tail, $client) = @_;
                   1302:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1303:     my $userinput = "$cmd:$tail";
                   1304:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1305:         &Failure($client,"refused\n","$cmd:$tail");
                   1306:         return 1;
                   1307:     }
                   1308:     if ($getpropath) {
                   1309:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1310:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1311:         } else {
                   1312:             &Failure($client,"refused\n","$cmd:$tail");
                   1313:             return 1;
                   1314:         }
                   1315:     }
                   1316:     #  Since $ududir could have some nasties in it,
                   1317:     #  we will require that ududir is a valid
                   1318:     #  directory.  Just in case someone tries to
                   1319:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1320:     #  etc.
                   1321:     #
                   1322:     if (-d $ududir) {
                   1323:         my $total_size=0;
                   1324:         my $code=sub {
                   1325:             if ($_=~/\.\d+\./) { return;}
                   1326:             if ($_=~/\.meta$/) { return;}
                   1327:             if (-d $_)         { return;}
                   1328:             $total_size+=(stat($_))[7];
                   1329:         };
                   1330:         chdir($ududir);
                   1331:         find($code,$ududir);
                   1332:         $total_size=int($total_size/1024);
                   1333:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1334:     } else {
                   1335:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1336:     }
                   1337:     return 1;
                   1338: }
                   1339: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1340: 
                   1341: #
                   1342: # The ls_handler routine should be considered obsolete and is retained
                   1343: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1344: #
1.239     foxr     1345: #   ls  - list the contents of a directory.  For each file in the
                   1346: #    selected directory the filename followed by the full output of
                   1347: #    the stat function is returned.  The returned info for each
                   1348: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1349: # Parameters:
                   1350: #    $cmd        - The command that dispatched us (ls).
                   1351: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1352: #                  is relative as things like ls:. return e.g.
                   1353: #                  no_such_dir.
                   1354: #    $client     - Socket open on the client.
                   1355: # Returns:
                   1356: #     1 - indicating that the daemon should not disconnect.
                   1357: # Side Effects:
                   1358: #   The reply is written to  $client.
                   1359: #
                   1360: sub ls_handler {
1.280     matthew  1361:     # obsoleted by ls2_handler
1.239     foxr     1362:     my ($cmd, $ulsdir, $client) = @_;
                   1363: 
                   1364:     my $userinput = "$cmd:$ulsdir";
                   1365: 
                   1366:     my $obs;
                   1367:     my $rights;
                   1368:     my $ulsout='';
                   1369:     my $ulsfn;
                   1370:     if (-e $ulsdir) {
                   1371: 	if(-d $ulsdir) {
                   1372: 	    if (opendir(LSDIR,$ulsdir)) {
                   1373: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1374: 		    undef($obs);
                   1375: 		    undef($rights); 
1.239     foxr     1376: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1377: 		    #We do some obsolete checking here
                   1378: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1379: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1380: 			my @obsolete=<FILE>;
                   1381: 			foreach my $obsolete (@obsolete) {
1.301     www      1382: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1383: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1384: 			}
                   1385: 		    }
                   1386: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1387: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1388: 		    else { $ulsout.="&0"; }
                   1389: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1390: 		    else { $ulsout.="&0:"; }
                   1391: 		}
                   1392: 		closedir(LSDIR);
                   1393: 	    }
                   1394: 	} else {
                   1395: 	    my @ulsstats=stat($ulsdir);
                   1396: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1397: 	}
                   1398:     } else {
                   1399: 	$ulsout='no_such_dir';
                   1400:     }
                   1401:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1402:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1403:     
                   1404:     return 1;
                   1405: 
                   1406: }
                   1407: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1408: 
1.399     raeburn  1409: # The ls2_handler routine should be considered obsolete and is retained
                   1410: # for communication with legacy servers.  Please see the ls3_handler.
                   1411: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1412: # ls2_handler differs from ls_handler in that it escapes its return 
                   1413: # values before concatenating them together with ':'s.
                   1414: #
                   1415: #   ls2  - list the contents of a directory.  For each file in the
                   1416: #    selected directory the filename followed by the full output of
                   1417: #    the stat function is returned.  The returned info for each
                   1418: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1419: # Parameters:
                   1420: #    $cmd        - The command that dispatched us (ls).
                   1421: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1422: #                  is relative as things like ls:. return e.g.
                   1423: #                  no_such_dir.
                   1424: #    $client     - Socket open on the client.
                   1425: # Returns:
                   1426: #     1 - indicating that the daemon should not disconnect.
                   1427: # Side Effects:
                   1428: #   The reply is written to  $client.
                   1429: #
                   1430: sub ls2_handler {
                   1431:     my ($cmd, $ulsdir, $client) = @_;
                   1432: 
                   1433:     my $userinput = "$cmd:$ulsdir";
                   1434: 
                   1435:     my $obs;
                   1436:     my $rights;
                   1437:     my $ulsout='';
                   1438:     my $ulsfn;
                   1439:     if (-e $ulsdir) {
                   1440:         if(-d $ulsdir) {
                   1441:             if (opendir(LSDIR,$ulsdir)) {
                   1442:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1443:                     undef($obs);
                   1444: 		    undef($rights); 
1.280     matthew  1445:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1446:                     #We do some obsolete checking here
                   1447:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1448:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1449:                         my @obsolete=<FILE>;
                   1450:                         foreach my $obsolete (@obsolete) {
1.301     www      1451:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1452:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1453:                                 $rights = 1;
                   1454:                             }
                   1455:                         }
                   1456:                     }
                   1457:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1458:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1459:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1460:                     $ulsout.= &escape($tmp).':';
                   1461:                 }
                   1462:                 closedir(LSDIR);
                   1463:             }
                   1464:         } else {
                   1465:             my @ulsstats=stat($ulsdir);
                   1466:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1467:         }
                   1468:     } else {
                   1469:         $ulsout='no_such_dir';
                   1470:    }
                   1471:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1472:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1473:    return 1;
                   1474: }
                   1475: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1476: #
                   1477: #   ls3  - list the contents of a directory.  For each file in the
                   1478: #    selected directory the filename followed by the full output of
                   1479: #    the stat function is returned.  The returned info for each
                   1480: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1481: # Parameters:
                   1482: #    $cmd        - The command that dispatched us (ls).
                   1483: #    $tail       - The tail of the request that invoked us.
                   1484: #                  $tail is a : separated list of the following:
                   1485: #                   - $ulsdir - directory path to list (before prepending)
                   1486: #                   - $getpropath = 1 if &propath() should prepend
                   1487: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1488: #                                     prepend
                   1489: #                   - $alternate_root - path to prepend
                   1490: #                   - $uname - username to use for &propath or user dir
                   1491: #                   - $udom - domain to use for &propath or user dir
                   1492: #            All of these except $getpropath and &getuserdir are escaped.    
                   1493: #                  no_such_dir.
                   1494: #    $client     - Socket open on the client.
                   1495: # Returns:
                   1496: #     1 - indicating that the daemon should not disconnect.
                   1497: # Side Effects:
                   1498: #   The reply is written to $client.
                   1499: #
                   1500: 
                   1501: sub ls3_handler {
                   1502:     my ($cmd, $tail, $client) = @_;
                   1503:     my $userinput = "$cmd:$tail";
                   1504:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1505:         split(/:/,$tail);
                   1506:     if (defined($ulsdir)) {
                   1507:         $ulsdir = &unescape($ulsdir);
                   1508:     }
                   1509:     if (defined($alternate_root)) {
                   1510:         $alternate_root = &unescape($alternate_root);
                   1511:     }
                   1512:     if (defined($uname)) {
                   1513:         $uname = &unescape($uname);
                   1514:     }
                   1515:     if (defined($udom)) {
                   1516:         $udom = &unescape($udom);
                   1517:     }
                   1518: 
                   1519:     my $dir_root = $perlvar{'lonDocRoot'};
                   1520:     if ($getpropath) {
                   1521:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1522:             $dir_root = &propath($udom,$uname);
                   1523:             $dir_root =~ s/\/$//;
                   1524:         } else {
                   1525:             &Failure($client,"refused\n","$cmd:$tail");
                   1526:             return 1;
                   1527:         }
                   1528:     } elsif ($getuserdir) {
                   1529:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1530:             my $subdir=$uname.'__';
                   1531:             $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   1532:             $dir_root = $Apache::lonnet::perlvar{'lonUsersDir'}
                   1533:                        ."/$udom/$subdir/$uname";
                   1534:         } else {
                   1535:             &Failure($client,"refused\n","$cmd:$tail");
                   1536:             return 1;
                   1537:         }
1.400     raeburn  1538:     } elsif ($alternate_root ne '') {
1.399     raeburn  1539:         $dir_root = $alternate_root;
                   1540:     }
1.408     raeburn  1541:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1542:         if ($ulsdir =~ /^\//) {
                   1543:             $ulsdir = $dir_root.$ulsdir;
                   1544:         } else {
                   1545:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1546:         }
1.399     raeburn  1547:     }
                   1548:     my $obs;
                   1549:     my $rights;
                   1550:     my $ulsout='';
                   1551:     my $ulsfn;
                   1552:     if (-e $ulsdir) {
                   1553:         if(-d $ulsdir) {
                   1554:             if (opendir(LSDIR,$ulsdir)) {
                   1555:                 while ($ulsfn=readdir(LSDIR)) {
                   1556:                     undef($obs);
                   1557:                     undef($rights);
                   1558:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1559:                     #We do some obsolete checking here
                   1560:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1561:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1562:                         my @obsolete=<FILE>;
                   1563:                         foreach my $obsolete (@obsolete) {
                   1564:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1565:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1566:                                 $rights = 1;
                   1567:                             }
                   1568:                         }
                   1569:                     }
                   1570:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1571:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1572:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1573:                     $ulsout.= &escape($tmp).':';
                   1574:                 }
                   1575:                 closedir(LSDIR);
                   1576:             }
                   1577:         } else {
                   1578:             my @ulsstats=stat($ulsdir);
                   1579:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1580:         }
                   1581:     } else {
                   1582:         $ulsout='no_such_dir';
1.400     raeburn  1583:     }
                   1584:     if ($ulsout eq '') { $ulsout='empty'; }
                   1585:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1586:     return 1;
1.399     raeburn  1587: }
                   1588: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1589: 
1.410     raeburn  1590: sub server_timezone_handler {
                   1591:     my ($cmd,$tail,$client) = @_;
                   1592:     my $userinput = "$cmd:$tail";
                   1593:     my $timezone;
                   1594:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   1595:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   1596:     if (-e $clockfile) {
                   1597:         if (open(my $fh,"<$clockfile")) {
                   1598:             while (<$fh>) {
                   1599:                 next if (/^[\#\s]/);
                   1600:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   1601:                     $timezone = $1;
                   1602:                     last;
                   1603:                 }
                   1604:             }
                   1605:             close($fh);
                   1606:         }
                   1607:     } elsif (-e $tzfile) {
                   1608:         if (open(my $fh,"<$tzfile")) {
                   1609:             $timezone = <$fh>;
                   1610:             close($fh);
                   1611:             chomp($timezone);
                   1612:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   1613:                 $timezone = $1;
                   1614:             }
                   1615:         }
                   1616:     }
                   1617:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   1618:     return 1;
                   1619: }
                   1620: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   1621: 
1.218     foxr     1622: #   Process a reinit request.  Reinit requests that either
                   1623: #   lonc or lond be reinitialized so that an updated 
                   1624: #   host.tab or domain.tab can be processed.
                   1625: #
                   1626: # Parameters:
                   1627: #      $cmd    - the actual keyword that invoked us.
                   1628: #      $tail   - the tail of the request that invoked us.
                   1629: #      $client - File descriptor connected to the client
                   1630: #  Returns:
                   1631: #      1       - Ok to continue processing.
                   1632: #      0       - Program should exit
                   1633: #  Implicit output:
                   1634: #     a reply is sent to the client.
                   1635: #
                   1636: sub reinit_process_handler {
                   1637:     my ($cmd, $tail, $client) = @_;
                   1638:    
                   1639:     my $userinput = "$cmd:$tail";
                   1640:    
                   1641:     my $cert = &GetCertificate($userinput);
                   1642:     if(&ValidManager($cert)) {
                   1643: 	chomp($userinput);
                   1644: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 1645: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     1646:     } else {
                   1647: 	&Failure( $client, "refused\n", $userinput);
                   1648:     }
                   1649:     return 1;
                   1650: }
                   1651: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   1652: 
                   1653: #  Process the editing script for a table edit operation.
                   1654: #  the editing operation must be encrypted and requested by
                   1655: #  a manager host.
                   1656: #
                   1657: # Parameters:
                   1658: #      $cmd    - the actual keyword that invoked us.
                   1659: #      $tail   - the tail of the request that invoked us.
                   1660: #      $client - File descriptor connected to the client
                   1661: #  Returns:
                   1662: #      1       - Ok to continue processing.
                   1663: #      0       - Program should exit
                   1664: #  Implicit output:
                   1665: #     a reply is sent to the client.
                   1666: #
                   1667: sub edit_table_handler {
                   1668:     my ($command, $tail, $client) = @_;
                   1669:    
                   1670:     my $userinput = "$command:$tail";
                   1671: 
                   1672:     my $cert = &GetCertificate($userinput);
                   1673:     if(&ValidManager($cert)) {
                   1674: 	my($filetype, $script) = split(/:/, $tail);
                   1675: 	if (($filetype eq "hosts") || 
                   1676: 	    ($filetype eq "domain")) {
                   1677: 	    if($script ne "") {
                   1678: 		&Reply($client,              # BUGBUG - EditFile
                   1679: 		      &EditFile($userinput), #   could fail.
                   1680: 		      $userinput);
                   1681: 	    } else {
                   1682: 		&Failure($client,"refused\n",$userinput);
                   1683: 	    }
                   1684: 	} else {
                   1685: 	    &Failure($client,"refused\n",$userinput);
                   1686: 	}
                   1687:     } else {
                   1688: 	&Failure($client,"refused\n",$userinput);
                   1689:     }
                   1690:     return 1;
                   1691: }
1.263     albertel 1692: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     1693: 
1.220     foxr     1694: #
                   1695: #   Authenticate a user against the LonCAPA authentication
                   1696: #   database.  Note that there are several authentication
                   1697: #   possibilities:
                   1698: #   - unix     - The user can be authenticated against the unix
                   1699: #                password file.
                   1700: #   - internal - The user can be authenticated against a purely 
                   1701: #                internal per user password file.
                   1702: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   1703: #                ticket granting authority.
                   1704: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   1705: #                mechanism that is per system.
                   1706: #
                   1707: # Parameters:
                   1708: #    $cmd      - The command that got us here.
                   1709: #    $tail     - Tail of the command (remaining parameters).
                   1710: #    $client   - File descriptor connected to client.
                   1711: # Returns
                   1712: #     0        - Requested to exit, caller should shut down.
                   1713: #     1        - Continue processing.
                   1714: # Implicit inputs:
                   1715: #    The authentication systems describe above have their own forms of implicit
                   1716: #    input into the authentication process that are described above.
                   1717: #
                   1718: sub authenticate_handler {
                   1719:     my ($cmd, $tail, $client) = @_;
                   1720: 
                   1721:     
                   1722:     #  Regenerate the full input line 
                   1723:     
                   1724:     my $userinput  = $cmd.":".$tail;
                   1725:     
                   1726:     #  udom    - User's domain.
                   1727:     #  uname   - Username.
                   1728:     #  upass   - User's password.
1.396     raeburn  1729:     #  checkdefauth - Pass to validate_user() to try authentication
                   1730:     #                 with default auth type(s) if no user account.
1.220     foxr     1731:     
1.396     raeburn  1732:     my ($udom, $uname, $upass, $checkdefauth)=split(/:/,$tail);
1.399     raeburn  1733:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     1734:     chomp($upass);
                   1735:     $upass=&unescape($upass);
                   1736: 
1.396     raeburn  1737:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     1738:     if($pwdcorrect) {
                   1739: 	&Reply( $client, "authorized\n", $userinput);
                   1740: 	#
                   1741: 	#  Bad credentials: Failed to authorize
                   1742: 	#
                   1743:     } else {
                   1744: 	&Failure( $client, "non_authorized\n", $userinput);
                   1745:     }
                   1746: 
                   1747:     return 1;
                   1748: }
1.263     albertel 1749: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     1750: 
1.222     foxr     1751: #
                   1752: #   Change a user's password.  Note that this function is complicated by
                   1753: #   the fact that a user may be authenticated in more than one way:
                   1754: #   At present, we are not able to change the password for all types of
                   1755: #   authentication methods.  Only for:
                   1756: #      unix    - unix password or shadow passoword style authentication.
                   1757: #      local   - Locally written authentication mechanism.
                   1758: #   For now, kerb4 and kerb5 password changes are not supported and result
                   1759: #   in an error.
                   1760: # FUTURE WORK:
                   1761: #    Support kerberos passwd changes?
                   1762: # Parameters:
                   1763: #    $cmd      - The command that got us here.
                   1764: #    $tail     - Tail of the command (remaining parameters).
                   1765: #    $client   - File descriptor connected to client.
                   1766: # Returns
                   1767: #     0        - Requested to exit, caller should shut down.
                   1768: #     1        - Continue processing.
                   1769: # Implicit inputs:
                   1770: #    The authentication systems describe above have their own forms of implicit
                   1771: #    input into the authentication process that are described above.
                   1772: sub change_password_handler {
                   1773:     my ($cmd, $tail, $client) = @_;
                   1774: 
                   1775:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   1776: 
                   1777:     #
                   1778:     #  udom  - user's domain.
                   1779:     #  uname - Username.
                   1780:     #  upass - Current password.
                   1781:     #  npass - New password.
1.346     raeburn  1782:     #  context - Context in which this was called 
                   1783:     #            (preferences or reset_by_email).
1.222     foxr     1784:    
1.346     raeburn  1785:     my ($udom,$uname,$upass,$npass,$context)=split(/:/,$tail);
1.222     foxr     1786: 
                   1787:     $upass=&unescape($upass);
                   1788:     $npass=&unescape($npass);
                   1789:     &Debug("Trying to change password for $uname");
                   1790: 
                   1791:     # First require that the user can be authenticated with their
1.346     raeburn  1792:     # old password unless context was 'reset_by_email':
                   1793:     
                   1794:     my $validated;
                   1795:     if ($context eq 'reset_by_email') {
                   1796:         $validated = 1;
                   1797:     } else {
                   1798:         $validated = &validate_user($udom, $uname, $upass);
                   1799:     }
1.222     foxr     1800:     if($validated) {
                   1801: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   1802: 	
                   1803: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   1804: 	if ($howpwd eq 'internal') {
                   1805: 	    &Debug("internal auth");
                   1806: 	    my $salt=time;
                   1807: 	    $salt=substr($salt,6,2);
                   1808: 	    my $ncpass=crypt($npass,$salt);
                   1809: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
                   1810: 		&logthis("Result of password change for "
                   1811: 			 ."$uname: pwchange_success");
                   1812: 		&Reply($client, "ok\n", $userinput);
                   1813: 	    } else {
                   1814: 		&logthis("Unable to open $uname passwd "               
                   1815: 			 ."to change password");
                   1816: 		&Failure( $client, "non_authorized\n",$userinput);
                   1817: 	    }
1.346     raeburn  1818: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     1819: 	    my $result = &change_unix_password($uname, $npass);
1.222     foxr     1820: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     1821: 		     $result);
1.387     albertel 1822: 	    &Reply($client, \$result, $userinput);
1.222     foxr     1823: 	} else {
                   1824: 	    # this just means that the current password mode is not
                   1825: 	    # one we know how to change (e.g the kerberos auth modes or
                   1826: 	    # locally written auth handler).
                   1827: 	    #
                   1828: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   1829: 	}  
                   1830: 	
1.224     foxr     1831:     } else {
1.222     foxr     1832: 	&Failure( $client, "non_authorized\n", $userinput);
                   1833:     }
                   1834: 
                   1835:     return 1;
                   1836: }
1.263     albertel 1837: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     1838: 
1.225     foxr     1839: #
                   1840: #   Create a new user.  User in this case means a lon-capa user.
                   1841: #   The user must either already exist in some authentication realm
                   1842: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   1843: #   this loncapa system is created.
                   1844: #
                   1845: # Parameters:
                   1846: #    $cmd      - The command that got us here.
                   1847: #    $tail     - Tail of the command (remaining parameters).
                   1848: #    $client   - File descriptor connected to client.
                   1849: # Returns
                   1850: #     0        - Requested to exit, caller should shut down.
                   1851: #     1        - Continue processing.
                   1852: # Implicit inputs:
                   1853: #    The authentication systems describe above have their own forms of implicit
                   1854: #    input into the authentication process that are described above.
                   1855: sub add_user_handler {
                   1856: 
                   1857:     my ($cmd, $tail, $client) = @_;
                   1858: 
                   1859: 
                   1860:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   1861:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   1862: 
                   1863:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   1864: 
                   1865: 
                   1866:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   1867: 	
                   1868: 	my $oldumask=umask(0077);
                   1869: 	chomp($npass);
                   1870: 	$npass=&unescape($npass);
                   1871: 	my $passfilename  = &password_path($udom, $uname);
                   1872: 	&Debug("Password file created will be:".$passfilename);
                   1873: 	if (-e $passfilename) {
                   1874: 	    &Failure( $client, "already_exists\n", $userinput);
                   1875: 	} else {
                   1876: 	    my $fperror='';
1.264     albertel 1877: 	    if (!&mkpath($passfilename)) {
                   1878: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   1879: 		    ."makeuser";
1.225     foxr     1880: 	    }
                   1881: 	    unless ($fperror) {
                   1882: 		my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
1.390     raeburn  1883: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     1884: 	    } else {
1.387     albertel 1885: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     1886: 	    }
                   1887: 	}
                   1888: 	umask($oldumask);
                   1889:     }  else {
                   1890: 	&Failure($client, "not_right_domain\n",
                   1891: 		$userinput);	# Even if we are multihomed.
                   1892:     
                   1893:     }
                   1894:     return 1;
                   1895: 
                   1896: }
                   1897: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   1898: 
                   1899: #
                   1900: #   Change the authentication method of a user.  Note that this may
                   1901: #   also implicitly change the user's password if, for example, the user is
                   1902: #   joining an existing authentication realm.  Known authentication realms at
                   1903: #   this time are:
                   1904: #    internal   - Purely internal password file (only loncapa knows this user)
                   1905: #    local      - Institutionally written authentication module.
                   1906: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   1907: #    kerb4      - kerberos version 4
                   1908: #    kerb5      - kerberos version 5
                   1909: #
                   1910: # Parameters:
                   1911: #    $cmd      - The command that got us here.
                   1912: #    $tail     - Tail of the command (remaining parameters).
                   1913: #    $client   - File descriptor connected to client.
                   1914: # Returns
                   1915: #     0        - Requested to exit, caller should shut down.
                   1916: #     1        - Continue processing.
                   1917: # Implicit inputs:
                   1918: #    The authentication systems describe above have their own forms of implicit
                   1919: #    input into the authentication process that are described above.
1.287     foxr     1920: # NOTE:
                   1921: #   This is also used to change the authentication credential values (e.g. passwd).
                   1922: #   
1.225     foxr     1923: #
                   1924: sub change_authentication_handler {
                   1925: 
                   1926:     my ($cmd, $tail, $client) = @_;
                   1927:    
                   1928:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   1929: 
                   1930:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   1931:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   1932:     if ($udom ne $currentdomainid) {
                   1933: 	&Failure( $client, "not_right_domain\n", $client);
                   1934:     } else {
                   1935: 	
                   1936: 	chomp($npass);
                   1937: 	
                   1938: 	$npass=&unescape($npass);
1.261     foxr     1939: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     1940: 	my $passfilename = &password_path($udom, $uname);
                   1941: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     1942: 	    # If just changing the unix passwd. need to arrange to run
                   1943: 	    # passwd since otherwise make_passwd_file will run
                   1944: 	    # lcuseradd which fails if an account already exists
                   1945: 	    # (to prevent an unscrupulous LONCAPA admin from stealing
                   1946: 	    # an existing account by overwriting it as a LonCAPA account).
                   1947: 
                   1948: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   1949: 		my $result = &change_unix_password($uname, $npass);
                   1950: 		&logthis("Result of password change for $uname: ".$result);
                   1951: 		if ($result eq "ok") {
1.390     raeburn  1952: 		    &Reply($client, \$result);
1.288     albertel 1953: 		} else {
1.387     albertel 1954: 		    &Failure($client, \$result);
1.287     foxr     1955: 		}
1.288     albertel 1956: 	    } else {
1.287     foxr     1957: 		my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
                   1958: 		#
                   1959: 		#  If the current auth mode is internal, and the old auth mode was
                   1960: 		#  unix, or krb*,  and the user is an author for this domain,
                   1961: 		#  re-run manage_permissions for that role in order to be able
                   1962: 		#  to take ownership of the construction space back to www:www
                   1963: 		#
                   1964: 		
                   1965: 		
                   1966: 		if( (($oldauth =~ /^unix/) && ($umode eq "internal")) ||
                   1967: 		    (($oldauth =~ /^internal/) && ($umode eq "unix")) ) { 
                   1968: 		    if(&is_author($udom, $uname)) {
                   1969: 			&Debug(" Need to manage author permissions...");
                   1970: 			&manage_permissions("/$udom/_au", $udom, $uname, "$umode:");
                   1971: 		    }
1.261     foxr     1972: 		}
1.387     albertel 1973: 		&Reply($client, \$result, $userinput);
1.261     foxr     1974: 	    }
                   1975: 	       
                   1976: 
1.225     foxr     1977: 	} else {	       
1.251     foxr     1978: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     1979: 	}
                   1980:     }
                   1981:     return 1;
                   1982: }
                   1983: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   1984: 
                   1985: #
                   1986: #   Determines if this is the home server for a user.  The home server
                   1987: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   1988: #   to do is determine if this file exists.
                   1989: #
                   1990: # Parameters:
                   1991: #    $cmd      - The command that got us here.
                   1992: #    $tail     - Tail of the command (remaining parameters).
                   1993: #    $client   - File descriptor connected to client.
                   1994: # Returns
                   1995: #     0        - Requested to exit, caller should shut down.
                   1996: #     1        - Continue processing.
                   1997: # Implicit inputs:
                   1998: #    The authentication systems describe above have their own forms of implicit
                   1999: #    input into the authentication process that are described above.
                   2000: #
                   2001: sub is_home_handler {
                   2002:     my ($cmd, $tail, $client) = @_;
                   2003:    
                   2004:     my $userinput  = "$cmd:$tail";
                   2005:    
                   2006:     my ($udom,$uname)=split(/:/,$tail);
                   2007:     chomp($uname);
                   2008:     my $passfile = &password_filename($udom, $uname);
                   2009:     if($passfile) {
                   2010: 	&Reply( $client, "found\n", $userinput);
                   2011:     } else {
                   2012: 	&Failure($client, "not_found\n", $userinput);
                   2013:     }
                   2014:     return 1;
                   2015: }
                   2016: &register_handler("home", \&is_home_handler, 0,1,0);
                   2017: 
                   2018: #
                   2019: #   Process an update request for a resource?? I think what's going on here is
                   2020: #   that a resource has been modified that we hold a subscription to.
                   2021: #   If the resource is not local, then we must update, or at least invalidate our
                   2022: #   cached copy of the resource. 
                   2023: #   FUTURE WORK:
                   2024: #      I need to look at this logic carefully.  My druthers would be to follow
                   2025: #      typical caching logic, and simple invalidate the cache, drop any subscription
                   2026: #      an let the next fetch start the ball rolling again... however that may
                   2027: #      actually be more difficult than it looks given the complex web of
                   2028: #      proxy servers.
                   2029: # Parameters:
                   2030: #    $cmd      - The command that got us here.
                   2031: #    $tail     - Tail of the command (remaining parameters).
                   2032: #    $client   - File descriptor connected to client.
                   2033: # Returns
                   2034: #     0        - Requested to exit, caller should shut down.
                   2035: #     1        - Continue processing.
                   2036: # Implicit inputs:
                   2037: #    The authentication systems describe above have their own forms of implicit
                   2038: #    input into the authentication process that are described above.
                   2039: #
                   2040: sub update_resource_handler {
                   2041: 
                   2042:     my ($cmd, $tail, $client) = @_;
                   2043:    
                   2044:     my $userinput = "$cmd:$tail";
                   2045:    
                   2046:     my $fname= $tail;		# This allows interactive testing
                   2047: 
                   2048: 
                   2049:     my $ownership=ishome($fname);
                   2050:     if ($ownership eq 'not_owner') {
                   2051: 	if (-e $fname) {
                   2052: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2053: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2054: 	    my $now=time;
                   2055: 	    my $since=$now-$atime;
                   2056: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2057: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2058: 		&devalidate_meta_cache($fname);
1.225     foxr     2059: 		unlink("$fname");
1.334     albertel 2060: 		unlink("$fname.meta");
1.225     foxr     2061: 	    } else {
                   2062: 		my $transname="$fname.in.transfer";
1.365     albertel 2063: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2064: 		my $response;
                   2065: 		alarm(120);
                   2066: 		{
                   2067: 		    my $ua=new LWP::UserAgent;
                   2068: 		    my $request=new HTTP::Request('GET',"$remoteurl");
                   2069: 		    $response=$ua->request($request,$transname);
                   2070: 		}
                   2071: 		alarm(0);
                   2072: 		if ($response->is_error()) {
                   2073: 		    unlink($transname);
                   2074: 		    my $message=$response->status_line;
                   2075: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2076: 		} else {
                   2077: 		    if ($remoteurl!~/\.meta$/) {
                   2078: 			alarm(120);
                   2079: 			{
                   2080: 			    my $ua=new LWP::UserAgent;
                   2081: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2082: 			    my $mresponse=$ua->request($mrequest,$fname.'.meta');
                   2083: 			    if ($mresponse->is_error()) {
                   2084: 				unlink($fname.'.meta');
                   2085: 			    }
                   2086: 			}
                   2087: 			alarm(0);
                   2088: 		    }
                   2089: 		    rename($transname,$fname);
1.308     albertel 2090: 		    &devalidate_meta_cache($fname);
1.225     foxr     2091: 		}
                   2092: 	    }
                   2093: 	    &Reply( $client, "ok\n", $userinput);
                   2094: 	} else {
                   2095: 	    &Failure($client, "not_found\n", $userinput);
                   2096: 	}
                   2097:     } else {
                   2098: 	&Failure($client, "rejected\n", $userinput);
                   2099:     }
                   2100:     return 1;
                   2101: }
                   2102: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2103: 
1.308     albertel 2104: sub devalidate_meta_cache {
                   2105:     my ($url) = @_;
                   2106:     use Cache::Memcached;
                   2107:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2108:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2109:     $url =~ s-\.meta$--;
                   2110:     my $id = &escape('meta:'.$url);
                   2111:     $memcache->delete($id);
                   2112: }
                   2113: 
1.225     foxr     2114: #
1.226     foxr     2115: #   Fetch a user file from a remote server to the user's home directory
                   2116: #   userfiles subdir.
1.225     foxr     2117: # Parameters:
                   2118: #    $cmd      - The command that got us here.
                   2119: #    $tail     - Tail of the command (remaining parameters).
                   2120: #    $client   - File descriptor connected to client.
                   2121: # Returns
                   2122: #     0        - Requested to exit, caller should shut down.
                   2123: #     1        - Continue processing.
                   2124: #
                   2125: sub fetch_user_file_handler {
                   2126: 
                   2127:     my ($cmd, $tail, $client) = @_;
                   2128: 
                   2129:     my $userinput = "$cmd:$tail";
                   2130:     my $fname           = $tail;
1.232     foxr     2131:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2132:     my $udir=&propath($udom,$uname).'/userfiles';
                   2133:     unless (-e $udir) {
                   2134: 	mkdir($udir,0770); 
                   2135:     }
1.232     foxr     2136:     Debug("fetch user file for $fname");
1.225     foxr     2137:     if (-e $udir) {
                   2138: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2139: 
                   2140: 	# IF necessary, create the path right down to the file.
                   2141: 	# Note that any regular files in the way of this path are
                   2142: 	# wiped out to deal with some earlier folly of mine.
                   2143: 
1.267     raeburn  2144: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2145: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2146: 	}
                   2147: 
1.225     foxr     2148: 	my $destname=$udir.'/'.$ufile;
                   2149: 	my $transname=$udir.'/'.$ufile.'.in.transit';
                   2150: 	my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
                   2151: 	my $response;
1.232     foxr     2152: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.225     foxr     2153: 	alarm(120);
                   2154: 	{
                   2155: 	    my $ua=new LWP::UserAgent;
                   2156: 	    my $request=new HTTP::Request('GET',"$remoteurl");
                   2157: 	    $response=$ua->request($request,$transname);
                   2158: 	}
                   2159: 	alarm(0);
                   2160: 	if ($response->is_error()) {
                   2161: 	    unlink($transname);
                   2162: 	    my $message=$response->status_line;
                   2163: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2164: 	    &Failure($client, "failed\n", $userinput);
                   2165: 	} else {
1.232     foxr     2166: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2167: 	    if (!rename($transname,$destname)) {
                   2168: 		&logthis("Unable to move $transname to $destname");
                   2169: 		unlink($transname);
                   2170: 		&Failure($client, "failed\n", $userinput);
                   2171: 	    } else {
                   2172: 		&Reply($client, "ok\n", $userinput);
                   2173: 	    }
                   2174: 	}   
                   2175:     } else {
                   2176: 	&Failure($client, "not_home\n", $userinput);
                   2177:     }
                   2178:     return 1;
                   2179: }
                   2180: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2181: 
1.226     foxr     2182: #
                   2183: #   Remove a file from a user's home directory userfiles subdirectory.
                   2184: # Parameters:
                   2185: #    cmd   - the Lond request keyword that got us here.
                   2186: #    tail  - the part of the command past the keyword.
                   2187: #    client- File descriptor connected with the client.
                   2188: #
                   2189: # Returns:
                   2190: #    1    - Continue processing.
                   2191: sub remove_user_file_handler {
                   2192:     my ($cmd, $tail, $client) = @_;
                   2193: 
                   2194:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2195: 
                   2196:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2197:     if ($ufile =~m|/\.\./|) {
                   2198: 	# any files paths with /../ in them refuse 
                   2199: 	# to deal with
                   2200: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2201:     } else {
                   2202: 	my $udir = &propath($udom,$uname);
                   2203: 	if (-e $udir) {
                   2204: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2205: 	    if (-e $file) {
1.253     foxr     2206: 		#
                   2207: 		#   If the file is a regular file unlink is fine...
                   2208: 		#   However it's possible the client wants a dir.
                   2209: 		#   removed, in which case rmdir is more approprate:
                   2210: 		#
1.240     banghart 2211: 	        if (-f $file){
1.241     albertel 2212: 		    unlink($file);
                   2213: 		} elsif(-d $file) {
                   2214: 		    rmdir($file);
1.240     banghart 2215: 		}
1.226     foxr     2216: 		if (-e $file) {
1.253     foxr     2217: 		    #  File is still there after we deleted it ?!?
                   2218: 
1.226     foxr     2219: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2220: 		} else {
                   2221: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2222: 		}
                   2223: 	    } else {
                   2224: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2225: 	    }
                   2226: 	} else {
                   2227: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2228: 	}
                   2229:     }
                   2230:     return 1;
                   2231: }
                   2232: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2233: 
1.236     albertel 2234: #
                   2235: #   make a directory in a user's home directory userfiles subdirectory.
                   2236: # Parameters:
                   2237: #    cmd   - the Lond request keyword that got us here.
                   2238: #    tail  - the part of the command past the keyword.
                   2239: #    client- File descriptor connected with the client.
                   2240: #
                   2241: # Returns:
                   2242: #    1    - Continue processing.
                   2243: sub mkdir_user_file_handler {
                   2244:     my ($cmd, $tail, $client) = @_;
                   2245: 
                   2246:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2247:     $dir=&unescape($dir);
                   2248:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2249:     if ($ufile =~m|/\.\./|) {
                   2250: 	# any files paths with /../ in them refuse 
                   2251: 	# to deal with
                   2252: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2253:     } else {
                   2254: 	my $udir = &propath($udom,$uname);
                   2255: 	if (-e $udir) {
1.264     albertel 2256: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2257: 	    if (!&mkpath($newdir)) {
                   2258: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2259: 	    }
1.264     albertel 2260: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2261: 	} else {
                   2262: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2263: 	}
                   2264:     }
                   2265:     return 1;
                   2266: }
                   2267: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2268: 
1.237     albertel 2269: #
                   2270: #   rename a file in a user's home directory userfiles subdirectory.
                   2271: # Parameters:
                   2272: #    cmd   - the Lond request keyword that got us here.
                   2273: #    tail  - the part of the command past the keyword.
                   2274: #    client- File descriptor connected with the client.
                   2275: #
                   2276: # Returns:
                   2277: #    1    - Continue processing.
                   2278: sub rename_user_file_handler {
                   2279:     my ($cmd, $tail, $client) = @_;
                   2280: 
                   2281:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2282:     $old=&unescape($old);
                   2283:     $new=&unescape($new);
                   2284:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2285: 	# any files paths with /../ in them refuse to deal with
                   2286: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2287:     } else {
                   2288: 	my $udir = &propath($udom,$uname);
                   2289: 	if (-e $udir) {
                   2290: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2291: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2292: 	    if (-e $newfile) {
                   2293: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2294: 	    } elsif (! -e $oldfile) {
                   2295: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2296: 	    } else {
                   2297: 		if (!rename($oldfile,$newfile)) {
                   2298: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2299: 		} else {
                   2300: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2301: 		}
                   2302: 	    }
                   2303: 	} else {
                   2304: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2305: 	}
                   2306:     }
                   2307:     return 1;
                   2308: }
                   2309: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2310: 
1.227     foxr     2311: #
1.382     albertel 2312: #  Checks if the specified user has an active session on the server
                   2313: #  return ok if so, not_found if not
                   2314: #
                   2315: # Parameters:
                   2316: #   cmd      - The request keyword that dispatched to tus.
                   2317: #   tail     - The tail of the request (colon separated parameters).
                   2318: #   client   - Filehandle open on the client.
                   2319: # Return:
                   2320: #    1.
                   2321: sub user_has_session_handler {
                   2322:     my ($cmd, $tail, $client) = @_;
                   2323: 
                   2324:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   2325:     
                   2326:     &logthis("Looking for $udom $uname");
                   2327:     opendir(DIR,$perlvar{'lonIDsDir'});
                   2328:     my $filename;
                   2329:     while ($filename=readdir(DIR)) {
                   2330: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   2331:     }
                   2332:     if ($filename) {
                   2333: 	&Reply($client, "ok\n", "$cmd:$tail");
                   2334:     } else {
                   2335: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   2336:     }
                   2337:     return 1;
                   2338: 
                   2339: }
                   2340: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   2341: 
                   2342: #
1.263     albertel 2343: #  Authenticate access to a user file by checking that the token the user's 
                   2344: #  passed also exists in their session file
1.227     foxr     2345: #
                   2346: # Parameters:
                   2347: #   cmd      - The request keyword that dispatched to tus.
                   2348: #   tail     - The tail of the request (colon separated parameters).
                   2349: #   client   - Filehandle open on the client.
                   2350: # Return:
                   2351: #    1.
                   2352: sub token_auth_user_file_handler {
                   2353:     my ($cmd, $tail, $client) = @_;
                   2354: 
                   2355:     my ($fname, $session) = split(/:/, $tail);
                   2356:     
                   2357:     chomp($session);
1.393     raeburn  2358:     my $reply="non_auth";
1.343     albertel 2359:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   2360:     if (open(ENVIN,"$file")) {
1.332     albertel 2361: 	flock(ENVIN,LOCK_SH);
1.343     albertel 2362: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   2363: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  2364: 	    $reply="ok";
1.343     albertel 2365: 	} else {
                   2366: 	    foreach my $envname (keys(%disk_env)) {
                   2367: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  2368: 		    $reply="ok";
1.343     albertel 2369: 		    last;
                   2370: 		}
                   2371: 	    }
1.227     foxr     2372: 	}
1.343     albertel 2373: 	untie(%disk_env);
1.227     foxr     2374: 	close(ENVIN);
1.387     albertel 2375: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     2376:     } else {
                   2377: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2378:     }
                   2379:     return 1;
                   2380: 
                   2381: }
                   2382: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2383: 
                   2384: #
                   2385: #   Unsubscribe from a resource.
                   2386: #
                   2387: # Parameters:
                   2388: #    $cmd      - The command that got us here.
                   2389: #    $tail     - Tail of the command (remaining parameters).
                   2390: #    $client   - File descriptor connected to client.
                   2391: # Returns
                   2392: #     0        - Requested to exit, caller should shut down.
                   2393: #     1        - Continue processing.
                   2394: #
                   2395: sub unsubscribe_handler {
                   2396:     my ($cmd, $tail, $client) = @_;
                   2397: 
                   2398:     my $userinput= "$cmd:$tail";
                   2399:     
                   2400:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   2401: 
                   2402:     &Debug("Unsubscribing $fname");
                   2403:     if (-e $fname) {
                   2404: 	&Debug("Exists");
                   2405: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   2406:     } else {
                   2407: 	&Failure($client, "not_found\n", $userinput);
                   2408:     }
                   2409:     return 1;
                   2410: }
                   2411: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 2412: 
1.230     foxr     2413: #   Subscribe to a resource
                   2414: #
                   2415: # Parameters:
                   2416: #    $cmd      - The command that got us here.
                   2417: #    $tail     - Tail of the command (remaining parameters).
                   2418: #    $client   - File descriptor connected to client.
                   2419: # Returns
                   2420: #     0        - Requested to exit, caller should shut down.
                   2421: #     1        - Continue processing.
                   2422: #
                   2423: sub subscribe_handler {
                   2424:     my ($cmd, $tail, $client)= @_;
                   2425: 
                   2426:     my $userinput  = "$cmd:$tail";
                   2427: 
                   2428:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   2429: 
                   2430:     return 1;
                   2431: }
                   2432: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   2433: 
                   2434: #
1.379     albertel 2435: #   Determine the latest version of a resource (it looks for the highest
                   2436: #   past version and then returns that +1)
1.230     foxr     2437: #
                   2438: # Parameters:
                   2439: #    $cmd      - The command that got us here.
                   2440: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 2441: #                 (Should consist of an absolute path to a file)
1.230     foxr     2442: #    $client   - File descriptor connected to client.
                   2443: # Returns
                   2444: #     0        - Requested to exit, caller should shut down.
                   2445: #     1        - Continue processing.
                   2446: #
                   2447: sub current_version_handler {
                   2448:     my ($cmd, $tail, $client) = @_;
                   2449: 
                   2450:     my $userinput= "$cmd:$tail";
                   2451:    
                   2452:     my $fname   = $tail;
                   2453:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   2454:     return 1;
                   2455: 
                   2456: }
                   2457: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   2458: 
                   2459: #  Make an entry in a user's activity log.
                   2460: #
                   2461: # Parameters:
                   2462: #    $cmd      - The command that got us here.
                   2463: #    $tail     - Tail of the command (remaining parameters).
                   2464: #    $client   - File descriptor connected to client.
                   2465: # Returns
                   2466: #     0        - Requested to exit, caller should shut down.
                   2467: #     1        - Continue processing.
                   2468: #
                   2469: sub activity_log_handler {
                   2470:     my ($cmd, $tail, $client) = @_;
                   2471: 
                   2472: 
                   2473:     my $userinput= "$cmd:$tail";
                   2474: 
                   2475:     my ($udom,$uname,$what)=split(/:/,$tail);
                   2476:     chomp($what);
                   2477:     my $proname=&propath($udom,$uname);
                   2478:     my $now=time;
                   2479:     my $hfh;
                   2480:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   2481: 	print $hfh "$now:$clientname:$what\n";
                   2482: 	&Reply( $client, "ok\n", $userinput); 
                   2483:     } else {
                   2484: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   2485: 		 ."while attempting log\n", 
                   2486: 		 $userinput);
                   2487:     }
                   2488: 
                   2489:     return 1;
                   2490: }
1.263     albertel 2491: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     2492: 
                   2493: #
                   2494: #   Put a namespace entry in a user profile hash.
                   2495: #   My druthers would be for this to be an encrypted interaction too.
                   2496: #   anything that might be an inadvertent covert channel about either
                   2497: #   user authentication or user personal information....
                   2498: #
                   2499: # Parameters:
                   2500: #    $cmd      - The command that got us here.
                   2501: #    $tail     - Tail of the command (remaining parameters).
                   2502: #    $client   - File descriptor connected to client.
                   2503: # Returns
                   2504: #     0        - Requested to exit, caller should shut down.
                   2505: #     1        - Continue processing.
                   2506: #
                   2507: sub put_user_profile_entry {
                   2508:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     2509: 
1.230     foxr     2510:     my $userinput = "$cmd:$tail";
                   2511:     
1.242     raeburn  2512:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     2513:     if ($namespace ne 'roles') {
                   2514: 	chomp($what);
                   2515: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2516: 				  &GDBM_WRCREAT(),"P",$what);
                   2517: 	if($hashref) {
                   2518: 	    my @pairs=split(/\&/,$what);
                   2519: 	    foreach my $pair (@pairs) {
                   2520: 		my ($key,$value)=split(/=/,$pair);
                   2521: 		$hashref->{$key}=$value;
                   2522: 	    }
1.311     albertel 2523: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     2524: 		&Reply( $client, "ok\n", $userinput);
                   2525: 	    } else {
                   2526: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2527: 			"while attempting put\n", 
                   2528: 			$userinput);
                   2529: 	    }
                   2530: 	} else {
1.316     albertel 2531: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     2532: 		     "while attempting put\n", $userinput);
                   2533: 	}
                   2534:     } else {
                   2535:         &Failure( $client, "refused\n", $userinput);
                   2536:     }
                   2537:     
                   2538:     return 1;
                   2539: }
                   2540: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   2541: 
1.283     albertel 2542: #   Put a piece of new data in hash, returns error if entry already exists
                   2543: # Parameters:
                   2544: #    $cmd      - The command that got us here.
                   2545: #    $tail     - Tail of the command (remaining parameters).
                   2546: #    $client   - File descriptor connected to client.
                   2547: # Returns
                   2548: #     0        - Requested to exit, caller should shut down.
                   2549: #     1        - Continue processing.
                   2550: #
                   2551: sub newput_user_profile_entry {
                   2552:     my ($cmd, $tail, $client)  = @_;
                   2553: 
                   2554:     my $userinput = "$cmd:$tail";
                   2555: 
                   2556:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   2557:     if ($namespace eq 'roles') {
                   2558:         &Failure( $client, "refused\n", $userinput);
                   2559: 	return 1;
                   2560:     }
                   2561: 
                   2562:     chomp($what);
                   2563: 
                   2564:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2565: 				 &GDBM_WRCREAT(),"N",$what);
                   2566:     if(!$hashref) {
1.316     albertel 2567: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 2568: 		  "while attempting put\n", $userinput);
                   2569: 	return 1;
                   2570:     }
                   2571: 
                   2572:     my @pairs=split(/\&/,$what);
                   2573:     foreach my $pair (@pairs) {
                   2574: 	my ($key,$value)=split(/=/,$pair);
                   2575: 	if (exists($hashref->{$key})) {
                   2576: 	    &Failure($client, "key_exists: ".$key."\n",$userinput);
                   2577: 	    return 1;
                   2578: 	}
                   2579:     }
                   2580: 
                   2581:     foreach my $pair (@pairs) {
                   2582: 	my ($key,$value)=split(/=/,$pair);
                   2583: 	$hashref->{$key}=$value;
                   2584:     }
                   2585: 
1.311     albertel 2586:     if (&untie_user_hash($hashref)) {
1.283     albertel 2587: 	&Reply( $client, "ok\n", $userinput);
                   2588:     } else {
                   2589: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2590: 		 "while attempting put\n", 
                   2591: 		 $userinput);
                   2592:     }
                   2593:     return 1;
                   2594: }
                   2595: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   2596: 
1.230     foxr     2597: # 
                   2598: #   Increment a profile entry in the user history file.
                   2599: #   The history contains keyword value pairs.  In this case,
                   2600: #   The value itself is a pair of numbers.  The first, the current value
                   2601: #   the second an increment that this function applies to the current
                   2602: #   value.
                   2603: #
                   2604: # Parameters:
                   2605: #    $cmd      - The command that got us here.
                   2606: #    $tail     - Tail of the command (remaining parameters).
                   2607: #    $client   - File descriptor connected to client.
                   2608: # Returns
                   2609: #     0        - Requested to exit, caller should shut down.
                   2610: #     1        - Continue processing.
                   2611: #
                   2612: sub increment_user_value_handler {
                   2613:     my ($cmd, $tail, $client) = @_;
                   2614:     
                   2615:     my $userinput   = "$cmd:$tail";
                   2616:     
                   2617:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   2618:     if ($namespace ne 'roles') {
                   2619:         chomp($what);
                   2620: 	my $hashref = &tie_user_hash($udom, $uname,
                   2621: 				     $namespace, &GDBM_WRCREAT(),
                   2622: 				     "P",$what);
                   2623: 	if ($hashref) {
                   2624: 	    my @pairs=split(/\&/,$what);
                   2625: 	    foreach my $pair (@pairs) {
                   2626: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  2627:                 $value = &unescape($value);
1.230     foxr     2628: 		# We could check that we have a number...
                   2629: 		if (! defined($value) || $value eq '') {
                   2630: 		    $value = 1;
                   2631: 		}
                   2632: 		$hashref->{$key}+=$value;
1.284     raeburn  2633:                 if ($namespace eq 'nohist_resourcetracker') {
                   2634:                     if ($hashref->{$key} < 0) {
                   2635:                         $hashref->{$key} = 0;
                   2636:                     }
                   2637:                 }
1.230     foxr     2638: 	    }
1.311     albertel 2639: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     2640: 		&Reply( $client, "ok\n", $userinput);
                   2641: 	    } else {
                   2642: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2643: 			 "while attempting inc\n", $userinput);
                   2644: 	    }
                   2645: 	} else {
                   2646: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2647: 		     "while attempting inc\n", $userinput);
                   2648: 	}
                   2649:     } else {
                   2650: 	&Failure($client, "refused\n", $userinput);
                   2651:     }
                   2652:     
                   2653:     return 1;
                   2654: }
                   2655: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   2656: 
                   2657: #
                   2658: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   2659: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   2660: #   for a person grants the permissions packaged with that role
                   2661: #   to that user when the role is selected.
                   2662: #
                   2663: # Parameters:
                   2664: #    $cmd       - The command string (rolesput).
                   2665: #    $tail      - The remainder of the request line.  For rolesput this
                   2666: #                 consists of a colon separated list that contains:
                   2667: #                 The domain and user that is granting the role (logged).
                   2668: #                 The domain and user that is getting the role.
                   2669: #                 The roles being granted as a set of & separated pairs.
                   2670: #                 each pair a key value pair.
                   2671: #    $client    - File descriptor connected to the client.
                   2672: # Returns:
                   2673: #     0         - If the daemon should exit
                   2674: #     1         - To continue processing.
                   2675: #
                   2676: #
                   2677: sub roles_put_handler {
                   2678:     my ($cmd, $tail, $client) = @_;
                   2679: 
                   2680:     my $userinput  = "$cmd:$tail";
                   2681: 
                   2682:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   2683:     
                   2684: 
                   2685:     my $namespace='roles';
                   2686:     chomp($what);
                   2687:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2688: 				 &GDBM_WRCREAT(), "P",
                   2689: 				 "$exedom:$exeuser:$what");
                   2690:     #
                   2691:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   2692:     #  handle is open for the minimal amount of time.  Since the flush
                   2693:     #  is done on close this improves the chances the log will be an un-
                   2694:     #  corrupted ordered thing.
                   2695:     if ($hashref) {
1.261     foxr     2696: 	my $pass_entry = &get_auth_type($udom, $uname);
                   2697: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   2698: 	$auth_type = $auth_type.":";
1.230     foxr     2699: 	my @pairs=split(/\&/,$what);
                   2700: 	foreach my $pair (@pairs) {
                   2701: 	    my ($key,$value)=split(/=/,$pair);
                   2702: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     2703: 			       $auth_type);
1.230     foxr     2704: 	    $hashref->{$key}=$value;
                   2705: 	}
1.311     albertel 2706: 	if (&untie_user_hash($hashref)) {
1.230     foxr     2707: 	    &Reply($client, "ok\n", $userinput);
                   2708: 	} else {
                   2709: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2710: 		     "while attempting rolesput\n", $userinput);
                   2711: 	}
                   2712:     } else {
                   2713: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2714: 		 "while attempting rolesput\n", $userinput);
                   2715:     }
                   2716:     return 1;
                   2717: }
                   2718: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   2719: 
                   2720: #
1.231     foxr     2721: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   2722: #  a permissions package associated with the role from the user's profile.
                   2723: #
                   2724: # Parameters:
                   2725: #     $cmd                 - The command (rolesdel)
                   2726: #     $tail                - The remainder of the request line. This consists
                   2727: #                             of:
                   2728: #                             The domain and user requesting the change (logged)
                   2729: #                             The domain and user being changed.
                   2730: #                             The roles being revoked.  These are shipped to us
                   2731: #                             as a bunch of & separated role name keywords.
                   2732: #     $client              - The file handle open on the client.
                   2733: # Returns:
                   2734: #     1                    - Continue processing
                   2735: #     0                    - Exit.
                   2736: #
                   2737: sub roles_delete_handler {
                   2738:     my ($cmd, $tail, $client)  = @_;
                   2739: 
                   2740:     my $userinput    = "$cmd:$tail";
                   2741:    
                   2742:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   2743:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   2744: 	   "what = ".$what);
                   2745:     my $namespace='roles';
                   2746:     chomp($what);
                   2747:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2748: 				 &GDBM_WRCREAT(), "D",
                   2749: 				 "$exedom:$exeuser:$what");
                   2750:     
                   2751:     if ($hashref) {
                   2752: 	my @rolekeys=split(/\&/,$what);
                   2753: 	
                   2754: 	foreach my $key (@rolekeys) {
                   2755: 	    delete $hashref->{$key};
                   2756: 	}
1.315     albertel 2757: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2758: 	    &Reply($client, "ok\n", $userinput);
                   2759: 	} else {
                   2760: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2761: 		     "while attempting rolesdel\n", $userinput);
                   2762: 	}
                   2763:     } else {
                   2764:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2765: 		 "while attempting rolesdel\n", $userinput);
                   2766:     }
                   2767:     
                   2768:     return 1;
                   2769: }
                   2770: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   2771: 
                   2772: # Unencrypted get from a user's profile database.  See 
                   2773: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   2774: # This function retrieves a keyed item from a specific named database in the
                   2775: # user's directory.
                   2776: #
                   2777: # Parameters:
                   2778: #   $cmd             - Command request keyword (get).
                   2779: #   $tail            - Tail of the command.  This is a colon separated list
                   2780: #                      consisting of the domain and username that uniquely
                   2781: #                      identifies the profile,
                   2782: #                      The 'namespace' which selects the gdbm file to 
                   2783: #                      do the lookup in, 
                   2784: #                      & separated list of keys to lookup.  Note that
                   2785: #                      the values are returned as an & separated list too.
                   2786: #   $client          - File descriptor open on the client.
                   2787: # Returns:
                   2788: #   1       - Continue processing.
                   2789: #   0       - Exit.
                   2790: #
                   2791: sub get_profile_entry {
                   2792:     my ($cmd, $tail, $client) = @_;
                   2793: 
                   2794:     my $userinput= "$cmd:$tail";
                   2795:    
                   2796:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2797:     chomp($what);
1.255     foxr     2798: 
1.390     raeburn  2799: 
1.255     foxr     2800:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   2801:     my ($first) = split(/:/,$replystring);
                   2802:     if($first ne "error") {
1.387     albertel 2803: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     2804:     } else {
1.255     foxr     2805: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     2806:     }
                   2807:     return 1;
1.255     foxr     2808: 
                   2809: 
1.231     foxr     2810: }
                   2811: &register_handler("get", \&get_profile_entry, 0,1,0);
                   2812: 
                   2813: #
                   2814: #  Process the encrypted get request.  Note that the request is sent
                   2815: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   2816: #  information about the sensitive keys is given to the snooper.  Just not
                   2817: #  information about the values of the sensitive key.  Hmm if I wanted to
                   2818: #  know these I'd snoop for the egets. Get the profile item names from them
                   2819: #  and then issue a get for them since there's no enforcement of the
                   2820: #  requirement of an encrypted get for particular profile items.  If I
                   2821: #  were re-doing this, I'd force the request to be encrypted as well as the
                   2822: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   2823: #  that would prevent any covert channel snooping.
                   2824: #
                   2825: #  Parameters:
                   2826: #     $cmd               - Command keyword of request (eget).
                   2827: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
                   2828: #     $client            - File open on the client.
                   2829: #  Returns:
                   2830: #     1      - Continue processing
                   2831: #     0      - server should exit.
                   2832: sub get_profile_entry_encrypted {
                   2833:     my ($cmd, $tail, $client) = @_;
                   2834: 
                   2835:     my $userinput = "$cmd:$tail";
                   2836:    
1.339     albertel 2837:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     2838:     chomp($what);
1.255     foxr     2839:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   2840:     my ($first) = split(/:/, $qresult);
                   2841:     if($first ne "error") {
                   2842: 	
                   2843: 	if ($cipher) {
                   2844: 	    my $cmdlength=length($qresult);
                   2845: 	    $qresult.="         ";
                   2846: 	    my $encqresult='';
                   2847: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   2848: 		$encqresult.= unpack("H16", 
                   2849: 				     $cipher->encrypt(substr($qresult,
                   2850: 							     $encidx,
                   2851: 							     8)));
                   2852: 	    }
                   2853: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   2854: 	} else {
1.231     foxr     2855: 		&Failure( $client, "error:no_key\n", $userinput);
                   2856: 	    }
                   2857:     } else {
1.255     foxr     2858: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   2859: 
1.231     foxr     2860:     }
                   2861:     
                   2862:     return 1;
                   2863: }
1.255     foxr     2864: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 2865: 
1.231     foxr     2866: #
                   2867: #   Deletes a key in a user profile database.
                   2868: #   
                   2869: #   Parameters:
                   2870: #       $cmd                  - Command keyword (del).
                   2871: #       $tail                 - Command tail.  IN this case a colon
                   2872: #                               separated list containing:
                   2873: #                               The domain and user that identifies uniquely
                   2874: #                               the identity of the user.
                   2875: #                               The profile namespace (name of the profile
                   2876: #                               database file).
                   2877: #                               & separated list of keywords to delete.
                   2878: #       $client              - File open on client socket.
                   2879: # Returns:
                   2880: #     1   - Continue processing
                   2881: #     0   - Exit server.
                   2882: #
                   2883: #
                   2884: sub delete_profile_entry {
                   2885:     my ($cmd, $tail, $client) = @_;
                   2886: 
                   2887:     my $userinput = "cmd:$tail";
                   2888: 
                   2889:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2890:     chomp($what);
                   2891:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2892: 				 &GDBM_WRCREAT(),
                   2893: 				 "D",$what);
                   2894:     if ($hashref) {
                   2895:         my @keys=split(/\&/,$what);
                   2896: 	foreach my $key (@keys) {
                   2897: 	    delete($hashref->{$key});
                   2898: 	}
1.315     albertel 2899: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2900: 	    &Reply($client, "ok\n", $userinput);
                   2901: 	} else {
                   2902: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2903: 		    "while attempting del\n", $userinput);
                   2904: 	}
                   2905:     } else {
                   2906: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2907: 		 "while attempting del\n", $userinput);
                   2908:     }
                   2909:     return 1;
                   2910: }
                   2911: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 2912: 
1.231     foxr     2913: #
                   2914: #  List the set of keys that are defined in a profile database file.
                   2915: #  A successful reply from this will contain an & separated list of
                   2916: #  the keys. 
                   2917: # Parameters:
                   2918: #     $cmd              - Command request (keys).
                   2919: #     $tail             - Remainder of the request, a colon separated
                   2920: #                         list containing domain/user that identifies the
                   2921: #                         user being queried, and the database namespace
                   2922: #                         (database filename essentially).
                   2923: #     $client           - File open on the client.
                   2924: #  Returns:
                   2925: #    1    - Continue processing.
                   2926: #    0    - Exit the server.
                   2927: #
                   2928: sub get_profile_keys {
                   2929:     my ($cmd, $tail, $client) = @_;
                   2930: 
                   2931:     my $userinput = "$cmd:$tail";
                   2932: 
                   2933:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   2934:     my $qresult='';
                   2935:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2936: 				  &GDBM_READER());
                   2937:     if ($hashref) {
                   2938: 	foreach my $key (keys %$hashref) {
                   2939: 	    $qresult.="$key&";
                   2940: 	}
1.315     albertel 2941: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2942: 	    $qresult=~s/\&$//;
1.387     albertel 2943: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     2944: 	} else {
                   2945: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2946: 		    "while attempting keys\n", $userinput);
                   2947: 	}
                   2948:     } else {
                   2949: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2950: 		 "while attempting keys\n", $userinput);
                   2951:     }
                   2952:    
                   2953:     return 1;
                   2954: }
                   2955: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   2956: 
                   2957: #
                   2958: #   Dump the contents of a user profile database.
                   2959: #   Note that this constitutes a very large covert channel too since
                   2960: #   the dump will return sensitive information that is not encrypted.
                   2961: #   The naive security assumption is that the session negotiation ensures
                   2962: #   our client is trusted and I don't believe that's assured at present.
                   2963: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   2964: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   2965: # 
                   2966: #  Parameters:
                   2967: #     $cmd           - The command request keyword (currentdump).
                   2968: #     $tail          - Remainder of the request, consisting of a colon
                   2969: #                      separated list that has the domain/username and
                   2970: #                      the namespace to dump (database file).
                   2971: #     $client        - file open on the remote client.
                   2972: # Returns:
                   2973: #     1    - Continue processing.
                   2974: #     0    - Exit the server.
                   2975: #
                   2976: sub dump_profile_database {
                   2977:     my ($cmd, $tail, $client) = @_;
                   2978: 
                   2979:     my $userinput = "$cmd:$tail";
                   2980:    
                   2981:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   2982:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2983: 				 &GDBM_READER());
                   2984:     if ($hashref) {
                   2985: 	# Structure of %data:
                   2986: 	# $data{$symb}->{$parameter}=$value;
                   2987: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   2988: 	# since $parameter will be unescaped, we do not
                   2989:  	# have to worry about silly parameter names...
                   2990: 	
                   2991:         my $qresult='';
                   2992: 	my %data = ();                     # A hash of anonymous hashes..
                   2993: 	while (my ($key,$value) = each(%$hashref)) {
                   2994: 	    my ($v,$symb,$param) = split(/:/,$key);
                   2995: 	    next if ($v eq 'version' || $symb eq 'keys');
                   2996: 	    next if (exists($data{$symb}) && 
                   2997: 		     exists($data{$symb}->{$param}) &&
                   2998: 		     $data{$symb}->{'v.'.$param} > $v);
                   2999: 	    $data{$symb}->{$param}=$value;
                   3000: 	    $data{$symb}->{'v.'.$param}=$v;
                   3001: 	}
1.311     albertel 3002: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3003: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3004: 		while(my ($param,$value) = each (%$param_hash)){
                   3005: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3006: 		    #
                   3007: 		    #   Just dump the symb=value pairs separated by &
                   3008: 		    #
                   3009: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3010: 		}
                   3011: 	    }
                   3012: 	    chop($qresult);
1.387     albertel 3013: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3014: 	} else {
                   3015: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3016: 		     "while attempting currentdump\n", $userinput);
                   3017: 	}
                   3018:     } else {
                   3019: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3020: 		"while attempting currentdump\n", $userinput);
                   3021:     }
                   3022: 
                   3023:     return 1;
                   3024: }
                   3025: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3026: 
                   3027: #
                   3028: #   Dump a profile database with an optional regular expression
                   3029: #   to match against the keys.  In this dump, no effort is made
                   3030: #   to separate symb from version information. Presumably the
                   3031: #   databases that are dumped by this command are of a different
                   3032: #   structure.  Need to look at this and improve the documentation of
                   3033: #   both this and the currentdump handler.
                   3034: # Parameters:
                   3035: #    $cmd                     - The command keyword.
                   3036: #    $tail                    - All of the characters after the $cmd:
                   3037: #                               These are expected to be a colon
                   3038: #                               separated list containing:
                   3039: #                               domain/user - identifying the user.
                   3040: #                               namespace   - identifying the database.
                   3041: #                               regexp      - optional regular expression
                   3042: #                                             that is matched against
                   3043: #                                             database keywords to do
                   3044: #                                             selective dumps.
                   3045: #   $client                   - Channel open on the client.
                   3046: # Returns:
                   3047: #    1    - Continue processing.
                   3048: # Side effects:
                   3049: #    response is written to $client.
                   3050: #
                   3051: sub dump_with_regexp {
                   3052:     my ($cmd, $tail, $client) = @_;
                   3053: 
                   3054: 
                   3055:     my $userinput = "$cmd:$tail";
                   3056: 
1.306     albertel 3057:     my ($udom,$uname,$namespace,$regexp,$range)=split(/:/,$tail);
1.231     foxr     3058:     if (defined($regexp)) {
                   3059: 	$regexp=&unescape($regexp);
                   3060:     } else {
                   3061: 	$regexp='.';
                   3062:     }
1.306     albertel 3063:     my ($start,$end);
                   3064:     if (defined($range)) {
                   3065: 	if ($range =~/^(\d+)\-(\d+)$/) {
                   3066: 	    ($start,$end) = ($1,$2);
                   3067: 	} elsif ($range =~/^(\d+)$/) {
                   3068: 	    ($start,$end) = (0,$1);
                   3069: 	} else {
                   3070: 	    undef($range);
                   3071: 	}
                   3072:     }
1.231     foxr     3073:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3074: 				 &GDBM_READER());
                   3075:     if ($hashref) {
                   3076:         my $qresult='';
1.306     albertel 3077: 	my $count=0;
1.231     foxr     3078: 	while (my ($key,$value) = each(%$hashref)) {
                   3079: 	    if ($regexp eq '.') {
1.306     albertel 3080: 		$count++;
                   3081: 		if (defined($range) && $count >= $end)   { last; }
                   3082: 		if (defined($range) && $count <  $start) { next; }
1.231     foxr     3083: 		$qresult.=$key.'='.$value.'&';
                   3084: 	    } else {
                   3085: 		my $unescapeKey = &unescape($key);
                   3086: 		if (eval('$unescapeKey=~/$regexp/')) {
1.306     albertel 3087: 		    $count++;
                   3088: 		    if (defined($range) && $count >= $end)   { last; }
                   3089: 		    if (defined($range) && $count <  $start) { next; }
1.231     foxr     3090: 		    $qresult.="$key=$value&";
                   3091: 		}
                   3092: 	    }
                   3093: 	}
1.311     albertel 3094: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3095: 	    chop($qresult);
1.387     albertel 3096: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3097: 	} else {
                   3098: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3099: 		     "while attempting dump\n", $userinput);
                   3100: 	}
                   3101:     } else {
                   3102: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3103: 		"while attempting dump\n", $userinput);
                   3104:     }
                   3105: 
                   3106:     return 1;
                   3107: }
                   3108: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3109: 
                   3110: #  Store a set of key=value pairs associated with a versioned name.
                   3111: #
                   3112: #  Parameters:
                   3113: #    $cmd                - Request command keyword.
                   3114: #    $tail               - Tail of the request.  This is a colon
                   3115: #                          separated list containing:
                   3116: #                          domain/user - User and authentication domain.
                   3117: #                          namespace   - Name of the database being modified
                   3118: #                          rid         - Resource keyword to modify.
                   3119: #                          what        - new value associated with rid.
                   3120: #
                   3121: #    $client             - Socket open on the client.
                   3122: #
                   3123: #
                   3124: #  Returns:
                   3125: #      1 (keep on processing).
                   3126: #  Side-Effects:
                   3127: #    Writes to the client
                   3128: sub store_handler {
                   3129:     my ($cmd, $tail, $client) = @_;
                   3130:  
                   3131:     my $userinput = "$cmd:$tail";
                   3132: 
                   3133:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
                   3134:     if ($namespace ne 'roles') {
                   3135: 
                   3136: 	chomp($what);
                   3137: 	my @pairs=split(/\&/,$what);
                   3138: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3139: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3140: 				       "$rid:$what");
                   3141: 	if ($hashref) {
                   3142: 	    my $now = time;
                   3143: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
                   3144: 	    my $key;
                   3145: 	    $hashref->{"version:$rid"}++;
                   3146: 	    my $version=$hashref->{"version:$rid"};
                   3147: 	    my $allkeys=''; 
                   3148: 	    foreach my $pair (@pairs) {
                   3149: 		my ($key,$value)=split(/=/,$pair);
                   3150: 		$allkeys.=$key.':';
                   3151: 		$hashref->{"$version:$rid:$key"}=$value;
                   3152: 	    }
                   3153: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3154: 	    $allkeys.='timestamp';
                   3155: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3156: 	    if (&untie_user_hash($hashref)) {
1.231     foxr     3157: 		&Reply($client, "ok\n", $userinput);
                   3158: 	    } else {
                   3159: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3160: 			"while attempting store\n", $userinput);
                   3161: 	    }
                   3162: 	} else {
                   3163: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3164: 		     "while attempting store\n", $userinput);
                   3165: 	}
                   3166:     } else {
                   3167: 	&Failure($client, "refused\n", $userinput);
                   3168:     }
                   3169: 
                   3170:     return 1;
                   3171: }
                   3172: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3173: 
1.323     albertel 3174: #  Modify a set of key=value pairs associated with a versioned name.
                   3175: #
                   3176: #  Parameters:
                   3177: #    $cmd                - Request command keyword.
                   3178: #    $tail               - Tail of the request.  This is a colon
                   3179: #                          separated list containing:
                   3180: #                          domain/user - User and authentication domain.
                   3181: #                          namespace   - Name of the database being modified
                   3182: #                          rid         - Resource keyword to modify.
                   3183: #                          v           - Version item to modify
                   3184: #                          what        - new value associated with rid.
                   3185: #
                   3186: #    $client             - Socket open on the client.
                   3187: #
                   3188: #
                   3189: #  Returns:
                   3190: #      1 (keep on processing).
                   3191: #  Side-Effects:
                   3192: #    Writes to the client
                   3193: sub putstore_handler {
                   3194:     my ($cmd, $tail, $client) = @_;
                   3195:  
                   3196:     my $userinput = "$cmd:$tail";
                   3197: 
                   3198:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3199:     if ($namespace ne 'roles') {
                   3200: 
                   3201: 	chomp($what);
                   3202: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3203: 				       &GDBM_WRCREAT(), "M",
                   3204: 				       "$rid:$v:$what");
                   3205: 	if ($hashref) {
                   3206: 	    my $now = time;
                   3207: 	    my %data = &hash_extract($what);
                   3208: 	    my @allkeys;
                   3209: 	    while (my($key,$value) = each(%data)) {
                   3210: 		push(@allkeys,$key);
                   3211: 		$hashref->{"$v:$rid:$key"} = $value;
                   3212: 	    }
                   3213: 	    my $allkeys = join(':',@allkeys);
                   3214: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3215: 
                   3216: 	    if (&untie_user_hash($hashref)) {
                   3217: 		&Reply($client, "ok\n", $userinput);
                   3218: 	    } else {
                   3219: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3220: 			"while attempting store\n", $userinput);
                   3221: 	    }
                   3222: 	} else {
                   3223: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3224: 		     "while attempting store\n", $userinput);
                   3225: 	}
                   3226:     } else {
                   3227: 	&Failure($client, "refused\n", $userinput);
                   3228:     }
                   3229: 
                   3230:     return 1;
                   3231: }
                   3232: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3233: 
                   3234: sub hash_extract {
                   3235:     my ($str)=@_;
                   3236:     my %hash;
                   3237:     foreach my $pair (split(/\&/,$str)) {
                   3238: 	my ($key,$value)=split(/=/,$pair);
                   3239: 	$hash{$key}=$value;
                   3240:     }
                   3241:     return (%hash);
                   3242: }
                   3243: sub hash_to_str {
                   3244:     my ($hash_ref)=@_;
                   3245:     my $str;
                   3246:     foreach my $key (keys(%$hash_ref)) {
                   3247: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3248:     }
                   3249:     $str=~s/\&$//;
                   3250:     return $str;
                   3251: }
                   3252: 
1.231     foxr     3253: #
                   3254: #  Dump out all versions of a resource that has key=value pairs associated
                   3255: # with it for each version.  These resources are built up via the store
                   3256: # command.
                   3257: #
                   3258: #  Parameters:
                   3259: #     $cmd               - Command keyword.
                   3260: #     $tail              - Remainder of the request which consists of:
                   3261: #                          domain/user   - User and auth. domain.
                   3262: #                          namespace     - name of resource database.
                   3263: #                          rid           - Resource id.
                   3264: #    $client             - socket open on the client.
                   3265: #
                   3266: # Returns:
                   3267: #      1  indicating the caller should not yet exit.
                   3268: # Side-effects:
                   3269: #   Writes a reply to the client.
                   3270: #   The reply is a string of the following shape:
                   3271: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3272: #    Where the 1 above represents version 1.
                   3273: #    this continues for all pairs of keys in all versions.
                   3274: #
                   3275: #
                   3276: #    
                   3277: #
                   3278: sub restore_handler {
                   3279:     my ($cmd, $tail, $client) = @_;
                   3280: 
                   3281:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 3282:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 3283:     $namespace=~s/\//\_/g;
1.350     albertel 3284:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 3285: 
1.231     foxr     3286:     chomp($rid);
                   3287:     my $qresult='';
1.309     albertel 3288:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3289:     if ($hashref) {
                   3290: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3291: 	$qresult.="version=$version&";
                   3292: 	my $scope;
                   3293: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3294: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3295: 	    my @keys=split(/:/,$vkeys);
                   3296: 	    my $key;
                   3297: 	    $qresult.="$scope:keys=$vkeys&";
                   3298: 	    foreach $key (@keys) {
1.309     albertel 3299: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3300: 	    }                                  
                   3301: 	}
1.311     albertel 3302: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3303: 	    $qresult=~s/\&$//;
1.387     albertel 3304: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     3305: 	} else {
                   3306: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3307: 		    "while attempting restore\n", $userinput);
                   3308: 	}
                   3309:     } else {
                   3310: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3311: 		"while attempting restore\n", $userinput);
                   3312:     }
                   3313:   
                   3314:     return 1;
                   3315: 
                   3316: 
                   3317: }
                   3318: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3319: 
                   3320: #
1.324     raeburn  3321: #   Add a chat message to a synchronous discussion board.
1.234     foxr     3322: #
                   3323: # Parameters:
                   3324: #    $cmd                - Request keyword.
                   3325: #    $tail               - Tail of the command. A colon separated list
                   3326: #                          containing:
                   3327: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  3328: #                          cnum    - Course containing the chat board.
                   3329: #                          newpost - Body of the posting.
                   3330: #                          group   - Optional group, if chat board is only 
                   3331: #                                    accessible in a group within the course 
1.234     foxr     3332: #   $client              - Socket open on the client.
                   3333: # Returns:
                   3334: #   1    - Indicating caller should keep on processing.
                   3335: #
                   3336: # Side-effects:
                   3337: #   writes a reply to the client.
                   3338: #
                   3339: #
                   3340: sub send_chat_handler {
                   3341:     my ($cmd, $tail, $client) = @_;
                   3342: 
                   3343:     
                   3344:     my $userinput = "$cmd:$tail";
                   3345: 
1.324     raeburn  3346:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   3347:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     3348:     &Reply($client, "ok\n", $userinput);
                   3349: 
                   3350:     return 1;
                   3351: }
                   3352: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3353: 
1.234     foxr     3354: #
1.324     raeburn  3355: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     3356: #
                   3357: #  Parameters:
                   3358: #    $cmd             - Command keyword that initiated the request.
                   3359: #    $tail            - Remainder of the request after the command
                   3360: #                       keyword.  In this case a colon separated list of
                   3361: #                       chat domain    - Which discussion board.
                   3362: #                       chat id        - Discussion thread(?)
                   3363: #                       domain/user    - Authentication domain and username
                   3364: #                                        of the requesting person.
1.324     raeburn  3365: #                       group          - Optional course group containing
                   3366: #                                        the board.      
1.234     foxr     3367: #   $client           - Socket open on the client program.
                   3368: # Returns:
                   3369: #    1     - continue processing
                   3370: # Side effects:
                   3371: #    Response is written to the client.
                   3372: #
                   3373: sub retrieve_chat_handler {
                   3374:     my ($cmd, $tail, $client) = @_;
                   3375: 
                   3376: 
                   3377:     my $userinput = "$cmd:$tail";
                   3378: 
1.324     raeburn  3379:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     3380:     my $reply='';
1.324     raeburn  3381:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     3382: 	$reply.=&escape($_).':';
                   3383:     }
                   3384:     $reply=~s/\:$//;
1.387     albertel 3385:     &Reply($client, \$reply, $userinput);
1.234     foxr     3386: 
                   3387: 
                   3388:     return 1;
                   3389: }
                   3390: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3391: 
                   3392: #
                   3393: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3394: #  a file for later retrieval.  This prevents sql query results from
                   3395: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3396: #  less of an issue since multiple outstanding requests can be concurrently
                   3397: #  serviced.
                   3398: #
                   3399: #  Parameters:
                   3400: #     $cmd       - COmmand keyword that initiated the request.
                   3401: #     $tail      - Remainder of the command after the keyword.
                   3402: #                  For this function, this consists of a query and
                   3403: #                  3 arguments that are self-documentingly labelled
                   3404: #                  in the original arg1, arg2, arg3.
                   3405: #     $client    - Socket open on the client.
                   3406: # Return:
                   3407: #    1   - Indicating processing should continue.
                   3408: # Side-effects:
                   3409: #    a reply is written to $client.
                   3410: #
                   3411: sub send_query_handler {
                   3412:     my ($cmd, $tail, $client) = @_;
                   3413: 
                   3414: 
                   3415:     my $userinput = "$cmd:$tail";
                   3416: 
                   3417:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3418:     $query=~s/\n*$//g;
                   3419:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   3420: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   3421: 	  $userinput);
                   3422:     
                   3423:     return 1;
                   3424: }
                   3425: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   3426: 
                   3427: #
                   3428: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   3429: #   The query is submitted via a "querysend" transaction.
                   3430: #   There it is passed on to the lonsql daemon, queued and issued to
                   3431: #   mysql.
                   3432: #     This transaction is invoked when the sql transaction is complete
                   3433: #   it stores the query results in flie and indicates query completion.
                   3434: #   presumably local software then fetches this response... I'm guessing
                   3435: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   3436: #   lonsql on completion of the query interacts with the lond of our
                   3437: #   client to do a query reply storing two files:
                   3438: #    - id     - The results of the query.
                   3439: #    - id.end - Indicating the transaction completed. 
                   3440: #    NOTE: id is a unique id assigned to the query and querysend time.
                   3441: # Parameters:
                   3442: #    $cmd        - Command keyword that initiated this request.
                   3443: #    $tail       - Remainder of the tail.  In this case that's a colon
                   3444: #                  separated list containing the query Id and the 
                   3445: #                  results of the query.
                   3446: #    $client     - Socket open on the client.
                   3447: # Return:
                   3448: #    1           - Indicating that we should continue processing.
                   3449: # Side effects:
                   3450: #    ok written to the client.
                   3451: #
                   3452: sub reply_query_handler {
                   3453:     my ($cmd, $tail, $client) = @_;
                   3454: 
                   3455: 
                   3456:     my $userinput = "$cmd:$tail";
                   3457: 
1.339     albertel 3458:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     3459:     my $store;
                   3460:     my $execdir=$perlvar{'lonDaemons'};
                   3461:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   3462: 	$reply=~s/\&/\n/g;
                   3463: 	print $store $reply;
                   3464: 	close $store;
                   3465: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   3466: 	print $store2 "done\n";
                   3467: 	close $store2;
                   3468: 	&Reply($client, "ok\n", $userinput);
                   3469:     } else {
                   3470: 	&Failure($client, "error: ".($!+0)
                   3471: 		." IO::File->new Failed ".
                   3472: 		"while attempting queryreply\n", $userinput);
                   3473:     }
                   3474:  
                   3475: 
                   3476:     return 1;
                   3477: }
                   3478: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   3479: 
                   3480: #
                   3481: #  Process the courseidput request.  Not quite sure what this means
                   3482: #  at the system level sense.  It appears a gdbm file in the 
                   3483: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   3484: #  a set of entries made in that database.
                   3485: #
                   3486: # Parameters:
                   3487: #   $cmd      - The command keyword that initiated this request.
                   3488: #   $tail     - Tail of the command.  In this case consists of a colon
                   3489: #               separated list contaning the domain to apply this to and
                   3490: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  3491: #               Each value is a colon separated list that includes:  
                   3492: #               description, institutional code and course owner.
                   3493: #               For backward compatibility with versions included
                   3494: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   3495: #               code and/or course owner are preserved from the existing 
                   3496: #               record when writing a new record in response to 1.1 or 
                   3497: #               1.2 implementations of lonnet::flushcourselogs().   
                   3498: #                      
1.234     foxr     3499: #   $client   - Socket open on the client.
                   3500: # Returns:
                   3501: #   1    - indicating that processing should continue
                   3502: #
                   3503: # Side effects:
                   3504: #   reply is written to the client.
                   3505: #
                   3506: sub put_course_id_handler {
                   3507:     my ($cmd, $tail, $client) = @_;
                   3508: 
                   3509: 
                   3510:     my $userinput = "$cmd:$tail";
                   3511: 
1.266     raeburn  3512:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     3513:     chomp($what);
                   3514:     my $now=time;
                   3515:     my @pairs=split(/\&/,$what);
                   3516: 
                   3517:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3518:     if ($hashref) {
                   3519: 	foreach my $pair (@pairs) {
1.271     raeburn  3520:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   3521:             $courseinfo =~ s/=/:/g;
1.384     raeburn  3522:             if (defined($hashref->{$key})) {
                   3523:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   3524:                 if (ref($value) eq 'HASH') {
                   3525:                     my @items = ('description','inst_code','owner','type');
                   3526:                     my @new_items = split(/:/,$courseinfo,-1);
                   3527:                     my %storehash; 
                   3528:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  3529:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  3530:                     }
                   3531:                     $hashref->{$key} = 
                   3532:                         &Apache::lonnet::freeze_escape(\%storehash);
                   3533:                     my $unesc_key = &unescape($key);
                   3534:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   3535:                     next;
1.383     raeburn  3536:                 }
1.384     raeburn  3537:             }
                   3538:             my @current_items = split(/:/,$hashref->{$key},-1);
                   3539:             shift(@current_items); # remove description
                   3540:             pop(@current_items);   # remove last access
                   3541:             my $numcurrent = scalar(@current_items);
                   3542:             if ($numcurrent > 3) {
                   3543:                 $numcurrent = 3;
                   3544:             }
                   3545:             my @new_items = split(/:/,$courseinfo,-1);
                   3546:             my $numnew = scalar(@new_items);
                   3547:             if ($numcurrent > 0) {
                   3548:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   3549:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   3550:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  3551:                     }
1.272     raeburn  3552:                 }
                   3553:             }
1.384     raeburn  3554:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     3555: 	}
1.311     albertel 3556: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     3557: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     3558: 	} else {
1.253     foxr     3559: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     3560: 		     ." untie(GDBM) Failed ".
                   3561: 		     "while attempting courseidput\n", $userinput);
                   3562: 	}
                   3563:     } else {
1.253     foxr     3564: 	&Failure($client, "error: ".($!+0)
1.234     foxr     3565: 		 ." tie(GDBM) Failed ".
                   3566: 		 "while attempting courseidput\n", $userinput);
                   3567:     }
                   3568: 
                   3569:     return 1;
                   3570: }
                   3571: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   3572: 
1.383     raeburn  3573: sub put_course_id_hash_handler {
                   3574:     my ($cmd, $tail, $client) = @_;
                   3575:     my $userinput = "$cmd:$tail";
1.384     raeburn  3576:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  3577:     chomp($what);
                   3578:     my $now=time;
                   3579:     my @pairs=split(/\&/,$what);
1.384     raeburn  3580:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  3581:     if ($hashref) {
                   3582:         foreach my $pair (@pairs) {
                   3583:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  3584:             my $unesc_key = &unescape($key);
                   3585:             if ($mode ne 'timeonly') {
                   3586:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   3587:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   3588:                     if (ref($curritems) ne 'HASH') {
                   3589:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   3590:                         my $lasttime = pop(@current_items);
                   3591:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   3592:                     } else {
                   3593:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   3594:                     }
                   3595:                 } 
                   3596:                 $hashref->{$key} = $value;
                   3597:             }
                   3598:             if ($mode ne 'notime') {
                   3599:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   3600:             }
1.383     raeburn  3601:         }
                   3602:         if (&untie_domain_hash($hashref)) {
                   3603:             &Reply($client, "ok\n", $userinput);
                   3604:         } else {
                   3605:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3606:                      "while attempting courseidputhash\n", $userinput);
                   3607:         }
                   3608:     } else {
                   3609:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3610:                   "while attempting courseidputhash\n", $userinput);
                   3611:     }
                   3612:     return 1;
                   3613: }
                   3614: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   3615: 
1.234     foxr     3616: #  Retrieves the value of a course id resource keyword pattern
                   3617: #  defined since a starting date.  Both the starting date and the
                   3618: #  keyword pattern are optional.  If the starting date is not supplied it
                   3619: #  is treated as the beginning of time.  If the pattern is not found,
                   3620: #  it is treatred as "." matching everything.
                   3621: #
                   3622: #  Parameters:
                   3623: #     $cmd     - Command keyword that resulted in us being dispatched.
                   3624: #     $tail    - The remainder of the command that, in this case, consists
                   3625: #                of a colon separated list of:
                   3626: #                 domain   - The domain in which the course database is 
                   3627: #                            defined.
                   3628: #                 since    - Optional parameter describing the minimum
                   3629: #                            time of definition(?) of the resources that
                   3630: #                            will match the dump.
                   3631: #                 description - regular expression that is used to filter
                   3632: #                            the dump.  Only keywords matching this regexp
                   3633: #                            will be used.
1.272     raeburn  3634: #                 institutional code - optional supplied code to filter 
                   3635: #                            the dump. Only courses with an institutional code 
                   3636: #                            that match the supplied code will be returned.
1.336     raeburn  3637: #                 owner    - optional supplied username and domain of owner to
                   3638: #                            filter the dump.  Only courses for which the course
                   3639: #                            owner matches the supplied username and/or domain
                   3640: #                            will be returned. Pre-2.2.0 legacy entries from 
                   3641: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  3642: #                 type     - optional parameter for selection 
                   3643: #                 regexp_ok - if true, allow the supplied institutional code
                   3644: #                            filter to behave as a regular expression.  
                   3645: #                 rtn_as_hash - whether to return the information available for
                   3646: #                            each matched item as a frozen hash of all 
                   3647: #                            key, value pairs in the item's hash, or as a 
                   3648: #                            colon-separated list of (in order) description,
                   3649: #                            institutional code, and course owner.
1.404     raeburn  3650: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   3651: #                                  now or in the future (selfenrollonly = 1).
                   3652: #                 catfilter - filter by course category, assigned to a course 
                   3653: #                             using manually defined categories (i.e., not
1.407     raeburn  3654: #                             self-cataloging based on on institutional code).   
1.404     raeburn  3655: #                 showhidden - include course in results even if course  
1.407     raeburn  3656: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  3657: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   3658: #                           from course catalog will be excluded from results (unless
                   3659: #                           overridden by "showhidden".
                   3660: #
1.234     foxr     3661: #     $client  - The socket open on the client.
                   3662: # Returns:
                   3663: #    1     - Continue processing.
                   3664: # Side Effects:
                   3665: #   a reply is written to $client.
                   3666: sub dump_course_id_handler {
                   3667:     my ($cmd, $tail, $client) = @_;
                   3668:     my $userinput = "$cmd:$tail";
                   3669: 
1.333     raeburn  3670:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  3671:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
                   3672:         $caller) =split(/:/,$tail);
1.397     raeburn  3673:     my $now = time;
1.234     foxr     3674:     if (defined($description)) {
                   3675: 	$description=&unescape($description);
                   3676:     } else {
                   3677: 	$description='.';
                   3678:     }
1.266     raeburn  3679:     if (defined($instcodefilter)) {
                   3680:         $instcodefilter=&unescape($instcodefilter);
                   3681:     } else {
                   3682:         $instcodefilter='.';
                   3683:     }
1.336     raeburn  3684:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  3685:     if (defined($ownerfilter)) {
                   3686:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  3687:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   3688:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   3689:                  $ownerunamefilter = $1;
                   3690:                  $ownerdomfilter = $2;
                   3691:             } else {
                   3692:                 $ownerunamefilter = $ownerfilter;
                   3693:                 $ownerdomfilter = '';
                   3694:             }
                   3695:         }
1.266     raeburn  3696:     } else {
                   3697:         $ownerfilter='.';
                   3698:     }
1.336     raeburn  3699: 
1.282     raeburn  3700:     if (defined($coursefilter)) {
                   3701:         $coursefilter=&unescape($coursefilter);
                   3702:     } else {
                   3703:         $coursefilter='.';
                   3704:     }
1.333     raeburn  3705:     if (defined($typefilter)) {
                   3706:         $typefilter=&unescape($typefilter);
                   3707:     } else {
                   3708:         $typefilter='.';
                   3709:     }
1.344     raeburn  3710:     if (defined($regexp_ok)) {
                   3711:         $regexp_ok=&unescape($regexp_ok);
                   3712:     }
1.401     raeburn  3713:     if (defined($catfilter)) {
                   3714:         $catfilter=&unescape($catfilter);
                   3715:     }
1.384     raeburn  3716:     my $unpack = 1;
                   3717:     if ($description eq '.' && $instcodefilter eq '.' && $coursefilter eq '.' && 
                   3718:         $typefilter eq '.') {
                   3719:         $unpack = 0;
                   3720:     }
                   3721:     if (!defined($since)) { $since=0; }
1.234     foxr     3722:     my $qresult='';
                   3723:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3724:     if ($hashref) {
1.384     raeburn  3725: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  3726:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.398     raeburn  3727:                 %unesc_val,$selfenroll_end,$selfenroll_types);
1.384     raeburn  3728:             $unesc_key = &unescape($key);
                   3729:             if ($unesc_key =~ /^lasttime:/) {
                   3730:                 next;
                   3731:             } else {
                   3732:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   3733:             }
                   3734:             if ($hashref->{$lasttime_key} ne '') {
                   3735:                 $lasttime = $hashref->{$lasttime_key};
                   3736:                 next if ($lasttime<$since);
                   3737:             }
                   3738:             my $items = &Apache::lonnet::thaw_unescape($value);
                   3739:             if (ref($items) eq 'HASH') {
                   3740:                 $is_hash =  1;
                   3741:                 if ($unpack || !$rtn_as_hash) {
                   3742:                     $unesc_val{'descr'} = $items->{'description'};
                   3743:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   3744:                     $unesc_val{'owner'} = $items->{'owner'};
                   3745:                     $unesc_val{'type'} = $items->{'type'};
1.404     raeburn  3746:                 }
                   3747:                 $selfenroll_types = $items->{'selfenroll_types'};
                   3748:                 $selfenroll_end = $items->{'selfenroll_end_date'};
                   3749:                 if ($selfenrollonly) {
                   3750:                     next if (!$selfenroll_types);
                   3751:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   3752:                         next;
1.397     raeburn  3753:                     }
1.404     raeburn  3754:                 }
                   3755:                 if ($catfilter ne '') {
1.406     raeburn  3756:                     next if ($items->{'categories'} eq '');
                   3757:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  3758:                     next if (@categories == 0);
                   3759:                     my @subcats = split('&',$catfilter);
                   3760:                     my $matchcat = 0;
                   3761:                     foreach my $cat (@categories) {
                   3762:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   3763:                             $matchcat = 1;
                   3764:                             last;
                   3765:                         }
                   3766:                     }
                   3767:                     next if (!$matchcat);
1.404     raeburn  3768:                 }
                   3769:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  3770:                     if ($items->{'hidefromcat'} eq 'yes') {
                   3771:                         next if !$showhidden;
1.401     raeburn  3772:                     }
1.384     raeburn  3773:                 }
1.383     raeburn  3774:             } else {
1.401     raeburn  3775:                 next if ($catfilter ne '');
                   3776:                 next if ($selfenrollonly); 
1.384     raeburn  3777:                 $is_hash =  0;
1.388     raeburn  3778:                 my @courseitems = split(/:/,$value);
1.403     raeburn  3779:                 $lasttime = pop(@courseitems);
1.402     raeburn  3780:                 if ($hashref->{$lasttime_key} eq '') {
                   3781:                     next if ($lasttime<$since);
                   3782:                 }
1.384     raeburn  3783: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  3784:             }
1.266     raeburn  3785:             my $match = 1;
1.384     raeburn  3786: 	    if ($description ne '.') {
                   3787:                 if (!$is_hash) {
                   3788:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   3789:                 }
                   3790:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  3791:                     $match = 0;
1.384     raeburn  3792:                 }
1.266     raeburn  3793:             }
1.384     raeburn  3794:             if ($instcodefilter ne '.') {
                   3795:                 if (!$is_hash) {
                   3796:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   3797:                 }
1.344     raeburn  3798:                 if ($regexp_ok) {
1.384     raeburn  3799:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  3800:                         $match = 0;
                   3801:                     }
                   3802:                 } else {
1.384     raeburn  3803:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  3804:                         $match = 0;
                   3805:                     }
1.266     raeburn  3806:                 }
1.234     foxr     3807: 	    }
1.384     raeburn  3808:             if ($ownerfilter ne '.') {
                   3809:                 if (!$is_hash) {
                   3810:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   3811:                 }
1.336     raeburn  3812:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  3813:                     if ($unesc_val{'owner'} =~ /:/) {
                   3814:                         if (eval{$unesc_val{'owner'} !~ 
                   3815:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  3816:                             $match = 0;
                   3817:                         } 
                   3818:                     } else {
1.384     raeburn  3819:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  3820:                             $match = 0;
                   3821:                         }
                   3822:                     }
                   3823:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  3824:                     if ($unesc_val{'owner'} =~ /:/) {
                   3825:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  3826:                              $match = 0;
                   3827:                         }
                   3828:                     } else {
1.384     raeburn  3829:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  3830:                             $match = 0;
                   3831:                         }
                   3832:                     }
                   3833:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  3834:                     if ($unesc_val{'owner'} =~ /:/) {
                   3835:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  3836:                              $match = 0;
                   3837:                         }
                   3838:                     } else {
                   3839:                         if ($ownerdomfilter ne $udom) {
                   3840:                             $match = 0;
                   3841:                         }
                   3842:                     }
1.266     raeburn  3843:                 }
                   3844:             }
1.384     raeburn  3845:             if ($coursefilter ne '.') {
                   3846:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  3847:                     $match = 0;
                   3848:                 }
                   3849:             }
1.384     raeburn  3850:             if ($typefilter ne '.') {
                   3851:                 if (!$is_hash) {
                   3852:                     $unesc_val{'type'} = &unescape($val{'type'});
                   3853:                 }
                   3854:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  3855:                     if ($typefilter ne 'Course') {
                   3856:                         $match = 0;
                   3857:                     }
1.383     raeburn  3858:                 } else {
1.384     raeburn  3859:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  3860:                         $match = 0;
                   3861:                     }
                   3862:                 }
                   3863:             }
1.266     raeburn  3864:             if ($match == 1) {
1.384     raeburn  3865:                 if ($rtn_as_hash) {
                   3866:                     if ($is_hash) {
                   3867:                         $qresult.=$key.'='.$value.'&';
                   3868:                     } else {
1.388     raeburn  3869:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   3870:                                         'inst_code' => &unescape($val{'inst_code'}),
                   3871:                                         'owner'     => &unescape($val{'owner'}),
                   3872:                                         'type'      => &unescape($val{'type'}),
1.384     raeburn  3873:                                       );
                   3874:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   3875:                         $qresult.=$key.'='.$items.'&';
                   3876:                     }
1.383     raeburn  3877:                 } else {
1.384     raeburn  3878:                     if ($is_hash) {
                   3879:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   3880:                                     &escape($unesc_val{'inst_code'}).':'.
                   3881:                                     &escape($unesc_val{'owner'}).'&';
                   3882:                     } else {
                   3883:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   3884:                                     ':'.$val{'owner'}.'&';
                   3885:                     }
1.383     raeburn  3886:                 }
1.266     raeburn  3887:             }
1.234     foxr     3888: 	}
1.311     albertel 3889: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     3890: 	    chop($qresult);
1.387     albertel 3891: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     3892: 	} else {
                   3893: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3894: 		    "while attempting courseiddump\n", $userinput);
                   3895: 	}
                   3896:     } else {
                   3897: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3898: 		"while attempting courseiddump\n", $userinput);
                   3899:     }
                   3900:     return 1;
                   3901: }
                   3902: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     3903: 
                   3904: #
1.348     raeburn  3905: # Puts an unencrypted entry in a namespace db file at the domain level 
                   3906: #
                   3907: # Parameters:
                   3908: #    $cmd      - The command that got us here.
                   3909: #    $tail     - Tail of the command (remaining parameters).
                   3910: #    $client   - File descriptor connected to client.
                   3911: # Returns
                   3912: #     0        - Requested to exit, caller should shut down.
                   3913: #     1        - Continue processing.
                   3914: #  Side effects:
                   3915: #     reply is written to $client.
                   3916: #
                   3917: sub put_domain_handler {
                   3918:     my ($cmd,$tail,$client) = @_;
                   3919: 
                   3920:     my $userinput = "$cmd:$tail";
                   3921: 
                   3922:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   3923:     chomp($what);
                   3924:     my @pairs=split(/\&/,$what);
                   3925:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   3926:                                    "P", $what);
                   3927:     if ($hashref) {
                   3928:         foreach my $pair (@pairs) {
                   3929:             my ($key,$value)=split(/=/,$pair);
                   3930:             $hashref->{$key}=$value;
                   3931:         }
                   3932:         if (&untie_domain_hash($hashref)) {
                   3933:             &Reply($client, "ok\n", $userinput);
                   3934:         } else {
                   3935:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3936:                      "while attempting putdom\n", $userinput);
                   3937:         }
                   3938:     } else {
                   3939:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3940:                   "while attempting putdom\n", $userinput);
                   3941:     }
                   3942: 
                   3943:     return 1;
                   3944: }
                   3945: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   3946: 
                   3947: # Unencrypted get from the namespace database file at the domain level.
                   3948: # This function retrieves a keyed item from a specific named database in the
                   3949: # domain directory.
                   3950: #
                   3951: # Parameters:
                   3952: #   $cmd             - Command request keyword (get).
                   3953: #   $tail            - Tail of the command.  This is a colon separated list
                   3954: #                      consisting of the domain and the 'namespace' 
                   3955: #                      which selects the gdbm file to do the lookup in,
                   3956: #                      & separated list of keys to lookup.  Note that
                   3957: #                      the values are returned as an & separated list too.
                   3958: #   $client          - File descriptor open on the client.
                   3959: # Returns:
                   3960: #   1       - Continue processing.
                   3961: #   0       - Exit.
                   3962: #  Side effects:
                   3963: #     reply is written to $client.
                   3964: #
                   3965: 
                   3966: sub get_domain_handler {
                   3967:     my ($cmd, $tail, $client) = @_;
                   3968: 
                   3969:     my $userinput = "$client:$tail";
                   3970: 
                   3971:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   3972:     chomp($what);
                   3973:     my @queries=split(/\&/,$what);
                   3974:     my $qresult='';
                   3975:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   3976:     if ($hashref) {
                   3977:         for (my $i=0;$i<=$#queries;$i++) {
                   3978:             $qresult.="$hashref->{$queries[$i]}&";
                   3979:         }
                   3980:         if (&untie_domain_hash($hashref)) {
                   3981:             $qresult=~s/\&$//;
1.387     albertel 3982:             &Reply($client, \$qresult, $userinput);
1.348     raeburn  3983:         } else {
                   3984:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3985:                       "while attempting getdom\n",$userinput);
                   3986:         }
                   3987:     } else {
                   3988:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3989:                  "while attempting getdom\n",$userinput);
                   3990:     }
                   3991: 
                   3992:     return 1;
                   3993: }
1.360     raeburn  3994: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
1.348     raeburn  3995: 
                   3996: 
                   3997: #
1.238     foxr     3998: #  Puts an id to a domains id database. 
                   3999: #
                   4000: #  Parameters:
                   4001: #   $cmd     - The command that triggered us.
                   4002: #   $tail    - Remainder of the request other than the command. This is a 
                   4003: #              colon separated list containing:
                   4004: #              $domain  - The domain for which we are writing the id.
                   4005: #              $pairs  - The id info to write... this is and & separated list
                   4006: #                        of keyword=value.
                   4007: #   $client  - Socket open on the client.
                   4008: #  Returns:
                   4009: #    1   - Continue processing.
                   4010: #  Side effects:
                   4011: #     reply is written to $client.
                   4012: #
                   4013: sub put_id_handler {
                   4014:     my ($cmd,$tail,$client) = @_;
                   4015: 
                   4016: 
                   4017:     my $userinput = "$cmd:$tail";
                   4018: 
                   4019:     my ($udom,$what)=split(/:/,$tail);
                   4020:     chomp($what);
                   4021:     my @pairs=split(/\&/,$what);
                   4022:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   4023: 				   "P", $what);
                   4024:     if ($hashref) {
                   4025: 	foreach my $pair (@pairs) {
                   4026: 	    my ($key,$value)=split(/=/,$pair);
                   4027: 	    $hashref->{$key}=$value;
                   4028: 	}
1.311     albertel 4029: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     4030: 	    &Reply($client, "ok\n", $userinput);
                   4031: 	} else {
                   4032: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4033: 		     "while attempting idput\n", $userinput);
                   4034: 	}
                   4035:     } else {
                   4036: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4037: 		  "while attempting idput\n", $userinput);
                   4038:     }
                   4039: 
                   4040:     return 1;
                   4041: }
1.263     albertel 4042: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     4043: 
                   4044: #
                   4045: #  Retrieves a set of id values from the id database.
                   4046: #  Returns an & separated list of results, one for each requested id to the
                   4047: #  client.
                   4048: #
                   4049: # Parameters:
                   4050: #   $cmd       - Command keyword that caused us to be dispatched.
                   4051: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4052: #               domain - the domain whose id table we dump
                   4053: #               ids      Consists of an & separated list of
                   4054: #                        id keywords whose values will be fetched.
                   4055: #                        nonexisting keywords will have an empty value.
                   4056: #   $client    - Socket open on the client.
                   4057: #
                   4058: # Returns:
                   4059: #    1 - indicating processing should continue.
                   4060: # Side effects:
                   4061: #   An & separated list of results is written to $client.
                   4062: #
                   4063: sub get_id_handler {
                   4064:     my ($cmd, $tail, $client) = @_;
                   4065: 
                   4066:     
                   4067:     my $userinput = "$client:$tail";
                   4068:     
                   4069:     my ($udom,$what)=split(/:/,$tail);
                   4070:     chomp($what);
                   4071:     my @queries=split(/\&/,$what);
                   4072:     my $qresult='';
                   4073:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   4074:     if ($hashref) {
                   4075: 	for (my $i=0;$i<=$#queries;$i++) {
                   4076: 	    $qresult.="$hashref->{$queries[$i]}&";
                   4077: 	}
1.311     albertel 4078: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     4079: 	    $qresult=~s/\&$//;
1.387     albertel 4080: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     4081: 	} else {
                   4082: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4083: 		      "while attempting idget\n",$userinput);
                   4084: 	}
                   4085:     } else {
                   4086: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4087: 		 "while attempting idget\n",$userinput);
                   4088:     }
                   4089:     
                   4090:     return 1;
                   4091: }
1.263     albertel 4092: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     4093: 
                   4094: #
1.299     raeburn  4095: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   4096: #
                   4097: # Parameters
                   4098: #   $cmd       - Command keyword that caused us to be dispatched.
                   4099: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4100: #               domain - the domain whose dcmail we are recording
                   4101: #               email    Consists of key=value pair 
                   4102: #                        where key is unique msgid
                   4103: #                        and value is message (in XML)
                   4104: #   $client    - Socket open on the client.
                   4105: #
                   4106: # Returns:
                   4107: #    1 - indicating processing should continue.
                   4108: # Side effects
                   4109: #     reply is written to $client.
                   4110: #
                   4111: sub put_dcmail_handler {
                   4112:     my ($cmd,$tail,$client) = @_;
                   4113:     my $userinput = "$cmd:$tail";
                   4114:                                                                                 
                   4115:     my ($udom,$what)=split(/:/,$tail);
                   4116:     chomp($what);
                   4117:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   4118:     if ($hashref) {
                   4119:         my ($key,$value)=split(/=/,$what);
                   4120:         $hashref->{$key}=$value;
                   4121:     }
1.311     albertel 4122:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  4123:         &Reply($client, "ok\n", $userinput);
                   4124:     } else {
                   4125:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4126:                  "while attempting dcmailput\n", $userinput);
                   4127:     }
                   4128:     return 1;
                   4129: }
                   4130: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   4131: 
                   4132: #
                   4133: # Retrieves broadcast e-mail from nohist_dcmail database
                   4134: # Returns to client an & separated list of key=value pairs,
                   4135: # where key is msgid and value is message information.
                   4136: #
                   4137: # Parameters
                   4138: #   $cmd       - Command keyword that caused us to be dispatched.
                   4139: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4140: #               domain - the domain whose dcmail table we dump
                   4141: #               startfilter - beginning of time window 
                   4142: #               endfilter - end of time window
                   4143: #               sendersfilter - & separated list of username:domain 
                   4144: #                 for senders to search for.
                   4145: #   $client    - Socket open on the client.
                   4146: #
                   4147: # Returns:
                   4148: #    1 - indicating processing should continue.
                   4149: # Side effects
                   4150: #     reply (& separated list of msgid=messageinfo pairs) is 
                   4151: #     written to $client.
                   4152: #
                   4153: sub dump_dcmail_handler {
                   4154:     my ($cmd, $tail, $client) = @_;
                   4155:                                                                                 
                   4156:     my $userinput = "$cmd:$tail";
                   4157:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   4158:     chomp($sendersfilter);
                   4159:     my @senders = ();
                   4160:     if (defined($startfilter)) {
                   4161:         $startfilter=&unescape($startfilter);
                   4162:     } else {
                   4163:         $startfilter='.';
                   4164:     }
                   4165:     if (defined($endfilter)) {
                   4166:         $endfilter=&unescape($endfilter);
                   4167:     } else {
                   4168:         $endfilter='.';
                   4169:     }
                   4170:     if (defined($sendersfilter)) {
                   4171:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 4172: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  4173:     }
                   4174: 
                   4175:     my $qresult='';
                   4176:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   4177:     if ($hashref) {
                   4178:         while (my ($key,$value) = each(%$hashref)) {
                   4179:             my $match = 1;
1.303     albertel 4180:             my ($timestamp,$subj,$uname,$udom) = 
                   4181: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  4182:             $subj = &unescape($subj);
                   4183:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   4184:                 if ($timestamp < $startfilter) {
                   4185:                     $match = 0;
                   4186:                 }
                   4187:             }
                   4188:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   4189:                 if ($timestamp > $endfilter) {
                   4190:                     $match = 0;
                   4191:                 }
                   4192:             }
                   4193:             unless (@senders < 1) {
                   4194:                 unless (grep/^$uname:$udom$/,@senders) {
                   4195:                     $match = 0;
                   4196:                 }
                   4197:             }
                   4198:             if ($match == 1) {
                   4199:                 $qresult.=$key.'='.$value.'&';
                   4200:             }
                   4201:         }
1.311     albertel 4202:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  4203:             chop($qresult);
1.387     albertel 4204:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  4205:         } else {
                   4206:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4207:                     "while attempting dcmaildump\n", $userinput);
                   4208:         }
                   4209:     } else {
                   4210:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4211:                 "while attempting dcmaildump\n", $userinput);
                   4212:     }
                   4213:     return 1;
                   4214: }
                   4215: 
                   4216: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   4217: 
                   4218: #
                   4219: # Puts domain roles in nohist_domainroles database
                   4220: #
                   4221: # Parameters
                   4222: #   $cmd       - Command keyword that caused us to be dispatched.
                   4223: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4224: #               domain - the domain whose roles we are recording  
                   4225: #               role -   Consists of key=value pair
                   4226: #                        where key is unique role
                   4227: #                        and value is start/end date information
                   4228: #   $client    - Socket open on the client.
                   4229: #
                   4230: # Returns:
                   4231: #    1 - indicating processing should continue.
                   4232: # Side effects
                   4233: #     reply is written to $client.
                   4234: #
                   4235: 
                   4236: sub put_domainroles_handler {
                   4237:     my ($cmd,$tail,$client) = @_;
                   4238: 
                   4239:     my $userinput = "$cmd:$tail";
                   4240:     my ($udom,$what)=split(/:/,$tail);
                   4241:     chomp($what);
                   4242:     my @pairs=split(/\&/,$what);
                   4243:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   4244:     if ($hashref) {
                   4245:         foreach my $pair (@pairs) {
                   4246:             my ($key,$value)=split(/=/,$pair);
                   4247:             $hashref->{$key}=$value;
                   4248:         }
1.311     albertel 4249:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  4250:             &Reply($client, "ok\n", $userinput);
                   4251:         } else {
                   4252:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4253:                      "while attempting domroleput\n", $userinput);
                   4254:         }
                   4255:     } else {
                   4256:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4257:                   "while attempting domroleput\n", $userinput);
                   4258:     }
                   4259:                                                                                   
                   4260:     return 1;
                   4261: }
                   4262: 
                   4263: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   4264: 
                   4265: #
                   4266: # Retrieves domain roles from nohist_domainroles database
                   4267: # Returns to client an & separated list of key=value pairs,
                   4268: # where key is role and value is start and end date information.
                   4269: #
                   4270: # Parameters
                   4271: #   $cmd       - Command keyword that caused us to be dispatched.
                   4272: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4273: #               domain - the domain whose domain roles table we dump
                   4274: #   $client    - Socket open on the client.
                   4275: #
                   4276: # Returns:
                   4277: #    1 - indicating processing should continue.
                   4278: # Side effects
                   4279: #     reply (& separated list of role=start/end info pairs) is
                   4280: #     written to $client.
                   4281: #
                   4282: sub dump_domainroles_handler {
                   4283:     my ($cmd, $tail, $client) = @_;
                   4284:                                                                                            
                   4285:     my $userinput = "$cmd:$tail";
                   4286:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   4287:     chomp($rolesfilter);
                   4288:     my @roles = ();
                   4289:     if (defined($startfilter)) {
                   4290:         $startfilter=&unescape($startfilter);
                   4291:     } else {
                   4292:         $startfilter='.';
                   4293:     }
                   4294:     if (defined($endfilter)) {
                   4295:         $endfilter=&unescape($endfilter);
                   4296:     } else {
                   4297:         $endfilter='.';
                   4298:     }
                   4299:     if (defined($rolesfilter)) {
                   4300:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 4301: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  4302:     }
                   4303:                                                                                            
                   4304:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   4305:     if ($hashref) {
                   4306:         my $qresult = '';
                   4307:         while (my ($key,$value) = each(%$hashref)) {
                   4308:             my $match = 1;
                   4309:             my ($start,$end) = split(/:/,&unescape($value));
                   4310:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
                   4311:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.410.2.1! raeburn  4312:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  4313:                     $match = 0;
                   4314:                 }
                   4315:             }
                   4316:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.410.2.1! raeburn  4317:                 if ((defined($end)) && ($end <= $endfilter)) {
1.299     raeburn  4318:                     $match = 0;
                   4319:                 }
                   4320:             }
                   4321:             unless (@roles < 1) {
1.389     raeburn  4322:                 unless (grep/^\Q$trole\E$/,@roles) {
1.299     raeburn  4323:                     $match = 0;
                   4324:                 }
                   4325:             }
                   4326:             if ($match == 1) {
                   4327:                 $qresult.=$key.'='.$value.'&';
                   4328:             }
                   4329:         }
1.311     albertel 4330:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  4331:             chop($qresult);
1.387     albertel 4332:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  4333:         } else {
                   4334:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4335:                     "while attempting domrolesdump\n", $userinput);
                   4336:         }
                   4337:     } else {
                   4338:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4339:                 "while attempting domrolesdump\n", $userinput);
                   4340:     }
                   4341:     return 1;
                   4342: }
                   4343: 
                   4344: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   4345: 
                   4346: 
1.238     foxr     4347: #  Process the tmpput command I'm not sure what this does.. Seems to
                   4348: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   4349: # where Id is the client's ip concatenated with a sequence number.
                   4350: # The file will contain some value that is passed in.  Is this e.g.
                   4351: # a login token?
                   4352: #
                   4353: # Parameters:
                   4354: #    $cmd     - The command that got us dispatched.
                   4355: #    $tail    - The remainder of the request following $cmd:
                   4356: #               In this case this will be the contents of the file.
                   4357: #    $client  - Socket connected to the client.
                   4358: # Returns:
                   4359: #    1 indicating processing can continue.
                   4360: # Side effects:
                   4361: #   A file is created in the local filesystem.
                   4362: #   A reply is sent to the client.
                   4363: sub tmp_put_handler {
                   4364:     my ($cmd, $what, $client) = @_;
                   4365: 
                   4366:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   4367: 
1.347     raeburn  4368:     my ($record,$context) = split(/:/,$what);
                   4369:     if ($context ne '') {
                   4370:         chomp($context);
                   4371:         $context = &unescape($context);
                   4372:     }
                   4373:     my ($id,$store);
1.238     foxr     4374:     $tmpsnum++;
1.347     raeburn  4375:     if ($context eq 'resetpw') {
                   4376:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   4377:     } else {
                   4378:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   4379:     }
1.238     foxr     4380:     $id=~s/\W/\_/g;
1.347     raeburn  4381:     $record=~s/\n//g;
1.238     foxr     4382:     my $execdir=$perlvar{'lonDaemons'};
                   4383:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  4384: 	print $store $record;
1.238     foxr     4385: 	close $store;
1.387     albertel 4386: 	&Reply($client, \$id, $userinput);
1.238     foxr     4387:     } else {
                   4388: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   4389: 		  "while attempting tmpput\n", $userinput);
                   4390:     }
                   4391:     return 1;
                   4392:   
                   4393: }
                   4394: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 4395: 
1.238     foxr     4396: #   Processes the tmpget command.  This command returns the contents
                   4397: #  of a temporary resource file(?) created via tmpput.
                   4398: #
                   4399: # Paramters:
                   4400: #    $cmd      - Command that got us dispatched.
                   4401: #    $id       - Tail of the command, contain the id of the resource
                   4402: #                we want to fetch.
                   4403: #    $client   - socket open on the client.
                   4404: # Return:
                   4405: #    1         - Inidcating processing can continue.
                   4406: # Side effects:
                   4407: #   A reply is sent to the client.
                   4408: #
                   4409: sub tmp_get_handler {
                   4410:     my ($cmd, $id, $client) = @_;
                   4411: 
                   4412:     my $userinput = "$cmd:$id"; 
                   4413:     
                   4414: 
                   4415:     $id=~s/\W/\_/g;
                   4416:     my $store;
                   4417:     my $execdir=$perlvar{'lonDaemons'};
                   4418:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   4419: 	my $reply=<$store>;
1.387     albertel 4420: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     4421: 	close $store;
                   4422:     } else {
                   4423: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   4424: 		  "while attempting tmpget\n", $userinput);
                   4425:     }
                   4426: 
                   4427:     return 1;
                   4428: }
                   4429: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 4430: 
1.238     foxr     4431: #
                   4432: #  Process the tmpdel command.  This command deletes a temp resource
                   4433: #  created by the tmpput command.
                   4434: #
                   4435: # Parameters:
                   4436: #   $cmd      - Command that got us here.
                   4437: #   $id       - Id of the temporary resource created.
                   4438: #   $client   - socket open on the client process.
                   4439: #
                   4440: # Returns:
                   4441: #   1     - Indicating processing should continue.
                   4442: # Side Effects:
                   4443: #   A file is deleted
                   4444: #   A reply is sent to the client.
                   4445: sub tmp_del_handler {
                   4446:     my ($cmd, $id, $client) = @_;
                   4447:     
                   4448:     my $userinput= "$cmd:$id";
                   4449:     
                   4450:     chomp($id);
                   4451:     $id=~s/\W/\_/g;
                   4452:     my $execdir=$perlvar{'lonDaemons'};
                   4453:     if (unlink("$execdir/tmp/$id.tmp")) {
                   4454: 	&Reply($client, "ok\n", $userinput);
                   4455:     } else {
                   4456: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   4457: 		  "while attempting tmpdel\n", $userinput);
                   4458:     }
                   4459:     
                   4460:     return 1;
                   4461: 
                   4462: }
                   4463: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 4464: 
1.238     foxr     4465: #
1.246     foxr     4466: #   Processes the setannounce command.  This command
                   4467: #   creates a file named announce.txt in the top directory of
                   4468: #   the documentn root and sets its contents.  The announce.txt file is
                   4469: #   printed in its entirety at the LonCAPA login page.  Note:
                   4470: #   once the announcement.txt fileis created it cannot be deleted.
                   4471: #   However, setting the contents of the file to empty removes the
                   4472: #   announcement from the login page of loncapa so who cares.
                   4473: #
                   4474: # Parameters:
                   4475: #    $cmd          - The command that got us dispatched.
                   4476: #    $announcement - The text of the announcement.
                   4477: #    $client       - Socket open on the client process.
                   4478: # Retunrns:
                   4479: #   1             - Indicating request processing should continue
                   4480: # Side Effects:
                   4481: #   The file {DocRoot}/announcement.txt is created.
                   4482: #   A reply is sent to $client.
                   4483: #
                   4484: sub set_announce_handler {
                   4485:     my ($cmd, $announcement, $client) = @_;
                   4486:   
                   4487:     my $userinput    = "$cmd:$announcement";
                   4488: 
                   4489:     chomp($announcement);
                   4490:     $announcement=&unescape($announcement);
                   4491:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   4492: 				'/announcement.txt')) {
                   4493: 	print $store $announcement;
                   4494: 	close $store;
                   4495: 	&Reply($client, "ok\n", $userinput);
                   4496:     } else {
                   4497: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   4498:     }
                   4499: 
                   4500:     return 1;
                   4501: }
                   4502: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 4503: 
1.246     foxr     4504: #
                   4505: #  Return the version of the daemon.  This can be used to determine
                   4506: #  the compatibility of cross version installations or, alternatively to
                   4507: #  simply know who's out of date and who isn't.  Note that the version
                   4508: #  is returned concatenated with the tail.
                   4509: # Parameters:
                   4510: #   $cmd        - the request that dispatched to us.
                   4511: #   $tail       - Tail of the request (client's version?).
                   4512: #   $client     - Socket open on the client.
                   4513: #Returns:
                   4514: #   1 - continue processing requests.
                   4515: # Side Effects:
                   4516: #   Replies with version to $client.
                   4517: sub get_version_handler {
                   4518:     my ($cmd, $tail, $client) = @_;
                   4519: 
                   4520:     my $userinput  = $cmd.$tail;
                   4521:     
                   4522:     &Reply($client, &version($userinput)."\n", $userinput);
                   4523: 
                   4524: 
                   4525:     return 1;
                   4526: }
                   4527: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 4528: 
1.246     foxr     4529: #  Set the current host and domain.  This is used to support
                   4530: #  multihomed systems.  Each IP of the system, or even separate daemons
                   4531: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   4532: #  machine.  This command selects the virtual lonCAPA.  The client always
                   4533: #  knows the right one since it is lonc and it is selecting the domain/system
                   4534: #  from the hosts.tab file.
                   4535: # Parameters:
                   4536: #    $cmd      - Command that dispatched us.
                   4537: #    $tail     - Tail of the command (domain/host requested).
                   4538: #    $socket   - Socket open on the client.
                   4539: #
                   4540: # Returns:
                   4541: #     1   - Indicates the program should continue to process requests.
                   4542: # Side-effects:
                   4543: #     The default domain/system context is modified for this daemon.
                   4544: #     a reply is sent to the client.
                   4545: #
                   4546: sub set_virtual_host_handler {
                   4547:     my ($cmd, $tail, $socket) = @_;
                   4548:   
                   4549:     my $userinput  ="$cmd:$tail";
                   4550: 
                   4551:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   4552: 
                   4553: 
                   4554:     return 1;
                   4555: }
1.247     albertel 4556: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     4557: 
                   4558: #  Process a request to exit:
                   4559: #   - "bye" is sent to the client.
                   4560: #   - The client socket is shutdown and closed.
                   4561: #   - We indicate to the caller that we should exit.
                   4562: # Formal Parameters:
                   4563: #   $cmd                - The command that got us here.
                   4564: #   $tail               - Tail of the command (empty).
                   4565: #   $client             - Socket open on the tail.
                   4566: # Returns:
                   4567: #   0      - Indicating the program should exit!!
                   4568: #
                   4569: sub exit_handler {
                   4570:     my ($cmd, $tail, $client) = @_;
                   4571: 
                   4572:     my $userinput = "$cmd:$tail";
                   4573: 
                   4574:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   4575:     &Reply($client, "bye\n", $userinput);
                   4576:     $client->shutdown(2);        # shutdown the socket forcibly.
                   4577:     $client->close();
                   4578: 
                   4579:     return 0;
                   4580: }
1.248     foxr     4581: &register_handler("exit", \&exit_handler, 0,1,1);
                   4582: &register_handler("init", \&exit_handler, 0,1,1);
                   4583: &register_handler("quit", \&exit_handler, 0,1,1);
                   4584: 
                   4585: #  Determine if auto-enrollment is enabled.
                   4586: #  Note that the original had what I believe to be a defect.
                   4587: #  The original returned 0 if the requestor was not a registerd client.
                   4588: #  It should return "refused".
                   4589: # Formal Parameters:
                   4590: #   $cmd       - The command that invoked us.
                   4591: #   $tail      - The tail of the command (Extra command parameters.
                   4592: #   $client    - The socket open on the client that issued the request.
                   4593: # Returns:
                   4594: #    1         - Indicating processing should continue.
                   4595: #
                   4596: sub enrollment_enabled_handler {
                   4597:     my ($cmd, $tail, $client) = @_;
                   4598:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   4599: 
                   4600:     
1.337     albertel 4601:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   4602: 
1.248     foxr     4603:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 4604:     &Reply($client, \$outcome, $userinput);
1.248     foxr     4605: 
                   4606:     return 1;
                   4607: }
                   4608: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   4609: 
                   4610: #   Get the official sections for which auto-enrollment is possible.
                   4611: #   Since the admin people won't know about 'unofficial sections' 
                   4612: #   we cannot auto-enroll on them.
                   4613: # Formal Parameters:
                   4614: #    $cmd     - The command request that got us dispatched here.
                   4615: #    $tail    - The remainder of the request.  In our case this
                   4616: #               will be split into:
                   4617: #               $coursecode   - The course name from the admin point of view.
                   4618: #               $cdom         - The course's domain(?).
                   4619: #    $client  - Socket open on the client.
                   4620: # Returns:
                   4621: #    1    - Indiciting processing should continue.
                   4622: #
                   4623: sub get_sections_handler {
                   4624:     my ($cmd, $tail, $client) = @_;
                   4625:     my $userinput = "$cmd:$tail";
                   4626: 
                   4627:     my ($coursecode, $cdom) = split(/:/, $tail);
                   4628:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   4629:     my $seclist = &escape(join(':',@secs));
                   4630: 
1.387     albertel 4631:     &Reply($client, \$seclist, $userinput);
1.248     foxr     4632:     
                   4633: 
                   4634:     return 1;
                   4635: }
                   4636: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   4637: 
                   4638: #   Validate the owner of a new course section.  
                   4639: #
                   4640: # Formal Parameters:
                   4641: #   $cmd      - Command that got us dispatched.
                   4642: #   $tail     - the remainder of the command.  For us this consists of a
                   4643: #               colon separated string containing:
                   4644: #                  $inst    - Course Id from the institutions point of view.
                   4645: #                  $owner   - Proposed owner of the course.
                   4646: #                  $cdom    - Domain of the course (from the institutions
                   4647: #                             point of view?)..
                   4648: #   $client   - Socket open on the client.
                   4649: #
                   4650: # Returns:
                   4651: #   1        - Processing should continue.
                   4652: #
                   4653: sub validate_course_owner_handler {
                   4654:     my ($cmd, $tail, $client)  = @_;
                   4655:     my $userinput = "$cmd:$tail";
                   4656:     my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
                   4657: 
1.336     raeburn  4658:     $owner = &unescape($owner);
1.248     foxr     4659:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
1.387     albertel 4660:     &Reply($client, \$outcome, $userinput);
1.248     foxr     4661: 
                   4662: 
                   4663: 
                   4664:     return 1;
                   4665: }
                   4666: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 4667: 
1.248     foxr     4668: #
                   4669: #   Validate a course section in the official schedule of classes
                   4670: #   from the institutions point of view (part of autoenrollment).
                   4671: #
                   4672: # Formal Parameters:
                   4673: #   $cmd          - The command request that got us dispatched.
                   4674: #   $tail         - The tail of the command.  In this case,
                   4675: #                   this is a colon separated set of words that will be split
                   4676: #                   into:
                   4677: #                        $inst_course_id - The course/section id from the
                   4678: #                                          institutions point of view.
                   4679: #                        $cdom           - The domain from the institutions
                   4680: #                                          point of view.
                   4681: #   $client       - Socket open on the client.
                   4682: # Returns:
                   4683: #    1           - Indicating processing should continue.
                   4684: #
                   4685: sub validate_course_section_handler {
                   4686:     my ($cmd, $tail, $client) = @_;
                   4687:     my $userinput = "$cmd:$tail";
                   4688:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   4689: 
                   4690:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 4691:     &Reply($client, \$outcome, $userinput);
1.248     foxr     4692: 
                   4693: 
                   4694:     return 1;
                   4695: }
                   4696: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   4697: 
                   4698: #
1.340     raeburn  4699: #   Validate course owner's access to enrollment data for specific class section. 
                   4700: #   
                   4701: #
                   4702: # Formal Parameters:
                   4703: #    $cmd     - The command request that got us dispatched.
                   4704: #    $tail    - The tail of the command.   In this case this is a colon separated
                   4705: #               set of words that will be split into:
                   4706: #               $inst_class  - Institutional code for the specific class section   
                   4707: #               $courseowner - The escaped username:domain of the course owner 
                   4708: #               $cdom        - The domain of the course from the institution's
                   4709: #                              point of view.
                   4710: #    $client  - The socket open on the client.
                   4711: # Returns:
                   4712: #    1 - continue processing.
                   4713: #
                   4714: 
                   4715: sub validate_class_access_handler {
                   4716:     my ($cmd, $tail, $client) = @_;
                   4717:     my $userinput = "$cmd:$tail";
1.383     raeburn  4718:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  4719:     my $owners = &unescape($ownerlist);
1.341     albertel 4720:     my $outcome;
                   4721:     eval {
                   4722: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  4723: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 4724:     };
1.387     albertel 4725:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  4726: 
                   4727:     return 1;
                   4728: }
                   4729: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   4730: 
                   4731: #
                   4732: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   4733: #   Only used for case where authentication method for new user is localauth
1.248     foxr     4734: #
                   4735: # Formal Parameters:
                   4736: #    $cmd     - The command request that got us dispatched.
                   4737: #    $tail    - The tail of the command.   In this case this is a colon separated
                   4738: #               set of words that will be split into:
1.340     raeburn  4739: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     4740: #               $cdom      - The domain of the course from the institution's
                   4741: #                            point of view.
                   4742: #    $client  - The socket open on the client.
                   4743: # Returns:
                   4744: #    1 - continue processing.
                   4745: #
                   4746: sub create_auto_enroll_password_handler {
                   4747:     my ($cmd, $tail, $client) = @_;
                   4748:     my $userinput = "$cmd:$tail";
                   4749: 
                   4750:     my ($authparam, $cdom) = split(/:/, $userinput);
                   4751: 
                   4752:     my ($create_passwd,$authchk);
                   4753:     ($authparam,
                   4754:      $create_passwd,
                   4755:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   4756: 
                   4757:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   4758: 	   $userinput);
                   4759: 
                   4760: 
                   4761:     return 1;
                   4762: }
                   4763: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   4764: 		  0, 1, 0);
                   4765: 
                   4766: #   Retrieve and remove temporary files created by/during autoenrollment.
                   4767: #
                   4768: # Formal Parameters:
                   4769: #    $cmd      - The command that got us dispatched.
                   4770: #    $tail     - The tail of the command.  In our case this is a colon 
                   4771: #                separated list that will be split into:
                   4772: #                $filename - The name of the file to remove.
                   4773: #                            The filename is given as a path relative to
                   4774: #                            the LonCAPA temp file directory.
                   4775: #    $client   - Socket open on the client.
                   4776: #
                   4777: # Returns:
                   4778: #   1     - Continue processing.
                   4779: sub retrieve_auto_file_handler {
                   4780:     my ($cmd, $tail, $client)    = @_;
                   4781:     my $userinput                = "cmd:$tail";
                   4782: 
                   4783:     my ($filename)   = split(/:/, $tail);
                   4784: 
                   4785:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
                   4786:     if ( (-e $source) && ($filename ne '') ) {
                   4787: 	my $reply = '';
                   4788: 	if (open(my $fh,$source)) {
                   4789: 	    while (<$fh>) {
                   4790: 		chomp($_);
                   4791: 		$_ =~ s/^\s+//g;
                   4792: 		$_ =~ s/\s+$//g;
                   4793: 		$reply .= $_;
                   4794: 	    }
                   4795: 	    close($fh);
                   4796: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   4797: 
                   4798: #   Does this have to be uncommented??!?  (RF).
                   4799: #
                   4800: #                                unlink($source);
                   4801: 	} else {
                   4802: 	    &Failure($client, "error\n", $userinput);
                   4803: 	}
                   4804:     } else {
                   4805: 	&Failure($client, "error\n", $userinput);
                   4806:     }
                   4807:     
                   4808: 
                   4809:     return 1;
                   4810: }
                   4811: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   4812: 
                   4813: #
                   4814: #   Read and retrieve institutional code format (for support form).
                   4815: # Formal Parameters:
                   4816: #    $cmd        - Command that dispatched us.
                   4817: #    $tail       - Tail of the command.  In this case it conatins 
                   4818: #                  the course domain and the coursename.
                   4819: #    $client     - Socket open on the client.
                   4820: # Returns:
                   4821: #    1     - Continue processing.
                   4822: #
                   4823: sub get_institutional_code_format_handler {
                   4824:     my ($cmd, $tail, $client)   = @_;
                   4825:     my $userinput               = "$cmd:$tail";
                   4826: 
                   4827:     my $reply;
                   4828:     my($cdom,$course) = split(/:/,$tail);
                   4829:     my @pairs = split/\&/,$course;
                   4830:     my %instcodes = ();
                   4831:     my %codes = ();
                   4832:     my @codetitles = ();
                   4833:     my %cat_titles = ();
                   4834:     my %cat_order = ();
                   4835:     foreach (@pairs) {
                   4836: 	my ($key,$value) = split/=/,$_;
                   4837: 	$instcodes{&unescape($key)} = &unescape($value);
                   4838:     }
                   4839:     my $formatreply = &localenroll::instcode_format($cdom,
                   4840: 						    \%instcodes,
                   4841: 						    \%codes,
                   4842: 						    \@codetitles,
                   4843: 						    \%cat_titles,
                   4844: 						    \%cat_order);
                   4845:     if ($formatreply eq 'ok') {
1.365     albertel 4846: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   4847: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   4848: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   4849: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     4850: 	&Reply($client,
                   4851: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   4852: 	       .$cat_order_str."\n",
                   4853: 	       $userinput);
                   4854:     } else {
                   4855: 	# this else branch added by RF since if not ok, lonc will
                   4856: 	# hang waiting on reply until timeout.
                   4857: 	#
                   4858: 	&Reply($client, "format_error\n", $userinput);
                   4859:     }
                   4860:     
                   4861:     return 1;
                   4862: }
1.265     albertel 4863: &register_handler("autoinstcodeformat",
                   4864: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     4865: 
1.345     raeburn  4866: sub get_institutional_defaults_handler {
                   4867:     my ($cmd, $tail, $client)   = @_;
                   4868:     my $userinput               = "$cmd:$tail";
                   4869: 
                   4870:     my $dom = $tail;
                   4871:     my %defaults_hash;
                   4872:     my @code_order;
                   4873:     my $outcome;
                   4874:     eval {
                   4875:         local($SIG{__DIE__})='DEFAULT';
                   4876:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   4877:                                                    \@code_order);
                   4878:     };
                   4879:     if (!$@) {
                   4880:         if ($outcome eq 'ok') {
                   4881:             my $result='';
                   4882:             while (my ($key,$value) = each(%defaults_hash)) {
                   4883:                 $result.=&escape($key).'='.&escape($value).'&';
                   4884:             }
                   4885:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 4886:             &Reply($client,\$result,$userinput);
1.345     raeburn  4887:         } else {
                   4888:             &Reply($client,"error\n", $userinput);
                   4889:         }
                   4890:     } else {
                   4891:         &Failure($client,"unknown_cmd\n",$userinput);
                   4892:     }
                   4893: }
                   4894: &register_handler("autoinstcodedefaults",
                   4895:                   \&get_institutional_defaults_handler,0,1,0);
                   4896: 
1.381     raeburn  4897: sub get_institutional_user_rules {
                   4898:     my ($cmd, $tail, $client)   = @_;
                   4899:     my $userinput               = "$cmd:$tail";
                   4900:     my $dom = &unescape($tail);
                   4901:     my (%rules_hash,@rules_order);
                   4902:     my $outcome;
                   4903:     eval {
                   4904:         local($SIG{__DIE__})='DEFAULT';
                   4905:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   4906:     };
                   4907:     if (!$@) {
                   4908:         if ($outcome eq 'ok') {
                   4909:             my $result;
                   4910:             foreach my $key (keys(%rules_hash)) {
                   4911:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   4912:             }
                   4913:             $result =~ s/\&$//;
                   4914:             $result .= ':';
                   4915:             if (@rules_order > 0) {
                   4916:                 foreach my $item (@rules_order) {
                   4917:                     $result .= &escape($item).'&';
                   4918:                 }
                   4919:             }
                   4920:             $result =~ s/\&$//;
1.387     albertel 4921:             &Reply($client,\$result,$userinput);
1.381     raeburn  4922:         } else {
                   4923:             &Reply($client,"error\n", $userinput);
                   4924:         }
                   4925:     } else {
                   4926:         &Failure($client,"unknown_cmd\n",$userinput);
                   4927:     }
                   4928: }
                   4929: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   4930: 
1.389     raeburn  4931: sub get_institutional_id_rules {
                   4932:     my ($cmd, $tail, $client)   = @_;
                   4933:     my $userinput               = "$cmd:$tail";
                   4934:     my $dom = &unescape($tail);
                   4935:     my (%rules_hash,@rules_order);
                   4936:     my $outcome;
                   4937:     eval {
                   4938:         local($SIG{__DIE__})='DEFAULT';
                   4939:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   4940:     };
                   4941:     if (!$@) {
                   4942:         if ($outcome eq 'ok') {
                   4943:             my $result;
                   4944:             foreach my $key (keys(%rules_hash)) {
                   4945:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   4946:             }
                   4947:             $result =~ s/\&$//;
                   4948:             $result .= ':';
                   4949:             if (@rules_order > 0) {
                   4950:                 foreach my $item (@rules_order) {
                   4951:                     $result .= &escape($item).'&';
                   4952:                 }
                   4953:             }
                   4954:             $result =~ s/\&$//;
                   4955:             &Reply($client,\$result,$userinput);
                   4956:         } else {
                   4957:             &Reply($client,"error\n", $userinput);
                   4958:         }
                   4959:     } else {
                   4960:         &Failure($client,"unknown_cmd\n",$userinput);
                   4961:     }
                   4962: }
                   4963: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   4964: 
1.397     raeburn  4965: sub get_institutional_selfcreate_rules {
1.396     raeburn  4966:     my ($cmd, $tail, $client)   = @_;
                   4967:     my $userinput               = "$cmd:$tail";
                   4968:     my $dom = &unescape($tail);
                   4969:     my (%rules_hash,@rules_order);
                   4970:     my $outcome;
                   4971:     eval {
                   4972:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  4973:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  4974:     };
                   4975:     if (!$@) {
                   4976:         if ($outcome eq 'ok') {
                   4977:             my $result;
                   4978:             foreach my $key (keys(%rules_hash)) {
                   4979:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   4980:             }
                   4981:             $result =~ s/\&$//;
                   4982:             $result .= ':';
                   4983:             if (@rules_order > 0) {
                   4984:                 foreach my $item (@rules_order) {
                   4985:                     $result .= &escape($item).'&';
                   4986:                 }
                   4987:             }
                   4988:             $result =~ s/\&$//;
                   4989:             &Reply($client,\$result,$userinput);
                   4990:         } else {
                   4991:             &Reply($client,"error\n", $userinput);
                   4992:         }
                   4993:     } else {
                   4994:         &Failure($client,"unknown_cmd\n",$userinput);
                   4995:     }
                   4996: }
1.397     raeburn  4997: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  4998: 
1.381     raeburn  4999: 
                   5000: sub institutional_username_check {
                   5001:     my ($cmd, $tail, $client)   = @_;
                   5002:     my $userinput               = "$cmd:$tail";
                   5003:     my %rulecheck;
                   5004:     my $outcome;
                   5005:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   5006:     $udom = &unescape($udom);
                   5007:     $uname = &unescape($uname);
                   5008:     @rules = map {&unescape($_);} (@rules);
                   5009:     eval {
                   5010:         local($SIG{__DIE__})='DEFAULT';
                   5011:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   5012:     };
                   5013:     if (!$@) {
                   5014:         if ($outcome eq 'ok') {
                   5015:             my $result='';
                   5016:             foreach my $key (keys(%rulecheck)) {
                   5017:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   5018:             }
1.387     albertel 5019:             &Reply($client,\$result,$userinput);
1.381     raeburn  5020:         } else {
                   5021:             &Reply($client,"error\n", $userinput);
                   5022:         }
                   5023:     } else {
                   5024:         &Failure($client,"unknown_cmd\n",$userinput);
                   5025:     }
                   5026: }
                   5027: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   5028: 
1.389     raeburn  5029: sub institutional_id_check {
                   5030:     my ($cmd, $tail, $client)   = @_;
                   5031:     my $userinput               = "$cmd:$tail";
                   5032:     my %rulecheck;
                   5033:     my $outcome;
                   5034:     my ($udom,$id,@rules) = split(/:/,$tail);
                   5035:     $udom = &unescape($udom);
                   5036:     $id = &unescape($id);
                   5037:     @rules = map {&unescape($_);} (@rules);
                   5038:     eval {
                   5039:         local($SIG{__DIE__})='DEFAULT';
                   5040:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   5041:     };
                   5042:     if (!$@) {
                   5043:         if ($outcome eq 'ok') {
                   5044:             my $result='';
                   5045:             foreach my $key (keys(%rulecheck)) {
                   5046:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   5047:             }
                   5048:             &Reply($client,\$result,$userinput);
                   5049:         } else {
                   5050:             &Reply($client,"error\n", $userinput);
                   5051:         }
                   5052:     } else {
                   5053:         &Failure($client,"unknown_cmd\n",$userinput);
                   5054:     }
                   5055: }
                   5056: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  5057: 
1.397     raeburn  5058: sub institutional_selfcreate_check {
1.396     raeburn  5059:     my ($cmd, $tail, $client)   = @_;
                   5060:     my $userinput               = "$cmd:$tail";
                   5061:     my %rulecheck;
                   5062:     my $outcome;
                   5063:     my ($udom,$email,@rules) = split(/:/,$tail);
                   5064:     $udom = &unescape($udom);
                   5065:     $email = &unescape($email);
                   5066:     @rules = map {&unescape($_);} (@rules);
                   5067:     eval {
                   5068:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  5069:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  5070:     };
                   5071:     if (!$@) {
                   5072:         if ($outcome eq 'ok') {
                   5073:             my $result='';
                   5074:             foreach my $key (keys(%rulecheck)) {
                   5075:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   5076:             }
                   5077:             &Reply($client,\$result,$userinput);
                   5078:         } else {
                   5079:             &Reply($client,"error\n", $userinput);
                   5080:         }
                   5081:     } else {
                   5082:         &Failure($client,"unknown_cmd\n",$userinput);
                   5083:     }
                   5084: }
1.397     raeburn  5085: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  5086: 
1.317     raeburn  5087: # Get domain specific conditions for import of student photographs to a course
                   5088: #
                   5089: # Retrieves information from photo_permission subroutine in localenroll.
                   5090: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   5091: # required to accept conditions of use (yes/no).
                   5092: #
                   5093: #    
                   5094: sub photo_permission_handler {
                   5095:     my ($cmd, $tail, $client)   = @_;
                   5096:     my $userinput               = "$cmd:$tail";
                   5097:     my $cdom = $tail;
                   5098:     my ($perm_reqd,$conditions);
1.320     albertel 5099:     my $outcome;
                   5100:     eval {
                   5101: 	local($SIG{__DIE__})='DEFAULT';
                   5102: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   5103: 						  \$conditions);
                   5104:     };
                   5105:     if (!$@) {
                   5106: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   5107: 	       $userinput);
                   5108:     } else {
                   5109: 	&Failure($client,"unknown_cmd\n",$userinput);
                   5110:     }
                   5111:     return 1;
1.317     raeburn  5112: }
                   5113: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   5114: 
                   5115: #
                   5116: # Checks if student photo is available for a user in the domain, in the user's
                   5117: # directory (in /userfiles/internal/studentphoto.jpg).
                   5118: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   5119: # the student's photo.   
                   5120: 
                   5121: sub photo_check_handler {
                   5122:     my ($cmd, $tail, $client)   = @_;
                   5123:     my $userinput               = "$cmd:$tail";
                   5124:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   5125:     $udom = &unescape($udom);
                   5126:     $uname = &unescape($uname);
                   5127:     $pid = &unescape($pid);
                   5128:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   5129:     if (!-e $path) {
                   5130:         &mkpath($path);
                   5131:     }
                   5132:     my $response;
                   5133:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   5134:     $result .= ':'.$response;
                   5135:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 5136:     return 1;
1.317     raeburn  5137: }
                   5138: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   5139: 
                   5140: #
                   5141: # Retrieve information from localenroll about whether to provide a button     
                   5142: # for users who have enbled import of student photos to initiate an 
                   5143: # update of photo files for registered students. Also include 
                   5144: # comment to display alongside button.  
                   5145: 
                   5146: sub photo_choice_handler {
                   5147:     my ($cmd, $tail, $client) = @_;
                   5148:     my $userinput             = "$cmd:$tail";
                   5149:     my $cdom                  = &unescape($tail);
1.320     albertel 5150:     my ($update,$comment);
                   5151:     eval {
                   5152: 	local($SIG{__DIE__})='DEFAULT';
                   5153: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   5154:     };
                   5155:     if (!$@) {
                   5156: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   5157:     } else {
                   5158: 	&Failure($client,"unknown_cmd\n",$userinput);
                   5159:     }
                   5160:     return 1;
1.317     raeburn  5161: }
                   5162: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   5163: 
1.265     albertel 5164: #
                   5165: # Gets a student's photo to exist (in the correct image type) in the user's 
                   5166: # directory.
                   5167: # Formal Parameters:
                   5168: #    $cmd     - The command request that got us dispatched.
                   5169: #    $tail    - A colon separated set of words that will be split into:
                   5170: #               $domain - student's domain
                   5171: #               $uname  - student username
                   5172: #               $type   - image type desired
                   5173: #    $client  - The socket open on the client.
                   5174: # Returns:
                   5175: #    1 - continue processing.
1.317     raeburn  5176: 
1.265     albertel 5177: sub student_photo_handler {
                   5178:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  5179:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 5180: 
1.317     raeburn  5181:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   5182:     my $filename = 'studentphoto.'.$ext;
                   5183:     if ($type eq 'thumbnail') {
                   5184:         $filename = 'studentphoto_tn.'.$ext;
                   5185:     }
                   5186:     if (-e $path.$filename) {
1.265     albertel 5187: 	&Reply($client,"ok\n","$cmd:$tail");
                   5188: 	return 1;
                   5189:     }
                   5190:     &mkpath($path);
1.317     raeburn  5191:     my $file;
                   5192:     if ($type eq 'thumbnail') {
1.320     albertel 5193: 	eval {
                   5194: 	    local($SIG{__DIE__})='DEFAULT';
                   5195: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   5196: 	};
1.317     raeburn  5197:     } else {
                   5198:         $file=&localstudentphoto::fetch($domain,$uname);
                   5199:     }
1.265     albertel 5200:     if (!$file) {
                   5201: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   5202: 	return 1;
                   5203:     }
1.317     raeburn  5204:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   5205:     if (-e $path.$filename) {
1.265     albertel 5206: 	&Reply($client,"ok\n","$cmd:$tail");
                   5207: 	return 1;
                   5208:     }
                   5209:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   5210:     return 1;
                   5211: }
                   5212: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     5213: 
1.361     raeburn  5214: sub inst_usertypes_handler {
                   5215:     my ($cmd, $domain, $client) = @_;
                   5216:     my $res;
                   5217:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 5218:     my (%typeshash,@order,$result);
                   5219:     eval {
                   5220: 	local($SIG{__DIE__})='DEFAULT';
                   5221: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   5222:     };
                   5223:     if ($result eq 'ok') {
1.361     raeburn  5224:         if (keys(%typeshash) > 0) {
                   5225:             foreach my $key (keys(%typeshash)) {
                   5226:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   5227:             }
                   5228:         }
                   5229:         $res=~s/\&$//;
                   5230:         $res .= ':';
                   5231:         if (@order > 0) {
                   5232:             foreach my $item (@order) {
                   5233:                 $res .= &escape($item).'&';
                   5234:             }
                   5235:         }
                   5236:         $res=~s/\&$//;
                   5237:     }
1.387     albertel 5238:     &Reply($client, \$res, $userinput);
1.361     raeburn  5239:     return 1;
                   5240: }
                   5241: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   5242: 
1.264     albertel 5243: # mkpath makes all directories for a file, expects an absolute path with a
                   5244: # file or a trailing / if just a dir is passed
                   5245: # returns 1 on success 0 on failure
                   5246: sub mkpath {
                   5247:     my ($file)=@_;
                   5248:     my @parts=split(/\//,$file,-1);
                   5249:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   5250:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 5251: 	$now.='/'.$parts[$i]; 
1.264     albertel 5252: 	if (!-e $now) {
                   5253: 	    if  (!mkdir($now,0770)) { return 0; }
                   5254: 	}
                   5255:     }
                   5256:     return 1;
                   5257: }
                   5258: 
1.207     foxr     5259: #---------------------------------------------------------------
                   5260: #
                   5261: #   Getting, decoding and dispatching requests:
                   5262: #
                   5263: #
                   5264: #   Get a Request:
                   5265: #   Gets a Request message from the client.  The transaction
                   5266: #   is defined as a 'line' of text.  We remove the new line
                   5267: #   from the text line.  
1.226     foxr     5268: #
1.211     albertel 5269: sub get_request {
1.207     foxr     5270:     my $input = <$client>;
                   5271:     chomp($input);
1.226     foxr     5272: 
1.234     foxr     5273:     &Debug("get_request: Request = $input\n");
1.207     foxr     5274: 
                   5275:     &status('Processing '.$clientname.':'.$input);
                   5276: 
                   5277:     return $input;
                   5278: }
1.212     foxr     5279: #---------------------------------------------------------------
                   5280: #
                   5281: #  Process a request.  This sub should shrink as each action
                   5282: #  gets farmed out into a separat sub that is registered 
                   5283: #  with the dispatch hash.  
                   5284: #
                   5285: # Parameters:
                   5286: #    user_input   - The request received from the client (lonc).
                   5287: # Returns:
                   5288: #    true to keep processing, false if caller should exit.
                   5289: #
                   5290: sub process_request {
                   5291:     my ($userinput) = @_;      # Easier for now to break style than to
                   5292:                                 # fix all the userinput -> user_input.
                   5293:     my $wasenc    = 0;		# True if request was encrypted.
                   5294: # ------------------------------------------------------------ See if encrypted
1.322     albertel 5295:     # for command
                   5296:     # sethost:<server>
                   5297:     # <command>:<args>
                   5298:     #   we just send it to the processor
                   5299:     # for
                   5300:     # sethost:<server>:<command>:<args>
                   5301:     #  we do the implict set host and then do the command
                   5302:     if ($userinput =~ /^sethost:/) {
                   5303: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   5304: 	if (defined($userinput)) {
                   5305: 	    &sethost("$cmd:$newid");
                   5306: 	} else {
                   5307: 	    $userinput = "$cmd:$newid";
                   5308: 	}
                   5309:     }
                   5310: 
1.212     foxr     5311:     if ($userinput =~ /^enc/) {
                   5312: 	$userinput = decipher($userinput);
                   5313: 	$wasenc=1;
                   5314: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     5315: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     5316: 	    return 0;
                   5317: 	}
                   5318:     }
                   5319:     Debug("process_request: $userinput\n");
                   5320:     
1.213     foxr     5321:     #  
                   5322:     #   The 'correct way' to add a command to lond is now to
                   5323:     #   write a sub to execute it and Add it to the command dispatch
                   5324:     #   hash via a call to register_handler..  The comments to that
                   5325:     #   sub should give you enough to go on to show how to do this
                   5326:     #   along with the examples that are building up as this code
                   5327:     #   is getting refactored.   Until all branches of the
                   5328:     #   if/elseif monster below have been factored out into
                   5329:     #   separate procesor subs, if the dispatch hash is missing
                   5330:     #   the command keyword, we will fall through to the remainder
                   5331:     #   of the if/else chain below in order to keep this thing in 
                   5332:     #   working order throughout the transmogrification.
                   5333: 
                   5334:     my ($command, $tail) = split(/:/, $userinput, 2);
                   5335:     chomp($command);
                   5336:     chomp($tail);
                   5337:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     5338:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   5339:     if(!$tail) {
                   5340: 	$tail ="";		# defined but blank.
                   5341:     }
1.213     foxr     5342: 
                   5343:     &Debug("Command received: $command, encoded = $wasenc");
                   5344: 
                   5345:     if(defined $Dispatcher{$command}) {
                   5346: 
                   5347: 	my $dispatch_info = $Dispatcher{$command};
                   5348: 	my $handler       = $$dispatch_info[0];
                   5349: 	my $need_encode   = $$dispatch_info[1];
                   5350: 	my $client_types  = $$dispatch_info[2];
                   5351: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   5352: 	      ."ClientType $client_types");
                   5353:       
                   5354: 	#  Validate the request:
                   5355:       
                   5356: 	my $ok = 1;
                   5357: 	my $requesterprivs = 0;
                   5358: 	if(&isClient()) {
                   5359: 	    $requesterprivs |= $CLIENT_OK;
                   5360: 	}
                   5361: 	if(&isManager()) {
                   5362: 	    $requesterprivs |= $MANAGER_OK;
                   5363: 	}
                   5364: 	if($need_encode && (!$wasenc)) {
                   5365: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   5366: 	    $ok = 0;
                   5367: 	}
                   5368: 	if(($client_types & $requesterprivs) == 0) {
                   5369: 	    Debug("Client not privileged to do this operation");
                   5370: 	    $ok = 0;
                   5371: 	}
                   5372: 
                   5373: 	if($ok) {
                   5374: 	    Debug("Dispatching to handler $command $tail");
                   5375: 	    my $keep_going = &$handler($command, $tail, $client);
                   5376: 	    return $keep_going;
                   5377: 	} else {
                   5378: 	    Debug("Refusing to dispatch because client did not match requirements");
                   5379: 	    Failure($client, "refused\n", $userinput);
                   5380: 	    return 1;
                   5381: 	}
                   5382: 
                   5383:     }    
                   5384: 
1.262     foxr     5385:     print $client "unknown_cmd\n";
1.212     foxr     5386: # -------------------------------------------------------------------- complete
                   5387:     Debug("process_request - returning 1");
                   5388:     return 1;
                   5389: }
1.207     foxr     5390: #
                   5391: #   Decipher encoded traffic
                   5392: #  Parameters:
                   5393: #     input      - Encoded data.
                   5394: #  Returns:
                   5395: #     Decoded data or undef if encryption key was not yet negotiated.
                   5396: #  Implicit input:
                   5397: #     cipher  - This global holds the negotiated encryption key.
                   5398: #
1.211     albertel 5399: sub decipher {
1.207     foxr     5400:     my ($input)  = @_;
                   5401:     my $output = '';
1.212     foxr     5402:     
                   5403:     
1.207     foxr     5404:     if($cipher) {
                   5405: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   5406: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   5407: 	    $output .= 
                   5408: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   5409: 	}
                   5410: 	return substr($output, 0, $enclength);
                   5411:     } else {
                   5412: 	return undef;
                   5413:     }
                   5414: }
                   5415: 
                   5416: #
                   5417: #   Register a command processor.  This function is invoked to register a sub
                   5418: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   5419: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   5420: #   as well:
                   5421: #    - Is the keyword recognized.
                   5422: #    - Is the proper client type attempting the request.
                   5423: #    - Is the request encrypted if it has to be.
                   5424: #   Parameters:
                   5425: #    $request_name         - Name of the request being registered.
                   5426: #                           This is the command request that will match
                   5427: #                           against the hash keywords to lookup the information
                   5428: #                           associated with the dispatch information.
                   5429: #    $procedure           - Reference to a sub to call to process the request.
                   5430: #                           All subs get called as follows:
                   5431: #                             Procedure($cmd, $tail, $replyfd, $key)
                   5432: #                             $cmd    - the actual keyword that invoked us.
                   5433: #                             $tail   - the tail of the request that invoked us.
                   5434: #                             $replyfd- File descriptor connected to the client
                   5435: #    $must_encode          - True if the request must be encoded to be good.
                   5436: #    $client_ok            - True if it's ok for a client to request this.
                   5437: #    $manager_ok           - True if it's ok for a manager to request this.
                   5438: # Side effects:
                   5439: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   5440: #      - On failure, the program will die as it's a bad internal bug to try to 
                   5441: #        register a duplicate command handler.
                   5442: #
1.211     albertel 5443: sub register_handler {
1.212     foxr     5444:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     5445: 
                   5446:     #  Don't allow duplication#
                   5447:    
                   5448:     if (defined $Dispatcher{$request_name}) {
                   5449: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   5450:     }
                   5451:     #   Build the client type mask:
                   5452:     
                   5453:     my $client_type_mask = 0;
                   5454:     if($client_ok) {
                   5455: 	$client_type_mask  |= $CLIENT_OK;
                   5456:     }
                   5457:     if($manager_ok) {
                   5458: 	$client_type_mask  |= $MANAGER_OK;
                   5459:     }
                   5460:    
                   5461:     #  Enter the hash:
                   5462:       
                   5463:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   5464:    
                   5465:     $Dispatcher{$request_name} = \@entry;
                   5466:    
                   5467: }
                   5468: 
                   5469: 
                   5470: #------------------------------------------------------------------
                   5471: 
                   5472: 
                   5473: 
                   5474: 
1.141     foxr     5475: #
1.96      foxr     5476: #  Convert an error return code from lcpasswd to a string value.
                   5477: #
                   5478: sub lcpasswdstrerror {
                   5479:     my $ErrorCode = shift;
1.97      foxr     5480:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     5481: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   5482:     } else {
1.98      foxr     5483: 	return $passwderrors[$ErrorCode];
1.96      foxr     5484:     }
                   5485: }
                   5486: 
1.97      foxr     5487: #
                   5488: # Convert an error return code from lcuseradd to a string value:
                   5489: #
                   5490: sub lcuseraddstrerror {
                   5491:     my $ErrorCode = shift;
                   5492:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
                   5493: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
                   5494:     } else {
1.98      foxr     5495: 	return $adderrors[$ErrorCode];
1.97      foxr     5496:     }
                   5497: }
                   5498: 
1.23      harris41 5499: # grabs exception and records it to log before exiting
                   5500: sub catchexception {
1.27      albertel 5501:     my ($error)=@_;
1.25      www      5502:     $SIG{'QUIT'}='DEFAULT';
                   5503:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 5504:     &status("Catching exception");
1.190     albertel 5505:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 5506:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 5507:      ."a crash with this error msg->[$error]</font>");
1.57      www      5508:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 5509:     if ($client) { print $client "error: $error\n"; }
1.59      www      5510:     $server->close();
1.27      albertel 5511:     die($error);
1.23      harris41 5512: }
1.63      www      5513: sub timeout {
1.165     albertel 5514:     &status("Handling Timeout");
1.190     albertel 5515:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      5516:     &catchexception('Timeout');
                   5517: }
1.22      harris41 5518: # -------------------------------- Set signal handlers to record abnormal exits
                   5519: 
1.226     foxr     5520: 
1.22      harris41 5521: $SIG{'QUIT'}=\&catchexception;
                   5522: $SIG{__DIE__}=\&catchexception;
                   5523: 
1.81      matthew  5524: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 5525: &status("Read loncapa.conf and loncapa_apache.conf");
                   5526: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     5527: %perlvar=%{$perlvarref};
1.80      harris41 5528: undef $perlvarref;
1.19      www      5529: 
1.35      harris41 5530: # ----------------------------- Make sure this process is running from user=www
                   5531: my $wwwid=getpwnam('www');
                   5532: if ($wwwid!=$<) {
1.134     albertel 5533:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   5534:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 5535:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 5536:  mailto $emailto -s '$subj' > /dev/null");
                   5537:    exit 1;
                   5538: }
                   5539: 
1.19      www      5540: # --------------------------------------------- Check if other instance running
                   5541: 
                   5542: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   5543: 
                   5544: if (-e $pidfile) {
                   5545:    my $lfh=IO::File->new("$pidfile");
                   5546:    my $pide=<$lfh>;
                   5547:    chomp($pide);
1.29      harris41 5548:    if (kill 0 => $pide) { die "already running"; }
1.19      www      5549: }
1.1       albertel 5550: 
                   5551: # ------------------------------------------------------------- Read hosts file
                   5552: 
                   5553: 
                   5554: 
                   5555: # establish SERVER socket, bind and listen.
                   5556: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   5557:                                 Type      => SOCK_STREAM,
                   5558:                                 Proto     => 'tcp',
                   5559:                                 Reuse     => 1,
                   5560:                                 Listen    => 10 )
1.29      harris41 5561:   or die "making socket: $@\n";
1.1       albertel 5562: 
                   5563: # --------------------------------------------------------- Do global variables
                   5564: 
                   5565: # global variables
                   5566: 
1.134     albertel 5567: my %children               = ();       # keys are current child process IDs
1.1       albertel 5568: 
                   5569: sub REAPER {                        # takes care of dead children
                   5570:     $SIG{CHLD} = \&REAPER;
1.165     albertel 5571:     &status("Handling child death");
1.178     foxr     5572:     my $pid;
                   5573:     do {
                   5574: 	$pid = waitpid(-1,&WNOHANG());
                   5575: 	if (defined($children{$pid})) {
                   5576: 	    &logthis("Child $pid died");
                   5577: 	    delete($children{$pid});
1.183     albertel 5578: 	} elsif ($pid > 0) {
1.178     foxr     5579: 	    &logthis("Unknown Child $pid died");
                   5580: 	}
                   5581:     } while ( $pid > 0 );
                   5582:     foreach my $child (keys(%children)) {
                   5583: 	$pid = waitpid($child,&WNOHANG());
                   5584: 	if ($pid > 0) {
                   5585: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   5586: 	    delete($children{$pid});
                   5587: 	}
1.176     albertel 5588:     }
1.165     albertel 5589:     &status("Finished Handling child death");
1.1       albertel 5590: }
                   5591: 
                   5592: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 5593:     &status("Killing children (INT)");
1.1       albertel 5594:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   5595:     kill 'INT' => keys %children;
1.59      www      5596:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 5597:     my $execdir=$perlvar{'lonDaemons'};
                   5598:     unlink("$execdir/logs/lond.pid");
1.190     albertel 5599:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 5600:     &status("Done killing children");
1.1       albertel 5601:     exit;                           # clean up with dignity
                   5602: }
                   5603: 
                   5604: sub HUPSMAN {                      # signal handler for SIGHUP
                   5605:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 5606:     &status("Killing children for restart (HUP)");
1.1       albertel 5607:     kill 'INT' => keys %children;
1.59      www      5608:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 5609:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 5610:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 5611:     unlink("$execdir/logs/lond.pid");
1.165     albertel 5612:     &status("Restarting self (HUP)");
1.1       albertel 5613:     exec("$execdir/lond");         # here we go again
                   5614: }
                   5615: 
1.144     foxr     5616: #
1.148     foxr     5617: #  Reload the Apache daemon's state.
1.150     foxr     5618: #  This is done by invoking /home/httpd/perl/apachereload
                   5619: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     5620: #
                   5621: sub ReloadApache {
1.150     foxr     5622:     my $execdir = $perlvar{'lonDaemons'};
                   5623:     my $script  = $execdir."/apachereload";
                   5624:     system($script);
1.148     foxr     5625: }
                   5626: 
                   5627: #
1.144     foxr     5628: #   Called in response to a USR2 signal.
                   5629: #   - Reread hosts.tab
                   5630: #   - All children connected to hosts that were removed from hosts.tab
                   5631: #     are killed via SIGINT
                   5632: #   - All children connected to previously existing hosts are sent SIGUSR1
                   5633: #   - Our internal hosts hash is updated to reflect the new contents of
                   5634: #     hosts.tab causing connections from hosts added to hosts.tab to
                   5635: #     now be honored.
                   5636: #
                   5637: sub UpdateHosts {
1.165     albertel 5638:     &status("Reload hosts.tab");
1.147     foxr     5639:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     5640:     #
                   5641:     #  The %children hash has the set of IP's we currently have children
                   5642:     #  on.  These need to be matched against records in the hosts.tab
                   5643:     #  Any ip's no longer in the table get killed off they correspond to
                   5644:     #  either dropped or changed hosts.  Note that the re-read of the table
                   5645:     #  will take care of new and changed hosts as connections come into being.
                   5646: 
1.371     albertel 5647:     &Apache::lonnet::reset_hosts_info();
1.148     foxr     5648: 
1.368     albertel 5649:     foreach my $child (keys(%children)) {
1.148     foxr     5650: 	my $childip = $children{$child};
1.374     albertel 5651: 	if ($childip ne '127.0.0.1'
                   5652: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     5653: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   5654: 		    ." $child for ip $childip </font>");
1.148     foxr     5655: 	    kill('INT', $child);
1.149     foxr     5656: 	} else {
                   5657: 	    logthis('<font color="green"> keeping child for ip '
                   5658: 		    ." $childip (pid=$child) </font>");
1.148     foxr     5659: 	}
                   5660:     }
                   5661:     ReloadApache;
1.165     albertel 5662:     &status("Finished reloading hosts.tab");
1.144     foxr     5663: }
                   5664: 
1.148     foxr     5665: 
1.57      www      5666: sub checkchildren {
1.165     albertel 5667:     &status("Checking on the children (sending signals)");
1.57      www      5668:     &initnewstatus();
                   5669:     &logstatus();
                   5670:     &logthis('Going to check on the children');
1.134     albertel 5671:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 5672:     foreach (sort keys %children) {
1.221     albertel 5673: 	#sleep 1;
1.57      www      5674:         unless (kill 'USR1' => $_) {
                   5675: 	    &logthis ('Child '.$_.' is dead');
                   5676:             &logstatus($$.' is dead');
1.221     albertel 5677: 	    delete($children{$_});
1.57      www      5678:         } 
1.61      harris41 5679:     }
1.63      www      5680:     sleep 5;
1.212     foxr     5681:     $SIG{ALRM} = sub { Debug("timeout"); 
                   5682: 		       die "timeout";  };
1.113     albertel 5683:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 5684:     &status("Checking on the children (waiting for reports)");
1.63      www      5685:     foreach (sort keys %children) {
                   5686:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 5687:           eval {
                   5688:             alarm(300);
1.63      www      5689: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 5690: 	    kill 9 => $_;
1.131     albertel 5691: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   5692: 	    #$subj="LON: $currenthostid killed lond process $_";
                   5693: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   5694: 	    #$execdir=$perlvar{'lonDaemons'};
                   5695: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 5696: 	    delete($children{$_});
1.113     albertel 5697: 	    alarm(0);
                   5698: 	  }
1.63      www      5699:         }
                   5700:     }
1.113     albertel 5701:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 5702:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 5703:     &status("Finished checking children");
1.221     albertel 5704:     &logthis('Finished Checking children');
1.57      www      5705: }
                   5706: 
1.1       albertel 5707: # --------------------------------------------------------------------- Logging
                   5708: 
                   5709: sub logthis {
                   5710:     my $message=shift;
                   5711:     my $execdir=$perlvar{'lonDaemons'};
                   5712:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   5713:     my $now=time;
                   5714:     my $local=localtime($now);
1.58      www      5715:     $lastlog=$local.': '.$message;
1.1       albertel 5716:     print $fh "$local ($$): $message\n";
                   5717: }
                   5718: 
1.77      foxr     5719: # ------------------------- Conditional log if $DEBUG true.
                   5720: sub Debug {
                   5721:     my $message = shift;
                   5722:     if($DEBUG) {
                   5723: 	&logthis($message);
                   5724:     }
                   5725: }
1.161     foxr     5726: 
                   5727: #
                   5728: #   Sub to do replies to client.. this gives a hook for some
                   5729: #   debug tracing too:
                   5730: #  Parameters:
                   5731: #     fd      - File open on client.
                   5732: #     reply   - Text to send to client.
                   5733: #     request - Original request from client.
                   5734: #
                   5735: sub Reply {
1.192     foxr     5736:     my ($fd, $reply, $request) = @_;
1.387     albertel 5737:     if (ref($reply)) {
                   5738: 	print $fd $$reply;
                   5739: 	print $fd "\n";
                   5740: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   5741:     } else {
                   5742: 	print $fd $reply;
                   5743: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   5744:     }
1.212     foxr     5745:     $Transactions++;
                   5746: }
                   5747: 
                   5748: 
                   5749: #
                   5750: #    Sub to report a failure.
                   5751: #    This function:
                   5752: #     -   Increments the failure statistic counters.
                   5753: #     -   Invokes Reply to send the error message to the client.
                   5754: # Parameters:
                   5755: #    fd       - File descriptor open on the client
                   5756: #    reply    - Reply text to emit.
                   5757: #    request  - The original request message (used by Reply
                   5758: #               to debug if that's enabled.
                   5759: # Implicit outputs:
                   5760: #    $Failures- The number of failures is incremented.
                   5761: #    Reply (invoked here) sends a message to the 
                   5762: #    client:
                   5763: #
                   5764: sub Failure {
                   5765:     my $fd      = shift;
                   5766:     my $reply   = shift;
                   5767:     my $request = shift;
                   5768:    
                   5769:     $Failures++;
                   5770:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     5771: }
1.57      www      5772: # ------------------------------------------------------------------ Log status
                   5773: 
                   5774: sub logstatus {
1.178     foxr     5775:     &status("Doing logging");
                   5776:     my $docdir=$perlvar{'lonDocRoot'};
                   5777:     {
                   5778: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  5779:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     5780:         $fh->close();
                   5781:     }
1.221     albertel 5782:     &status("Finished $$.txt");
                   5783:     {
                   5784: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   5785: 	flock(LOG,LOCK_EX);
                   5786: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   5787: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 5788: 	flock(LOG,LOCK_UN);
1.221     albertel 5789: 	close(LOG);
                   5790:     }
1.178     foxr     5791:     &status("Finished logging");
1.57      www      5792: }
                   5793: 
                   5794: sub initnewstatus {
                   5795:     my $docdir=$perlvar{'lonDocRoot'};
                   5796:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
                   5797:     my $now=time;
                   5798:     my $local=localtime($now);
                   5799:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      5800:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 5801:     while (my $filename=readdir(DIR)) {
1.64      www      5802:         unlink("$docdir/lon-status/londchld/$filename");
                   5803:     }
                   5804:     closedir(DIR);
1.57      www      5805: }
                   5806: 
                   5807: # -------------------------------------------------------------- Status setting
                   5808: 
                   5809: sub status {
                   5810:     my $what=shift;
                   5811:     my $now=time;
                   5812:     my $local=localtime($now);
1.178     foxr     5813:     $status=$local.': '.$what;
                   5814:     $0='lond: '.$what.' '.$local;
1.57      www      5815: }
1.11      www      5816: 
1.13      www      5817: # -------------------------------------------------------------- Talk to lonsql
                   5818: 
1.234     foxr     5819: sub sql_reply {
1.12      harris41 5820:     my ($cmd)=@_;
1.234     foxr     5821:     my $answer=&sub_sql_reply($cmd);
                   5822:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 5823:     return $answer;
                   5824: }
                   5825: 
1.234     foxr     5826: sub sub_sql_reply {
1.12      harris41 5827:     my ($cmd)=@_;
                   5828:     my $unixsock="mysqlsock";
                   5829:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   5830:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   5831:                                       Type    => SOCK_STREAM,
                   5832:                                       Timeout => 10)
                   5833:        or return "con_lost";
1.319     www      5834:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 5835:     my $answer=<$sclient>;
                   5836:     chomp($answer);
                   5837:     if (!$answer) { $answer="con_lost"; }
                   5838:     return $answer;
                   5839: }
                   5840: 
1.1       albertel 5841: # --------------------------------------- Is this the home server of an author?
1.11      www      5842: 
1.1       albertel 5843: sub ishome {
                   5844:     my $author=shift;
                   5845:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   5846:     my ($udom,$uname)=split(/\//,$author);
                   5847:     my $proname=propath($udom,$uname);
                   5848:     if (-e $proname) {
                   5849: 	return 'owner';
                   5850:     } else {
                   5851:         return 'not_owner';
                   5852:     }
                   5853: }
                   5854: 
                   5855: # ======================================================= Continue main program
                   5856: # ---------------------------------------------------- Fork once and dissociate
                   5857: 
1.134     albertel 5858: my $fpid=fork;
1.1       albertel 5859: exit if $fpid;
1.29      harris41 5860: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 5861: 
1.29      harris41 5862: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 5863: 
                   5864: # ------------------------------------------------------- Write our PID on disk
                   5865: 
1.134     albertel 5866: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 5867: open (PIDSAVE,">$execdir/logs/lond.pid");
                   5868: print PIDSAVE "$$\n";
                   5869: close(PIDSAVE);
1.190     albertel 5870: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      5871: &status('Starting');
1.1       albertel 5872: 
1.106     foxr     5873: 
1.1       albertel 5874: 
                   5875: # ----------------------------------------------------- Install signal handlers
                   5876: 
1.57      www      5877: 
1.1       albertel 5878: $SIG{CHLD} = \&REAPER;
                   5879: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   5880: $SIG{HUP}  = \&HUPSMAN;
1.57      www      5881: $SIG{USR1} = \&checkchildren;
1.144     foxr     5882: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     5883: 
1.148     foxr     5884: #  Read the host hashes:
1.368     albertel 5885: &Apache::lonnet::load_hosts_tab();
1.106     foxr     5886: 
1.286     albertel 5887: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
                   5888: 
1.106     foxr     5889: # --------------------------------------------------------------
                   5890: #   Accept connections.  When a connection comes in, it is validated
                   5891: #   and if good, a child process is created to process transactions
                   5892: #   along the connection.
                   5893: 
1.1       albertel 5894: while (1) {
1.165     albertel 5895:     &status('Starting accept');
1.106     foxr     5896:     $client = $server->accept() or next;
1.165     albertel 5897:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 5898:     make_new_child($client);
1.165     albertel 5899:     &status('Finished spawning');
1.1       albertel 5900: }
                   5901: 
1.212     foxr     5902: sub make_new_child {
                   5903:     my $pid;
                   5904: #    my $cipher;     # Now global
                   5905:     my $sigset;
1.178     foxr     5906: 
1.212     foxr     5907:     $client = shift;
                   5908:     &status('Starting new child '.$client);
                   5909:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   5910: 	     ")</font>");    
                   5911:     # block signal for fork
                   5912:     $sigset = POSIX::SigSet->new(SIGINT);
                   5913:     sigprocmask(SIG_BLOCK, $sigset)
                   5914:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     5915: 
1.212     foxr     5916:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     5917: 
1.212     foxr     5918:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   5919: 	                               # connection liveness.
1.178     foxr     5920: 
1.212     foxr     5921:     #
                   5922:     #  Figure out who we're talking to so we can record the peer in 
                   5923:     #  the pid hash.
                   5924:     #
                   5925:     my $caller = getpeername($client);
                   5926:     my ($port,$iaddr);
                   5927:     if (defined($caller) && length($caller) > 0) {
                   5928: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   5929:     } else {
                   5930: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   5931:     }
                   5932:     if (defined($iaddr)) {
                   5933: 	$clientip  = inet_ntoa($iaddr);
                   5934: 	Debug("Connected with $clientip");
                   5935:     } else {
                   5936: 	&logthis("Unable to determine clientip");
                   5937: 	$clientip='Unavailable';
                   5938:     }
                   5939:     
                   5940:     if ($pid) {
                   5941:         # Parent records the child's birth and returns.
                   5942:         sigprocmask(SIG_UNBLOCK, $sigset)
                   5943:             or die "Can't unblock SIGINT for fork: $!\n";
                   5944:         $children{$pid} = $clientip;
                   5945:         &status('Started child '.$pid);
                   5946:         return;
                   5947:     } else {
                   5948:         # Child can *not* return from this subroutine.
                   5949:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   5950:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   5951:                                 #don't get intercepted
                   5952:         $SIG{USR1}= \&logstatus;
                   5953:         $SIG{ALRM}= \&timeout;
                   5954:         $lastlog='Forked ';
                   5955:         $status='Forked';
1.178     foxr     5956: 
1.212     foxr     5957:         # unblock signals
                   5958:         sigprocmask(SIG_UNBLOCK, $sigset)
                   5959:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     5960: 
1.212     foxr     5961: #        my $tmpsnum=0;            # Now global
                   5962: #---------------------------------------------------- kerberos 5 initialization
                   5963:         &Authen::Krb5::init_context();
1.359     raeburn  5964: 	unless (($dist eq 'fedora5') || ($dist eq 'fedora4') ||  
                   5965: 		($dist eq 'fedora6') || ($dist eq 'suse9.3')) {
1.286     albertel 5966: 	    &Authen::Krb5::init_ets();
                   5967: 	}
1.209     albertel 5968: 
1.212     foxr     5969: 	&status('Accepted connection');
                   5970: # =============================================================================
                   5971:             # do something with the connection
                   5972: # -----------------------------------------------------------------------------
                   5973: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     5974: 
1.278     albertel 5975: 	my $outsideip=$clientip;
                   5976: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 5977: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 5978: 	}
                   5979: 
1.368     albertel 5980: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 5981: 	my $ismanager=($managers{$outsideip}    ne undef);
1.212     foxr     5982: 	$clientname  = "[unknonwn]";
                   5983: 	if($clientrec) {	# Establish client type.
                   5984: 	    $ConnectionType = "client";
1.368     albertel 5985: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     5986: 	    if($ismanager) {
                   5987: 		$ConnectionType = "both";
                   5988: 	    }
                   5989: 	} else {
                   5990: 	    $ConnectionType = "manager";
1.278     albertel 5991: 	    $clientname = $managers{$outsideip};
1.212     foxr     5992: 	}
                   5993: 	my $clientok;
1.178     foxr     5994: 
1.212     foxr     5995: 	if ($clientrec || $ismanager) {
                   5996: 	    &status("Waiting for init from $clientip $clientname");
                   5997: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   5998: 		     $clientip.
                   5999: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   6000: 	    &status("Connecting $clientip  ($clientname))"); 
                   6001: 	    my $remotereq=<$client>;
                   6002: 	    chomp($remotereq);
                   6003: 	    Debug("Got init: $remotereq");
1.337     albertel 6004: 
1.212     foxr     6005: 	    if ($remotereq =~ /^init/) {
                   6006: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   6007: 		#
                   6008: 		#  If the remote is attempting a local init... give that a try:
                   6009: 		#
                   6010: 		my ($i, $inittype) = split(/:/, $remotereq);
1.209     albertel 6011: 
1.212     foxr     6012: 		# If the connection type is ssl, but I didn't get my
                   6013: 		# certificate files yet, then I'll drop  back to 
                   6014: 		# insecure (if allowed).
                   6015: 		
                   6016: 		if($inittype eq "ssl") {
                   6017: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   6018: 		    my $kfile       = lonssl::KeyFile;
                   6019: 		    if((!$ca)   || 
                   6020: 		       (!$cert) || 
                   6021: 		       (!$kfile)) {
                   6022: 			$inittype = ""; # This forces insecure attempt.
                   6023: 			&logthis("<font color=\"blue\"> Certificates not "
                   6024: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     6025: 		    } else {	# SSL certificates are in place so
1.212     foxr     6026: 		    }		# Leave the inittype alone.
                   6027: 		}
                   6028: 
                   6029: 		if($inittype eq "local") {
                   6030: 		    my $key = LocalConnection($client, $remotereq);
                   6031: 		    if($key) {
                   6032: 			Debug("Got local key $key");
                   6033: 			$clientok     = 1;
                   6034: 			my $cipherkey = pack("H32", $key);
                   6035: 			$cipher       = new IDEA($cipherkey);
                   6036: 			print $client "ok:local\n";
                   6037: 			&logthis('<font color="green"'
                   6038: 				 . "Successful local authentication </font>");
                   6039: 			$keymode = "local"
1.178     foxr     6040: 		    } else {
1.212     foxr     6041: 			Debug("Failed to get local key");
                   6042: 			$clientok = 0;
                   6043: 			shutdown($client, 3);
                   6044: 			close $client;
1.178     foxr     6045: 		    }
1.212     foxr     6046: 		} elsif ($inittype eq "ssl") {
                   6047: 		    my $key = SSLConnection($client);
                   6048: 		    if ($key) {
                   6049: 			$clientok = 1;
                   6050: 			my $cipherkey = pack("H32", $key);
                   6051: 			$cipher       = new IDEA($cipherkey);
                   6052: 			&logthis('<font color="green">'
                   6053: 				 ."Successfull ssl authentication with $clientname </font>");
                   6054: 			$keymode = "ssl";
                   6055: 	     
1.178     foxr     6056: 		    } else {
1.212     foxr     6057: 			$clientok = 0;
                   6058: 			close $client;
1.178     foxr     6059: 		    }
1.212     foxr     6060: 	   
                   6061: 		} else {
                   6062: 		    my $ok = InsecureConnection($client);
                   6063: 		    if($ok) {
                   6064: 			$clientok = 1;
                   6065: 			&logthis('<font color="green">'
                   6066: 				 ."Successful insecure authentication with $clientname </font>");
                   6067: 			print $client "ok\n";
                   6068: 			$keymode = "insecure";
1.178     foxr     6069: 		    } else {
1.212     foxr     6070: 			&logthis('<font color="yellow">'
                   6071: 				  ."Attempted insecure connection disallowed </font>");
                   6072: 			close $client;
                   6073: 			$clientok = 0;
1.178     foxr     6074: 			
                   6075: 		    }
                   6076: 		}
1.212     foxr     6077: 	    } else {
                   6078: 		&logthis(
                   6079: 			 "<font color='blue'>WARNING: "
                   6080: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   6081: 		&status('No init '.$clientip);
                   6082: 	    }
                   6083: 	    
                   6084: 	} else {
                   6085: 	    &logthis(
                   6086: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   6087: 	    &status('Hung up on '.$clientip);
                   6088: 	}
                   6089:  
                   6090: 	if ($clientok) {
                   6091: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 6092: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 6093: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 6094: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     6095: 	    }
                   6096: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   6097: 	    &status('Will listen to '.$clientname);
                   6098: # ------------------------------------------------------------ Process requests
                   6099: 	    my $keep_going = 1;
                   6100: 	    my $user_input;
                   6101: 	    while(($user_input = get_request) && $keep_going) {
                   6102: 		alarm(120);
                   6103: 		Debug("Main: Got $user_input\n");
                   6104: 		$keep_going = &process_request($user_input);
1.178     foxr     6105: 		alarm(0);
1.212     foxr     6106: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     6107: 	    }
1.212     foxr     6108: 
1.59      www      6109: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     6110: 	}  else {
1.161     foxr     6111: 	    print $client "refused\n";
                   6112: 	    $client->close();
1.190     albertel 6113: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     6114: 		     ."Rejected client $clientip, closing connection</font>");
                   6115: 	}
1.212     foxr     6116:     }            
1.161     foxr     6117:     
1.1       albertel 6118: # =============================================================================
1.161     foxr     6119:     
1.190     albertel 6120:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     6121: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   6122:     
                   6123:     
                   6124:     # this exit is VERY important, otherwise the child will become
                   6125:     # a producer of more and more children, forking yourself into
                   6126:     # process death.
                   6127:     exit;
1.106     foxr     6128:     
1.78      foxr     6129: }
1.261     foxr     6130: #
                   6131: #   Determine if a user is an author for the indicated domain.
                   6132: #
                   6133: # Parameters:
                   6134: #    domain          - domain to check in .
                   6135: #    user            - Name of user to check.
                   6136: #
                   6137: # Return:
                   6138: #     1             - User is an author for domain.
                   6139: #     0             - User is not an author for domain.
                   6140: sub is_author {
                   6141:     my ($domain, $user) = @_;
                   6142: 
                   6143:     &Debug("is_author: $user @ $domain");
                   6144: 
                   6145:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   6146: 				 &GDBM_READER());
                   6147: 
                   6148:     #  Author role should show up as a key /domain/_au
1.78      foxr     6149: 
1.321     albertel 6150:     my $key    = "/$domain/_au";
                   6151:     my $value;
                   6152:     if (defined($hashref)) {
                   6153: 	$value = $hashref->{$key};
                   6154:     }
1.78      foxr     6155: 
1.261     foxr     6156:     if(defined($value)) {
                   6157: 	&Debug("$user @ $domain is an author");
                   6158:     }
                   6159: 
                   6160:     return defined($value);
                   6161: }
1.78      foxr     6162: #
                   6163: #   Checks to see if the input roleput request was to set
                   6164: # an author role.  If so, invokes the lchtmldir script to set
                   6165: # up a correct public_html 
                   6166: # Parameters:
                   6167: #    request   - The request sent to the rolesput subchunk.
                   6168: #                We're looking for  /domain/_au
                   6169: #    domain    - The domain in which the user is having roles doctored.
                   6170: #    user      - Name of the user for which the role is being put.
                   6171: #    authtype  - The authentication type associated with the user.
                   6172: #
1.289     albertel 6173: sub manage_permissions {
1.192     foxr     6174:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     6175: 
1.261     foxr     6176:     &Debug("manage_permissions: $request $domain $user $authtype");
                   6177: 
1.78      foxr     6178:     # See if the request is of the form /$domain/_au
1.289     albertel 6179:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.78      foxr     6180: 	my $execdir = $perlvar{'lonDaemons'};
                   6181: 	my $userhome= "/home/$user" ;
1.134     albertel 6182: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261     foxr     6183: 	&Debug("Setting homedir permissions for $userhome");
1.78      foxr     6184: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   6185:     }
                   6186: }
1.222     foxr     6187: 
                   6188: 
                   6189: #
                   6190: #  Return the full path of a user password file, whether it exists or not.
                   6191: # Parameters:
                   6192: #   domain     - Domain in which the password file lives.
                   6193: #   user       - name of the user.
                   6194: # Returns:
                   6195: #    Full passwd path:
                   6196: #
                   6197: sub password_path {
                   6198:     my ($domain, $user) = @_;
1.264     albertel 6199:     return &propath($domain, $user).'/passwd';
1.222     foxr     6200: }
                   6201: 
                   6202: #   Password Filename
                   6203: #   Returns the path to a passwd file given domain and user... only if
                   6204: #  it exists.
                   6205: # Parameters:
                   6206: #   domain    - Domain in which to search.
                   6207: #   user      - username.
                   6208: # Returns:
                   6209: #   - If the password file exists returns its path.
                   6210: #   - If the password file does not exist, returns undefined.
                   6211: #
                   6212: sub password_filename {
                   6213:     my ($domain, $user) = @_;
                   6214: 
                   6215:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   6216: 
                   6217:     my $path  = &password_path($domain, $user);
                   6218:     Debug("PasswordFilename got path: $path");
                   6219:     if(-e $path) {
                   6220: 	return $path;
                   6221:     } else {
                   6222: 	return undef;
                   6223:     }
                   6224: }
                   6225: 
                   6226: #
                   6227: #   Rewrite the contents of the user's passwd file.
                   6228: #  Parameters:
                   6229: #    domain    - domain of the user.
                   6230: #    name      - User's name.
                   6231: #    contents  - New contents of the file.
                   6232: # Returns:
                   6233: #   0    - Failed.
                   6234: #   1    - Success.
                   6235: #
                   6236: sub rewrite_password_file {
                   6237:     my ($domain, $user, $contents) = @_;
                   6238: 
                   6239:     my $file = &password_filename($domain, $user);
                   6240:     if (defined $file) {
                   6241: 	my $pf = IO::File->new(">$file");
                   6242: 	if($pf) {
                   6243: 	    print $pf "$contents\n";
                   6244: 	    return 1;
                   6245: 	} else {
                   6246: 	    return 0;
                   6247: 	}
                   6248:     } else {
                   6249: 	return 0;
                   6250:     }
                   6251: 
                   6252: }
                   6253: 
1.78      foxr     6254: #
1.222     foxr     6255: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     6256: 
                   6257: #     Returns the authorization type or nouser if there is no such user.
                   6258: #
1.222     foxr     6259: sub get_auth_type 
1.78      foxr     6260: {
1.192     foxr     6261: 
                   6262:     my ($domain, $user)  = @_;
1.78      foxr     6263: 
1.222     foxr     6264:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     6265:     my $proname    = &propath($domain, $user); 
                   6266:     my $passwdfile = "$proname/passwd";
                   6267:     if( -e $passwdfile ) {
                   6268: 	my $pf = IO::File->new($passwdfile);
                   6269: 	my $realpassword = <$pf>;
                   6270: 	chomp($realpassword);
1.79      foxr     6271: 	Debug("Password info = $realpassword\n");
1.78      foxr     6272: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     6273: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  6274: 	return "$authtype:$contentpwd";     
1.224     foxr     6275:     } else {
1.79      foxr     6276: 	Debug("Returning nouser");
1.78      foxr     6277: 	return "nouser";
                   6278:     }
1.1       albertel 6279: }
                   6280: 
1.220     foxr     6281: #
                   6282: #  Validate a user given their domain, name and password.  This utility
                   6283: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   6284: #  to validate the login credentials of a user.
                   6285: # Parameters:
                   6286: #    $domain    - The domain being logged into (this is required due to
                   6287: #                 the capability for multihomed systems.
                   6288: #    $user      - The name of the user being validated.
                   6289: #    $password  - The user's propoposed password.
                   6290: #
                   6291: # Returns:
                   6292: #     1        - The domain,user,pasword triplet corresponds to a valid
                   6293: #                user.
                   6294: #     0        - The domain,user,password triplet is not a valid user.
                   6295: #
                   6296: sub validate_user {
1.396     raeburn  6297:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     6298: 
                   6299:     # Why negative ~pi you may well ask?  Well this function is about
                   6300:     # authentication, and therefore very important to get right.
                   6301:     # I've initialized the flag that determines whether or not I've 
                   6302:     # validated correctly to a value it's not supposed to get.
                   6303:     # At the end of this function. I'll ensure that it's not still that
                   6304:     # value so we don't just wind up returning some accidental value
                   6305:     # as a result of executing an unforseen code path that
1.249     foxr     6306:     # did not set $validated.  At the end of valid execution paths,
                   6307:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     6308: 
                   6309:     my $validated = -3.14159;
                   6310: 
                   6311:     #  How we authenticate is determined by the type of authentication
                   6312:     #  the user has been assigned.  If the authentication type is
                   6313:     #  "nouser", the user does not exist so we will return 0.
                   6314: 
1.222     foxr     6315:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     6316:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   6317: 
                   6318:     my $null = pack("C",0);	# Used by kerberos auth types.
                   6319: 
1.395     raeburn  6320:     if ($howpwd eq 'nouser') {
1.396     raeburn  6321:         if ($checkdefauth) {
                   6322:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   6323:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   6324:                 $howpwd = $domdefaults{'auth_def'};
                   6325:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   6326:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   6327:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   6328:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   6329:                 $howpwd = $domdefaults{'auth_def'};
                   6330:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   6331:             }
1.395     raeburn  6332:         }
                   6333:     } 
1.220     foxr     6334:     if ($howpwd ne 'nouser') {
                   6335: 	if($howpwd eq "internal") { # Encrypted is in local password file.
                   6336: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
                   6337: 	}
                   6338: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   6339: 	    $contentpwd = (getpwnam($user))[1];
                   6340: 	    if($contentpwd) {
                   6341: 		if($contentpwd eq 'x') { # Shadow password file...
                   6342: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   6343: 		    open PWAUTH,  "|$pwauth_path" or
                   6344: 			die "Cannot invoke authentication";
                   6345: 		    print PWAUTH "$user\n$password\n";
                   6346: 		    close PWAUTH;
                   6347: 		    $validated = ! $?;
                   6348: 
                   6349: 		} else { 	         # Passwords in /etc/passwd. 
                   6350: 		    $validated = (crypt($password,
                   6351: 					$contentpwd) eq $contentpwd);
                   6352: 		}
                   6353: 	    } else {
                   6354: 		$validated = 0;
                   6355: 	    }
                   6356: 	}
                   6357: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   6358: 	    if(! ($password =~ /$null/) ) {
                   6359: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   6360: 							   "",
                   6361: 							   $contentpwd,,
                   6362: 							   'krbtgt',
                   6363: 							   $contentpwd,
                   6364: 							   1,
                   6365: 							   $password);
                   6366: 		if(!$k4error) {
                   6367: 		    $validated = 1;
1.224     foxr     6368: 		} else {
1.220     foxr     6369: 		    $validated = 0;
                   6370: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   6371: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   6372: 		}
1.224     foxr     6373: 	    } else {
1.220     foxr     6374: 		$validated = 0; # Password has a match with null.
                   6375: 	    }
1.224     foxr     6376: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220     foxr     6377: 	    if(!($password =~ /$null/)) { # Null password not allowed.
                   6378: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   6379: 							  .$contentpwd);
                   6380: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   6381: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   6382: 		my $credentials= &Authen::Krb5::cc_default();
1.359     raeburn  6383: 		$credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   6384:                                                                  .$contentpwd));
1.394     raeburn  6385:                 my $krbreturn;
                   6386:                 if (exists(&Authen::Krb5::get_init_creds_password)) {
                   6387:                     $krbreturn = 
                   6388:                         &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   6389:                                                                $krbservice);
                   6390:                     $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   6391:                 } else {
                   6392: 		    $krbreturn  = 
                   6393:                         &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   6394: 		 						$password,$credentials);
                   6395: 		    $validated = ($krbreturn == 1);
                   6396:                 }
1.380     albertel 6397: 		if (!$validated) {
                   6398: 		    &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   6399: 			     &Authen::Krb5::error());
                   6400: 		}
1.224     foxr     6401: 	    } else {
1.220     foxr     6402: 		$validated = 0;
                   6403: 	    }
1.224     foxr     6404: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     6405: 	    #  Authenticate via installation specific authentcation method:
                   6406: 	    $validated = &localauth::localauth($user, 
                   6407: 					       $password, 
1.353     albertel 6408: 					       $contentpwd,
                   6409: 					       $domain);
1.358     albertel 6410: 	    if ($validated < 0) {
1.357     albertel 6411: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   6412: 		$validated = 0;
                   6413: 	    }
1.224     foxr     6414: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     6415: 	    $validated = 0;
                   6416: 	}
                   6417:     } else {
                   6418: 	$validated = 0;
                   6419:     }
                   6420:     #
                   6421:     #  $validated has the correct stat of the authentication:
                   6422:     #
                   6423: 
                   6424:     unless ($validated != -3.14159) {
1.249     foxr     6425: 	#  I >really really< want to know if this happens.
                   6426: 	#  since it indicates that user authentication is badly
                   6427: 	#  broken in some code path.
                   6428:         #
                   6429: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     6430:     }
                   6431:     return $validated;
                   6432: }
                   6433: 
                   6434: 
1.84      albertel 6435: sub addline {
                   6436:     my ($fname,$hostid,$ip,$newline)=@_;
                   6437:     my $contents;
                   6438:     my $found=0;
1.355     albertel 6439:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 6440:     my $sh;
1.84      albertel 6441:     if ($sh=IO::File->new("$fname.subscription")) {
                   6442: 	while (my $subline=<$sh>) {
                   6443: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   6444: 	}
                   6445: 	$sh->close();
                   6446:     }
                   6447:     $sh=IO::File->new(">$fname.subscription");
                   6448:     if ($contents) { print $sh $contents; }
                   6449:     if ($newline) { print $sh $newline; }
                   6450:     $sh->close();
                   6451:     return $found;
1.86      www      6452: }
                   6453: 
1.234     foxr     6454: sub get_chat {
1.324     raeburn  6455:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 6456: 
1.87      www      6457:     my @entries=();
1.324     raeburn  6458:     my $namespace = 'nohist_chatroom';
                   6459:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 6460:     if ($group ne '') {
1.324     raeburn  6461:         $namespace .= '_'.$group;
                   6462:         $namespace_inroom .= '_'.$group;
                   6463:     }
                   6464:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 6465: 				 &GDBM_READER());
                   6466:     if ($hashref) {
                   6467: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 6468: 	&untie_user_hash($hashref);
1.123     www      6469:     }
1.124     www      6470:     my @participants=();
1.134     albertel 6471:     my $cutoff=time-60;
1.324     raeburn  6472:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 6473: 			      &GDBM_WRCREAT());
                   6474:     if ($hashref) {
                   6475:         $hashref->{$uname.':'.$udom}=time;
                   6476:         foreach my $user (sort(keys(%$hashref))) {
                   6477: 	    if ($hashref->{$user}>$cutoff) {
                   6478: 		push(@participants, 'active_participant:'.$user);
1.123     www      6479:             }
                   6480:         }
1.311     albertel 6481:         &untie_user_hash($hashref);
1.86      www      6482:     }
1.124     www      6483:     return (@participants,@entries);
1.86      www      6484: }
                   6485: 
1.234     foxr     6486: sub chat_add {
1.324     raeburn  6487:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 6488:     my @entries=();
1.142     www      6489:     my $time=time;
1.324     raeburn  6490:     my $namespace = 'nohist_chatroom';
                   6491:     my $logfile = 'chatroom.log';
1.335     albertel 6492:     if ($group ne '') {
1.324     raeburn  6493:         $namespace .= '_'.$group;
                   6494:         $logfile = 'chatroom_'.$group.'.log';
                   6495:     }
                   6496:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 6497: 				 &GDBM_WRCREAT());
                   6498:     if ($hashref) {
                   6499: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 6500: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   6501: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   6502: 	my $newid=$time.'_000000';
                   6503: 	if ($thentime==$time) {
                   6504: 	    $idnum=~s/^0+//;
                   6505: 	    $idnum++;
                   6506: 	    $idnum=substr('000000'.$idnum,-6,6);
                   6507: 	    $newid=$time.'_'.$idnum;
                   6508: 	}
1.310     albertel 6509: 	$hashref->{$newid}=$newchat;
1.88      albertel 6510: 	my $expired=$time-3600;
1.310     albertel 6511: 	foreach my $comment (keys(%$hashref)) {
                   6512: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 6513: 	    if ($thistime<$expired) {
1.310     albertel 6514: 		delete $hashref->{$comment};
1.88      albertel 6515: 	    }
                   6516: 	}
1.310     albertel 6517: 	{
                   6518: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  6519: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 6520: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   6521: 	    }
                   6522: 	    close(CHATLOG);
1.142     www      6523: 	}
1.311     albertel 6524: 	&untie_user_hash($hashref);
1.86      www      6525:     }
1.84      albertel 6526: }
                   6527: 
                   6528: sub unsub {
                   6529:     my ($fname,$clientip)=@_;
                   6530:     my $result;
1.188     foxr     6531:     my $unsubs = 0;		# Number of successful unsubscribes:
                   6532: 
                   6533: 
                   6534:     # An old way subscriptions were handled was to have a 
                   6535:     # subscription marker file:
                   6536: 
                   6537:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     6538:     if (unlink("$fname.$clientname")) {
1.188     foxr     6539: 	$unsubs++;		# Successful unsub via marker file.
                   6540:     } 
                   6541: 
                   6542:     # The more modern way to do it is to have a subscription list
                   6543:     # file:
                   6544: 
1.84      albertel 6545:     if (-e "$fname.subscription") {
1.161     foxr     6546: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     6547: 	if ($found) { 
                   6548: 	    $unsubs++;
                   6549: 	}
                   6550:     } 
                   6551: 
                   6552:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   6553:     #  resource we can return ok:
                   6554: 
                   6555:     if($unsubs) {
                   6556: 	$result = "ok\n";
1.84      albertel 6557:     } else {
1.188     foxr     6558: 	$result = "not_subscribed\n";
1.84      albertel 6559:     }
1.188     foxr     6560: 
1.84      albertel 6561:     return $result;
                   6562: }
                   6563: 
1.101     www      6564: sub currentversion {
                   6565:     my $fname=shift;
                   6566:     my $version=-1;
                   6567:     my $ulsdir='';
                   6568:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   6569:        $ulsdir=$1;
                   6570:     }
1.114     albertel 6571:     my ($fnamere1,$fnamere2);
                   6572:     # remove version if already specified
1.101     www      6573:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 6574:     # get the bits that go before and after the version number
                   6575:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   6576: 	$fnamere1=$1;
                   6577: 	$fnamere2='.'.$2;
                   6578:     }
1.101     www      6579:     if (-e $fname) { $version=1; }
                   6580:     if (-e $ulsdir) {
1.134     albertel 6581: 	if(-d $ulsdir) {
                   6582: 	    if (opendir(LSDIR,$ulsdir)) {
                   6583: 		my $ulsfn;
                   6584: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      6585: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 6586: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   6587: 		    unless (-l $thisfile) {
1.160     www      6588: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 6589: 			    if ($1>$version) { $version=$1; }
                   6590: 			}
                   6591: 		    }
                   6592: 		}
                   6593: 		closedir(LSDIR);
                   6594: 		$version++;
                   6595: 	    }
                   6596: 	}
                   6597:     }
                   6598:     return $version;
1.101     www      6599: }
                   6600: 
                   6601: sub thisversion {
                   6602:     my $fname=shift;
                   6603:     my $version=-1;
                   6604:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   6605: 	$version=$1;
                   6606:     }
                   6607:     return $version;
                   6608: }
                   6609: 
1.84      albertel 6610: sub subscribe {
                   6611:     my ($userinput,$clientip)=@_;
                   6612:     my $result;
1.293     albertel 6613:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 6614:     my $ownership=&ishome($fname);
                   6615:     if ($ownership eq 'owner') {
1.101     www      6616: # explitly asking for the current version?
                   6617:         unless (-e $fname) {
                   6618:             my $currentversion=&currentversion($fname);
                   6619: 	    if (&thisversion($fname)==$currentversion) {
                   6620:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   6621: 		    my $root=$1;
                   6622:                     my $extension=$2;
                   6623:                     symlink($root.'.'.$extension,
                   6624:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      6625:                     unless ($extension=~/\.meta$/) {
                   6626:                        symlink($root.'.'.$extension.'.meta',
                   6627:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   6628: 		    }
1.101     www      6629:                 }
                   6630:             }
                   6631:         }
1.84      albertel 6632: 	if (-e $fname) {
                   6633: 	    if (-d $fname) {
                   6634: 		$result="directory\n";
                   6635: 	    } else {
1.161     foxr     6636: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 6637: 		my $now=time;
1.161     foxr     6638: 		my $found=&addline($fname,$clientname,$clientip,
                   6639: 				   "$clientname:$clientip:$now\n");
1.84      albertel 6640: 		if ($found) { $result="$fname\n"; }
                   6641: 		# if they were subscribed to only meta data, delete that
                   6642:                 # subscription, when you subscribe to a file you also get
                   6643:                 # the metadata
                   6644: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   6645: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.373     albertel 6646: 		$fname="http://".&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 6647: 		$result="$fname\n";
                   6648: 	    }
                   6649: 	} else {
                   6650: 	    $result="not_found\n";
                   6651: 	}
                   6652:     } else {
                   6653: 	$result="rejected\n";
                   6654:     }
                   6655:     return $result;
                   6656: }
1.287     foxr     6657: #  Change the passwd of a unix user.  The caller must have
                   6658: #  first verified that the user is a loncapa user.
                   6659: #
                   6660: # Parameters:
                   6661: #    user      - Unix user name to change.
                   6662: #    pass      - New password for the user.
                   6663: # Returns:
                   6664: #    ok    - if success
                   6665: #    other - Some meaningfule error message string.
                   6666: # NOTE:
                   6667: #    invokes a setuid script to change the passwd.
                   6668: sub change_unix_password {
                   6669:     my ($user, $pass) = @_;
                   6670: 
                   6671:     &Debug("change_unix_password");
                   6672:     my $execdir=$perlvar{'lonDaemons'};
                   6673:     &Debug("Opening lcpasswd pipeline");
                   6674:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   6675: 			   ."$perlvar{'lonDaemons'}"
                   6676: 			   ."/logs/lcpasswd.log");
                   6677:     print $pf "$user\n$pass\n$pass\n";
                   6678:     close $pf;
                   6679:     my $err = $?;
                   6680:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   6681: 	"pwchange_falure - unknown error";
                   6682: 
                   6683:     
                   6684: }
                   6685: 
1.91      albertel 6686: 
                   6687: sub make_passwd_file {
1.98      foxr     6688:     my ($uname, $umode,$npass,$passfilename)=@_;
1.390     raeburn  6689:     my $result="ok";
1.91      albertel 6690:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   6691: 	{
                   6692: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     6693: 	    if ($pf) {
                   6694: 		print $pf "$umode:$npass\n";
                   6695: 	    } else {
                   6696: 		$result = "pass_file_failed_error";
                   6697: 	    }
1.91      albertel 6698: 	}
                   6699:     } elsif ($umode eq 'internal') {
                   6700: 	my $salt=time;
                   6701: 	$salt=substr($salt,6,2);
                   6702: 	my $ncpass=crypt($npass,$salt);
                   6703: 	{
                   6704: 	    &Debug("Creating internal auth");
                   6705: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     6706: 	    if($pf) {
                   6707: 		print $pf "internal:$ncpass\n"; 
                   6708: 	    } else {
                   6709: 		$result = "pass_file_failed_error";
                   6710: 	    }
1.91      albertel 6711: 	}
                   6712:     } elsif ($umode eq 'localauth') {
                   6713: 	{
                   6714: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     6715: 	    if($pf) {
                   6716: 		print $pf "localauth:$npass\n";
                   6717: 	    } else {
                   6718: 		$result = "pass_file_failed_error";
                   6719: 	    }
1.91      albertel 6720: 	}
                   6721:     } elsif ($umode eq 'unix') {
                   6722: 	{
1.186     foxr     6723: 	    #
                   6724: 	    #  Don't allow the creation of privileged accounts!!! that would
                   6725: 	    #  be real bad!!!
                   6726: 	    #
                   6727: 	    my $uid = getpwnam($uname);
                   6728: 	    if((defined $uid) && ($uid == 0)) {
                   6729: 		&logthis(">>>Attempted to create privilged account blocked");
                   6730: 		return "no_priv_account_error\n";
                   6731: 	    }
                   6732: 
1.223     foxr     6733: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224     foxr     6734: 
                   6735: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
1.91      albertel 6736: 	    {
                   6737: 		&Debug("Executing external: ".$execpath);
1.98      foxr     6738: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  6739: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 6740: 		print $se "$uname\n";
                   6741: 		print $se "$npass\n";
                   6742: 		print $se "$npass\n";
1.223     foxr     6743: 		print $se "$lc_error_file\n"; # Status -> unique file.
1.97      foxr     6744: 	    }
1.285     foxr     6745: 	    if (-r $lc_error_file) {
                   6746: 		&Debug("Opening error file: $lc_error_file");
                   6747: 		my $error = IO::File->new("< $lc_error_file");
                   6748: 		my $useraddok = <$error>;
                   6749: 		$error->close;
                   6750: 		unlink($lc_error_file);
                   6751: 		
                   6752: 		chomp $useraddok;
                   6753: 	
                   6754: 		if($useraddok > 0) {
                   6755: 		    my $error_text = &lcuseraddstrerror($useraddok);
                   6756: 		    &logthis("Failed lcuseradd: $error_text");
1.390     raeburn  6757: 		    $result = "lcuseradd_failed:$error_text";
1.285     foxr     6758: 		}  else {
                   6759: 		    my $pf = IO::File->new(">$passfilename");
                   6760: 		    if($pf) {
                   6761: 			print $pf "unix:\n";
                   6762: 		    } else {
                   6763: 			$result = "pass_file_failed_error";
                   6764: 		    }
                   6765: 		}
1.224     foxr     6766: 	    }  else {
1.285     foxr     6767: 		&Debug("Could not locate lcuseradd error: $lc_error_file");
                   6768: 		$result="bug_lcuseradd_no_output_file";
1.91      albertel 6769: 	    }
                   6770: 	}
                   6771:     } elsif ($umode eq 'none') {
                   6772: 	{
1.223     foxr     6773: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     6774: 	    if($pf) {
                   6775: 		print $pf "none:\n";
                   6776: 	    } else {
                   6777: 		$result = "pass_file_failed_error";
                   6778: 	    }
1.91      albertel 6779: 	}
                   6780:     } else {
1.390     raeburn  6781: 	$result="auth_mode_error";
1.91      albertel 6782:     }
                   6783:     return $result;
1.121     albertel 6784: }
                   6785: 
1.265     albertel 6786: sub convert_photo {
                   6787:     my ($start,$dest)=@_;
                   6788:     system("convert $start $dest");
                   6789: }
                   6790: 
1.121     albertel 6791: sub sethost {
                   6792:     my ($remotereq) = @_;
                   6793:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 6794:     # ignore sethost if we are already correct
                   6795:     if ($hostid eq $currenthostid) {
                   6796: 	return 'ok';
                   6797:     }
                   6798: 
1.121     albertel 6799:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 6800:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   6801: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  6802: 	$currenthostid  =$hostid;
1.369     albertel 6803: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.386     albertel 6804: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 6805:     } else {
                   6806: 	&logthis("Requested host id $hostid not an alias of ".
                   6807: 		 $perlvar{'lonHostID'}." refusing connection");
                   6808: 	return 'unable_to_set';
                   6809:     }
                   6810:     return 'ok';
                   6811: }
                   6812: 
                   6813: sub version {
                   6814:     my ($userinput)=@_;
                   6815:     $remoteVERSION=(split(/:/,$userinput))[1];
                   6816:     return "version:$VERSION";
1.127     albertel 6817: }
1.178     foxr     6818: 
1.200     matthew  6819: 
1.61      harris41 6820: # ----------------------------------- POD (plain old documentation, CPAN style)
                   6821: 
                   6822: =head1 NAME
                   6823: 
                   6824: lond - "LON Daemon" Server (port "LOND" 5663)
                   6825: 
                   6826: =head1 SYNOPSIS
                   6827: 
1.74      harris41 6828: Usage: B<lond>
                   6829: 
                   6830: Should only be run as user=www.  This is a command-line script which
                   6831: is invoked by B<loncron>.  There is no expectation that a typical user
                   6832: will manually start B<lond> from the command-line.  (In other words,
                   6833: DO NOT START B<lond> YOURSELF.)
1.61      harris41 6834: 
                   6835: =head1 DESCRIPTION
                   6836: 
1.74      harris41 6837: There are two characteristics associated with the running of B<lond>,
                   6838: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   6839: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   6840: subscriptions, etc).  These are described in two large
                   6841: sections below.
                   6842: 
                   6843: B<PROCESS MANAGEMENT>
                   6844: 
1.61      harris41 6845: Preforker - server who forks first. Runs as a daemon. HUPs.
                   6846: Uses IDEA encryption
                   6847: 
1.74      harris41 6848: B<lond> forks off children processes that correspond to the other servers
                   6849: in the network.  Management of these processes can be done at the
                   6850: parent process level or the child process level.
                   6851: 
                   6852: B<logs/lond.log> is the location of log messages.
                   6853: 
                   6854: The process management is now explained in terms of linux shell commands,
                   6855: subroutines internal to this code, and signal assignments:
                   6856: 
                   6857: =over 4
                   6858: 
                   6859: =item *
                   6860: 
                   6861: PID is stored in B<logs/lond.pid>
                   6862: 
                   6863: This is the process id number of the parent B<lond> process.
                   6864: 
                   6865: =item *
                   6866: 
                   6867: SIGTERM and SIGINT
                   6868: 
                   6869: Parent signal assignment:
                   6870:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   6871: 
                   6872: Child signal assignment:
                   6873:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   6874: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   6875:  to restart a new child.)
                   6876: 
                   6877: Command-line invocations:
                   6878:  B<kill> B<-s> SIGTERM I<PID>
                   6879:  B<kill> B<-s> SIGINT I<PID>
                   6880: 
                   6881: Subroutine B<HUNTSMAN>:
                   6882:  This is only invoked for the B<lond> parent I<PID>.
                   6883: This kills all the children, and then the parent.
                   6884: The B<lonc.pid> file is cleared.
                   6885: 
                   6886: =item *
                   6887: 
                   6888: SIGHUP
                   6889: 
                   6890: Current bug:
                   6891:  This signal can only be processed the first time
                   6892: on the parent process.  Subsequent SIGHUP signals
                   6893: have no effect.
                   6894: 
                   6895: Parent signal assignment:
                   6896:  $SIG{HUP}  = \&HUPSMAN;
                   6897: 
                   6898: Child signal assignment:
                   6899:  none (nothing happens)
                   6900: 
                   6901: Command-line invocations:
                   6902:  B<kill> B<-s> SIGHUP I<PID>
                   6903: 
                   6904: Subroutine B<HUPSMAN>:
                   6905:  This is only invoked for the B<lond> parent I<PID>,
                   6906: This kills all the children, and then the parent.
                   6907: The B<lond.pid> file is cleared.
                   6908: 
                   6909: =item *
                   6910: 
                   6911: SIGUSR1
                   6912: 
                   6913: Parent signal assignment:
                   6914:  $SIG{USR1} = \&USRMAN;
                   6915: 
                   6916: Child signal assignment:
                   6917:  $SIG{USR1}= \&logstatus;
                   6918: 
                   6919: Command-line invocations:
                   6920:  B<kill> B<-s> SIGUSR1 I<PID>
                   6921: 
                   6922: Subroutine B<USRMAN>:
                   6923:  When invoked for the B<lond> parent I<PID>,
                   6924: SIGUSR1 is sent to all the children, and the status of
                   6925: each connection is logged.
1.144     foxr     6926: 
                   6927: =item *
                   6928: 
                   6929: SIGUSR2
                   6930: 
                   6931: Parent Signal assignment:
                   6932:     $SIG{USR2} = \&UpdateHosts
                   6933: 
                   6934: Child signal assignment:
                   6935:     NONE
                   6936: 
1.74      harris41 6937: 
                   6938: =item *
                   6939: 
                   6940: SIGCHLD
                   6941: 
                   6942: Parent signal assignment:
                   6943:  $SIG{CHLD} = \&REAPER;
                   6944: 
                   6945: Child signal assignment:
                   6946:  none
                   6947: 
                   6948: Command-line invocations:
                   6949:  B<kill> B<-s> SIGCHLD I<PID>
                   6950: 
                   6951: Subroutine B<REAPER>:
                   6952:  This is only invoked for the B<lond> parent I<PID>.
                   6953: Information pertaining to the child is removed.
                   6954: The socket port is cleaned up.
                   6955: 
                   6956: =back
                   6957: 
                   6958: B<SERVER-SIDE ACTIVITIES>
                   6959: 
                   6960: Server-side information can be accepted in an encrypted or non-encrypted
                   6961: method.
                   6962: 
                   6963: =over 4
                   6964: 
                   6965: =item ping
                   6966: 
                   6967: Query a client in the hosts.tab table; "Are you there?"
                   6968: 
                   6969: =item pong
                   6970: 
                   6971: Respond to a ping query.
                   6972: 
                   6973: =item ekey
                   6974: 
                   6975: Read in encrypted key, make cipher.  Respond with a buildkey.
                   6976: 
                   6977: =item load
                   6978: 
                   6979: Respond with CPU load based on a computation upon /proc/loadavg.
                   6980: 
                   6981: =item currentauth
                   6982: 
                   6983: Reply with current authentication information (only over an
                   6984: encrypted channel).
                   6985: 
                   6986: =item auth
                   6987: 
                   6988: Only over an encrypted channel, reply as to whether a user's
                   6989: authentication information can be validated.
                   6990: 
                   6991: =item passwd
                   6992: 
                   6993: Allow for a password to be set.
                   6994: 
                   6995: =item makeuser
                   6996: 
                   6997: Make a user.
                   6998: 
                   6999: =item passwd
                   7000: 
                   7001: Allow for authentication mechanism and password to be changed.
                   7002: 
                   7003: =item home
1.61      harris41 7004: 
1.74      harris41 7005: Respond to a question "are you the home for a given user?"
                   7006: 
                   7007: =item update
                   7008: 
                   7009: Update contents of a subscribed resource.
                   7010: 
                   7011: =item unsubscribe
                   7012: 
                   7013: The server is unsubscribing from a resource.
                   7014: 
                   7015: =item subscribe
                   7016: 
                   7017: The server is subscribing to a resource.
                   7018: 
                   7019: =item log
                   7020: 
                   7021: Place in B<logs/lond.log>
                   7022: 
                   7023: =item put
                   7024: 
                   7025: stores hash in namespace
                   7026: 
1.230     foxr     7027: =item rolesputy
1.74      harris41 7028: 
                   7029: put a role into a user's environment
                   7030: 
                   7031: =item get
                   7032: 
                   7033: returns hash with keys from array
                   7034: reference filled in from namespace
                   7035: 
                   7036: =item eget
                   7037: 
                   7038: returns hash with keys from array
                   7039: reference filled in from namesp (encrypts the return communication)
                   7040: 
                   7041: =item rolesget
                   7042: 
                   7043: get a role from a user's environment
                   7044: 
                   7045: =item del
                   7046: 
                   7047: deletes keys out of array from namespace
                   7048: 
                   7049: =item keys
                   7050: 
                   7051: returns namespace keys
                   7052: 
                   7053: =item dump
                   7054: 
                   7055: dumps the complete (or key matching regexp) namespace into a hash
                   7056: 
                   7057: =item store
                   7058: 
                   7059: stores hash permanently
                   7060: for this url; hashref needs to be given and should be a \%hashname; the
                   7061: remaining args aren't required and if they aren't passed or are '' they will
                   7062: be derived from the ENV
                   7063: 
                   7064: =item restore
                   7065: 
                   7066: returns a hash for a given url
                   7067: 
                   7068: =item querysend
                   7069: 
                   7070: Tells client about the lonsql process that has been launched in response
                   7071: to a sent query.
                   7072: 
                   7073: =item queryreply
                   7074: 
                   7075: Accept information from lonsql and make appropriate storage in temporary
                   7076: file space.
                   7077: 
                   7078: =item idput
                   7079: 
                   7080: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   7081: for each student, defined perhaps by the institutional Registrar.)
                   7082: 
                   7083: =item idget
                   7084: 
                   7085: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   7086: for each student, defined perhaps by the institutional Registrar.)
                   7087: 
                   7088: =item tmpput
                   7089: 
                   7090: Accept and store information in temporary space.
                   7091: 
                   7092: =item tmpget
                   7093: 
                   7094: Send along temporarily stored information.
                   7095: 
                   7096: =item ls
                   7097: 
                   7098: List part of a user's directory.
                   7099: 
1.135     foxr     7100: =item pushtable
                   7101: 
                   7102: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   7103: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   7104: must be restored manually in case of a problem with the new table file.
                   7105: pushtable requires that the request be encrypted and validated via
                   7106: ValidateManager.  The form of the command is:
                   7107: enc:pushtable tablename <tablecontents> \n
                   7108: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   7109: cleartext newline.
                   7110: 
1.74      harris41 7111: =item Hanging up (exit or init)
                   7112: 
                   7113: What to do when a client tells the server that they (the client)
                   7114: are leaving the network.
                   7115: 
                   7116: =item unknown command
                   7117: 
                   7118: If B<lond> is sent an unknown command (not in the list above),
                   7119: it replys to the client "unknown_cmd".
1.135     foxr     7120: 
1.74      harris41 7121: 
                   7122: =item UNKNOWN CLIENT
                   7123: 
                   7124: If the anti-spoofing algorithm cannot verify the client,
                   7125: the client is rejected (with a "refused" message sent
                   7126: to the client, and the connection is closed.
                   7127: 
                   7128: =back
1.61      harris41 7129: 
                   7130: =head1 PREREQUISITES
                   7131: 
                   7132: IO::Socket
                   7133: IO::File
                   7134: Apache::File
                   7135: POSIX
                   7136: Crypt::IDEA
                   7137: LWP::UserAgent()
                   7138: GDBM_File
                   7139: Authen::Krb4
1.91      albertel 7140: Authen::Krb5
1.61      harris41 7141: 
                   7142: =head1 COREQUISITES
                   7143: 
                   7144: =head1 OSNAMES
                   7145: 
                   7146: linux
                   7147: 
                   7148: =head1 SCRIPT CATEGORIES
                   7149: 
                   7150: Server/Process
                   7151: 
                   7152: =cut
1.409     foxr     7153: 
                   7154: 
                   7155: =pod
                   7156: 
                   7157: =head1 LOG MESSAGES
                   7158: 
                   7159: The messages below can be emitted in the lond log.  This log is located
                   7160: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   7161: to provide coloring if examined from inside a web page. Some do not.
                   7162: Where color is used, the colors are; Red for sometihhng to get excited
                   7163: about and to follow up on. Yellow for something to keep an eye on to
                   7164: be sure it does not get worse, Green,and Blue for informational items.
                   7165: 
                   7166: In the discussions below, sometimes reference is made to ~httpd
                   7167: when describing file locations.  There isn't really an httpd 
                   7168: user, however there is an httpd directory that gets installed in the
                   7169: place that user home directories go.  On linux, this is usually
                   7170: (always?) /home/httpd.
                   7171: 
                   7172: 
                   7173: Some messages are colorless.  These are usually (not always)
                   7174: Green/Blue color level messages.
                   7175: 
                   7176: =over 2
                   7177: 
                   7178: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   7179: 
                   7180: A local connection negotiation was attempted by
                   7181: a host whose IP address was not 127.0.0.1.
                   7182: The socket is closed and the child will exit.
                   7183: lond has three ways to establish an encyrption
                   7184: key with a client:
                   7185: 
                   7186: =over 2
                   7187: 
                   7188: =item local 
                   7189: 
                   7190: The key is written and read from a file.
                   7191: This is only valid for connections from localhost.
                   7192: 
                   7193: =item insecure 
                   7194: 
                   7195: The key is generated by the server and
                   7196: transmitted to the client.
                   7197: 
                   7198: =item  ssl (secure)
                   7199: 
                   7200: An ssl connection is negotiated with the client,
                   7201: the key is generated by the server and sent to the 
                   7202: client across this ssl connection before the
                   7203: ssl connectionis terminated and clear text
                   7204: transmission resumes.
                   7205: 
                   7206: =back
                   7207: 
                   7208: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   7209: 
                   7210: The client is local but has not sent an initialization
                   7211: string that is the literal "init:local"  The connection
                   7212: is closed and the child exits.
                   7213: 
                   7214: =item Red CRITICAL Can't get key file <error>        
                   7215: 
                   7216: SSL key negotiation is being attempted but the call to
                   7217: lonssl::KeyFile  failed.  This usually means that the
                   7218: configuration file is not correctly defining or protecting
                   7219: the directories/files lonCertificateDirectory or
                   7220: lonnetPrivateKey
                   7221: <error> is a string that describes the reason that
                   7222: the key file could not be located.
                   7223: 
                   7224: =item (Red) CRITICAL  Can't get certificates <error>  
                   7225: 
                   7226: SSL key negotiation failed because we were not able to retrives our certificate
                   7227: or the CA's certificate in the call to lonssl::CertificateFile
                   7228: <error> is the textual reason this failed.  Usual reasons:
                   7229: 
                   7230: =over 2
                   7231:        
                   7232: =item Apache config file for loncapa  incorrect:
                   7233:  
                   7234: one of the variables 
                   7235: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   7236: undefined or incorrect
                   7237: 
                   7238: =item Permission error:
                   7239: 
                   7240: The directory pointed to by lonCertificateDirectory is not readable by lond
                   7241: 
                   7242: =item Permission error:
                   7243: 
                   7244: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   7245: 
                   7246: =item Installation error:                         
                   7247: 
                   7248: Either the certificate authority file or the certificate have not
                   7249: been installed in lonCertificateDirectory.
                   7250: 
                   7251: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   7252: 
                   7253: The promotion of the connection from plaintext to SSL failed
                   7254: <err> is the reason for the failure.  There are two
                   7255: system calls involved in the promotion (one of which failed), 
                   7256: a dup to produce
                   7257: a second fd on the raw socket over which the encrypted data
                   7258: will flow and IO::SOcket::SSL->new_from_fd which creates
                   7259: the SSL connection on the duped fd.
                   7260: 
                   7261: =item (Blue)   WARNING client did not respond to challenge 
                   7262: 
                   7263: This occurs on an insecure (non SSL) connection negotiation request.
                   7264: lond generates some number from the time, the PID and sends it to
                   7265: the client.  The client must respond by echoing this information back.
                   7266: If the client does not do so, that's a violation of the challenge
                   7267: protocols and the connection will be failed.
                   7268: 
                   7269: =item (Red) No manager table. Nobody can manage!!    
                   7270: 
                   7271: lond has the concept of privileged hosts that
                   7272: can perform remote management function such
                   7273: as update the hosts.tab.   The manager hosts
                   7274: are described in the 
                   7275: ~httpd/lonTabs/managers.tab file.
                   7276: this message is logged if this file is missing.
                   7277: 
                   7278: 
                   7279: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   7280: 
                   7281: Reports the successful parse and registration
                   7282: of a specific manager. 
                   7283: 
                   7284: =item Green existing host <clustername:dnsname>  
                   7285: 
                   7286: The manager host is already defined in the hosts.tab
                   7287: the information in that table, rather than the info in the
                   7288: manager table will be used to determine the manager's ip.
                   7289: 
                   7290: =item (Red) Unable to craete <filename>                 
                   7291: 
                   7292: lond has been asked to create new versions of an administrative
                   7293: file (by a manager).  When this is done, the new file is created
                   7294: in a temp file and then renamed into place so that there are always
                   7295: usable administrative files, even if the update fails.  This failure
                   7296: message means that the temp file could not be created.
                   7297: The update is abandoned, and the old file is available for use.
                   7298: 
                   7299: =item (Green) CopyFile from <oldname> to <newname> failed
                   7300: 
                   7301: In an update of administrative files, the copy of the existing file to a
                   7302: backup file failed.  The installation of the new file may still succeed,
                   7303: but there will not be a back up file to rever to (this should probably
                   7304: be yellow).
                   7305: 
                   7306: =item (Green) Pushfile: backed up <oldname> to <newname>
                   7307: 
                   7308: See above, the backup of the old administrative file succeeded.
                   7309: 
                   7310: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   7311: 
                   7312: The new administrative file could not be installed.  In this case,
                   7313: the old administrative file is still in use.
                   7314: 
                   7315: =item (Green) Installed new < filename>.                      
                   7316: 
                   7317: The new administrative file was successfullly installed.                                               
                   7318: 
                   7319: =item (Red) Reinitializing lond pid=<pid>                    
                   7320: 
                   7321: The lonc child process <pid> will be sent a USR2 
                   7322: signal.
                   7323: 
                   7324: =item (Red) Reinitializing self                                    
                   7325: 
                   7326: We've been asked to re-read our administrative files,and
                   7327: are doing so.
                   7328: 
                   7329: =item (Yellow) error:Invalid process identifier <ident>  
                   7330: 
                   7331: A reinit command was received, but the target part of the 
                   7332: command was not valid.  It must be either
                   7333: 'lond' or 'lonc' but was <ident>
                   7334: 
                   7335: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   7336: 
                   7337: Checking to see if lond has been handed a valid edit
                   7338: command.  It is possible the edit command is not valid
                   7339: in that case there are no log messages to indicate that.
                   7340: 
                   7341: =item Result of password change for  <username> pwchange_success
                   7342: 
                   7343: The password for <username> was
                   7344: successfully changed.
                   7345: 
                   7346: =item Unable to open <user> passwd to change password
                   7347: 
                   7348: Could not rewrite the 
                   7349: internal password file for a user
                   7350: 
                   7351: =item Result of password change for <user> : <result>
                   7352:                                                                      
                   7353: A unix password change for <user> was attempted 
                   7354: and the pipe returned <result>  
                   7355: 
                   7356: =item LWP GET: <message> for <fname> (<remoteurl>)
                   7357: 
                   7358: The lightweight process fetch for a resource failed
                   7359: with <message> the local filename that should
                   7360: have existed/been created was  <fname> the
                   7361: corresponding URI: <remoteurl>  This is emitted in several
                   7362: places.
                   7363: 
                   7364: =item Unable to move <transname> to <destname>     
                   7365: 
                   7366: From fetch_user_file_handler - the user file was replicated but could not
                   7367: be mv'd to its final location.
                   7368: 
                   7369: =item Looking for <domain> <username>              
                   7370: 
                   7371: From user_has_session_handler - This should be a Debug call instead
                   7372: it indicates lond is about to check whether the specified user has a 
                   7373: session active on the specified domain on the local host.
                   7374: 
                   7375: =item Client <ip> (<name>) hanging up: <input>     
                   7376: 
                   7377: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   7378: client systemand <input> is the full exit command sent to the server.
                   7379: 
                   7380: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
                   7381:                                                  
                   7382: A lond child terminated.  NOte that this termination can also occur when the
                   7383: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   7384: <hostname> the host lond is working for, and <message> the reason the child died
                   7385: to the best of our ability to get it (I would guess that any numeric value
                   7386: represents and errno value).  This is immediately followed by
                   7387: 
                   7388: =item  Famous last words: Catching exception - <log> 
                   7389: 
                   7390: Where log is some recent information about the state of the child.
                   7391: 
                   7392: =item Red CRITICAL: TIME OUT <pid>                     
                   7393: 
                   7394: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   7395: doing an HTTP::GET.
                   7396: 
                   7397: =item child <pid> died                              
                   7398: 
                   7399: The reaper caught a SIGCHILD for the lond child process <pid>
                   7400: This should be modified to also display the IP of the dying child
                   7401: $children{$pid}
                   7402: 
                   7403: =item Unknown child 0 died                           
                   7404: A child died but the wait for it returned a pid of zero which really should not
                   7405: ever happen. 
                   7406: 
                   7407: =item Child <which> - <pid> looks like we missed it's death 
                   7408: 
                   7409: When a sigchild is received, the reaper process checks all children to see if they are
                   7410: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   7411: that a signal hearalds the death of more than one child.  If so this message indicates
                   7412: which other one died. <which> is the ip of a dead child
                   7413: 
                   7414: =item Free socket: <shutdownretval>                
                   7415: 
                   7416: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   7417: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   7418: to return anything. This is followed by: 
                   7419: 
                   7420: =item Red CRITICAL: Shutting down                       
                   7421: 
                   7422: Just prior to exit.
                   7423: 
                   7424: =item Free socket: <shutdownretval>                 
                   7425: 
                   7426: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   7427: This is followed by:
                   7428: 
                   7429: =item (Red) CRITICAL: Restarting                         
                   7430: 
                   7431: lond is about to exec itself to restart.
                   7432: 
                   7433: =item (Blue) Updating connections                        
                   7434: 
                   7435: (In response to a USR2).  All the children (except the one for localhost)
                   7436: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   7437: 
                   7438: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   7439: 
                   7440: Due to USR2 as above.
                   7441: 
                   7442: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   7443: 
                   7444: In response to USR2 as above, the child indicated is not being restarted because
                   7445: it's assumed that we'll always need a child for the localhost.
                   7446: 
                   7447: 
                   7448: =item Going to check on the children                
                   7449: 
                   7450: Parent is about to check on the health of the child processes.
                   7451: Note that this is in response to a USR1 sent to the parent lond.
                   7452: there may be one or more of the next two messages:
                   7453: 
                   7454: =item <pid> is dead                                 
                   7455: 
                   7456: A child that we have in our child hash as alive has evidently died.
                   7457: 
                   7458: =item  Child <pid> did not respond                   
                   7459: 
                   7460: In the health check the child <pid> did not update/produce a pid_.txt
                   7461: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   7462: assumed to be hung in some un-fixable way.
                   7463: 
                   7464: =item Finished checking children                   
                   7465:  
                   7466: Master processs's USR1 processing is cojmplete.
                   7467: 
                   7468: =item (Red) CRITICAL: ------- Starting ------            
                   7469: 
                   7470: (There are more '-'s on either side).  Lond has forked itself off to 
                   7471: form a new session and is about to start actual initialization.
                   7472: 
                   7473: =item (Green) Attempting to start child (<client>)       
                   7474: 
                   7475: Started a new child process for <client>.  Client is IO::Socket object
                   7476: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   7477: 
                   7478: =item Unable to determine who caller was, getpeername returned nothing
                   7479:                                                   
                   7480: In child process initialization.  either getpeername returned undef or
                   7481: a zero sized object was returned.  Processing continues, but in my opinion,
                   7482: this should be cause for the child to exit.
                   7483: 
                   7484: =item Unable to determine clientip                  
                   7485: 
                   7486: In child process initialization.  The peer address from getpeername was not defined.
                   7487: The client address is stored as "Unavailable" and processing continues.
                   7488: 
                   7489: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
                   7490:                                                   
                   7491: In child initialization.  A good connectionw as received from <ip>.
                   7492: 
                   7493: =over 2
                   7494: 
                   7495: =item <name> 
                   7496: 
                   7497: is the name of the client from hosts.tab.
                   7498: 
                   7499: =item <type> 
                   7500: 
                   7501: Is the connection type which is either 
                   7502: 
                   7503: =over 2
                   7504: 
                   7505: =item manager 
                   7506: 
                   7507: The connection is from a manager node, not in hosts.tab
                   7508: 
                   7509: =item client  
                   7510: 
                   7511: the connection is from a non-manager in the hosts.tab
                   7512: 
                   7513: =item both
                   7514: 
                   7515: The connection is from a manager in the hosts.tab.
                   7516: 
                   7517: =back
                   7518: 
                   7519: =back
                   7520: 
                   7521: =item (Blue) Certificates not installed -- trying insecure auth
                   7522: 
                   7523: One of the certificate file, key file or
                   7524: certificate authority file could not be found for a client attempting
                   7525: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   7526: (this would be a system with an up to date lond that has not gotten a 
                   7527: certificate from us).
                   7528: 
                   7529: =item (Green)  Successful local authentication            
                   7530: 
                   7531: A local connection successfully negotiated the encryption key. 
                   7532: In this case the IDEA key is in a file (that is hopefully well protected).
                   7533: 
                   7534: =item (Green) Successful ssl authentication with <client>  
                   7535: 
                   7536: The client (<client> is the peer's name in hosts.tab), has successfully
                   7537: negotiated an SSL connection with this child process.
                   7538: 
                   7539: =item (Green) Successful insecure authentication with <client>
                   7540:                                                    
                   7541: 
                   7542: The client has successfully negotiated an  insecure connection withthe child process.
                   7543: 
                   7544: =item (Yellow) Attempted insecure connection disallowed    
                   7545: 
                   7546: The client attempted and failed to successfully negotiate a successful insecure
                   7547: connection.  This can happen either because the variable londAllowInsecure is false
                   7548: or undefined, or becuse the child did not successfully echo back the challenge
                   7549: string.
                   7550: 
                   7551: 
                   7552: =back
                   7553: 
                   7554: 
                   7555: =cut

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