Annotation of loncom/lond, revision 1.489.2.20

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

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