Annotation of loncom/lond, revision 1.489.2.6

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

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