Annotation of loncom/lond, revision 1.489.2.13

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

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