Annotation of loncom/lond, revision 1.489.2.1

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

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