Annotation of loncom/lond, revision 1.489.2.16

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.16! raeburn     5: # $Id: lond,v 1.489.2.15 2014/06/09 19:47:51 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.16! raeburn    64: my $VERSION='$Revision: 1.489.2.15 $'; #' 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...
                   2448: 		#   However it's possible the client wants a dir.
                   2449: 		#   removed, in which case rmdir is more approprate:
                   2450: 		#
1.240     banghart 2451: 	        if (-f $file){
1.241     albertel 2452: 		    unlink($file);
                   2453: 		} elsif(-d $file) {
                   2454: 		    rmdir($file);
1.240     banghart 2455: 		}
1.226     foxr     2456: 		if (-e $file) {
1.253     foxr     2457: 		    #  File is still there after we deleted it ?!?
                   2458: 
1.226     foxr     2459: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2460: 		} else {
                   2461: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2462: 		}
                   2463: 	    } else {
                   2464: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2465: 	    }
                   2466: 	} else {
                   2467: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2468: 	}
                   2469:     }
                   2470:     return 1;
                   2471: }
                   2472: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2473: 
1.236     albertel 2474: #
                   2475: #   make a directory in a user's home directory userfiles subdirectory.
                   2476: # Parameters:
                   2477: #    cmd   - the Lond request keyword that got us here.
                   2478: #    tail  - the part of the command past the keyword.
                   2479: #    client- File descriptor connected with the client.
                   2480: #
                   2481: # Returns:
                   2482: #    1    - Continue processing.
                   2483: sub mkdir_user_file_handler {
                   2484:     my ($cmd, $tail, $client) = @_;
                   2485: 
                   2486:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2487:     $dir=&unescape($dir);
                   2488:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2489:     if ($ufile =~m|/\.\./|) {
                   2490: 	# any files paths with /../ in them refuse 
                   2491: 	# to deal with
                   2492: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2493:     } else {
                   2494: 	my $udir = &propath($udom,$uname);
                   2495: 	if (-e $udir) {
1.264     albertel 2496: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2497: 	    if (!&mkpath($newdir)) {
                   2498: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2499: 	    }
1.264     albertel 2500: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2501: 	} else {
                   2502: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2503: 	}
                   2504:     }
                   2505:     return 1;
                   2506: }
                   2507: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2508: 
1.237     albertel 2509: #
                   2510: #   rename a file in a user's home directory userfiles subdirectory.
                   2511: # Parameters:
                   2512: #    cmd   - the Lond request keyword that got us here.
                   2513: #    tail  - the part of the command past the keyword.
                   2514: #    client- File descriptor connected with the client.
                   2515: #
                   2516: # Returns:
                   2517: #    1    - Continue processing.
                   2518: sub rename_user_file_handler {
                   2519:     my ($cmd, $tail, $client) = @_;
                   2520: 
                   2521:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2522:     $old=&unescape($old);
                   2523:     $new=&unescape($new);
                   2524:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2525: 	# any files paths with /../ in them refuse to deal with
                   2526: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2527:     } else {
                   2528: 	my $udir = &propath($udom,$uname);
                   2529: 	if (-e $udir) {
                   2530: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2531: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2532: 	    if (-e $newfile) {
                   2533: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2534: 	    } elsif (! -e $oldfile) {
                   2535: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2536: 	    } else {
                   2537: 		if (!rename($oldfile,$newfile)) {
                   2538: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2539: 		} else {
                   2540: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2541: 		}
                   2542: 	    }
                   2543: 	} else {
                   2544: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2545: 	}
                   2546:     }
                   2547:     return 1;
                   2548: }
                   2549: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2550: 
1.227     foxr     2551: #
1.382     albertel 2552: #  Checks if the specified user has an active session on the server
                   2553: #  return ok if so, not_found if not
                   2554: #
                   2555: # Parameters:
                   2556: #   cmd      - The request keyword that dispatched to tus.
                   2557: #   tail     - The tail of the request (colon separated parameters).
                   2558: #   client   - Filehandle open on the client.
                   2559: # Return:
                   2560: #    1.
                   2561: sub user_has_session_handler {
                   2562:     my ($cmd, $tail, $client) = @_;
                   2563: 
                   2564:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   2565:     
                   2566:     opendir(DIR,$perlvar{'lonIDsDir'});
                   2567:     my $filename;
                   2568:     while ($filename=readdir(DIR)) {
                   2569: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   2570:     }
                   2571:     if ($filename) {
                   2572: 	&Reply($client, "ok\n", "$cmd:$tail");
                   2573:     } else {
                   2574: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   2575:     }
                   2576:     return 1;
                   2577: 
                   2578: }
                   2579: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   2580: 
                   2581: #
1.263     albertel 2582: #  Authenticate access to a user file by checking that the token the user's 
                   2583: #  passed also exists in their session file
1.227     foxr     2584: #
                   2585: # Parameters:
                   2586: #   cmd      - The request keyword that dispatched to tus.
                   2587: #   tail     - The tail of the request (colon separated parameters).
                   2588: #   client   - Filehandle open on the client.
                   2589: # Return:
                   2590: #    1.
                   2591: sub token_auth_user_file_handler {
                   2592:     my ($cmd, $tail, $client) = @_;
                   2593: 
                   2594:     my ($fname, $session) = split(/:/, $tail);
                   2595:     
                   2596:     chomp($session);
1.393     raeburn  2597:     my $reply="non_auth";
1.343     albertel 2598:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   2599:     if (open(ENVIN,"$file")) {
1.332     albertel 2600: 	flock(ENVIN,LOCK_SH);
1.343     albertel 2601: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   2602: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  2603: 	    $reply="ok";
1.343     albertel 2604: 	} else {
                   2605: 	    foreach my $envname (keys(%disk_env)) {
                   2606: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  2607: 		    $reply="ok";
1.343     albertel 2608: 		    last;
                   2609: 		}
                   2610: 	    }
1.227     foxr     2611: 	}
1.343     albertel 2612: 	untie(%disk_env);
1.227     foxr     2613: 	close(ENVIN);
1.387     albertel 2614: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     2615:     } else {
                   2616: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2617:     }
                   2618:     return 1;
                   2619: 
                   2620: }
                   2621: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2622: 
                   2623: #
                   2624: #   Unsubscribe from a resource.
                   2625: #
                   2626: # Parameters:
                   2627: #    $cmd      - The command that got us here.
                   2628: #    $tail     - Tail of the command (remaining parameters).
                   2629: #    $client   - File descriptor connected to client.
                   2630: # Returns
                   2631: #     0        - Requested to exit, caller should shut down.
                   2632: #     1        - Continue processing.
                   2633: #
                   2634: sub unsubscribe_handler {
                   2635:     my ($cmd, $tail, $client) = @_;
                   2636: 
                   2637:     my $userinput= "$cmd:$tail";
                   2638:     
                   2639:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   2640: 
                   2641:     &Debug("Unsubscribing $fname");
                   2642:     if (-e $fname) {
                   2643: 	&Debug("Exists");
                   2644: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   2645:     } else {
                   2646: 	&Failure($client, "not_found\n", $userinput);
                   2647:     }
                   2648:     return 1;
                   2649: }
                   2650: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 2651: 
1.230     foxr     2652: #   Subscribe to a resource
                   2653: #
                   2654: # Parameters:
                   2655: #    $cmd      - The command that got us here.
                   2656: #    $tail     - Tail of the command (remaining parameters).
                   2657: #    $client   - File descriptor connected to client.
                   2658: # Returns
                   2659: #     0        - Requested to exit, caller should shut down.
                   2660: #     1        - Continue processing.
                   2661: #
                   2662: sub subscribe_handler {
                   2663:     my ($cmd, $tail, $client)= @_;
                   2664: 
                   2665:     my $userinput  = "$cmd:$tail";
                   2666: 
                   2667:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   2668: 
                   2669:     return 1;
                   2670: }
                   2671: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   2672: 
                   2673: #
1.379     albertel 2674: #   Determine the latest version of a resource (it looks for the highest
                   2675: #   past version and then returns that +1)
1.230     foxr     2676: #
                   2677: # Parameters:
                   2678: #    $cmd      - The command that got us here.
                   2679: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 2680: #                 (Should consist of an absolute path to a file)
1.230     foxr     2681: #    $client   - File descriptor connected to client.
                   2682: # Returns
                   2683: #     0        - Requested to exit, caller should shut down.
                   2684: #     1        - Continue processing.
                   2685: #
                   2686: sub current_version_handler {
                   2687:     my ($cmd, $tail, $client) = @_;
                   2688: 
                   2689:     my $userinput= "$cmd:$tail";
                   2690:    
                   2691:     my $fname   = $tail;
                   2692:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   2693:     return 1;
                   2694: 
                   2695: }
                   2696: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   2697: 
                   2698: #  Make an entry in a user's activity log.
                   2699: #
                   2700: # Parameters:
                   2701: #    $cmd      - The command that got us here.
                   2702: #    $tail     - Tail of the command (remaining parameters).
                   2703: #    $client   - File descriptor connected to client.
                   2704: # Returns
                   2705: #     0        - Requested to exit, caller should shut down.
                   2706: #     1        - Continue processing.
                   2707: #
                   2708: sub activity_log_handler {
                   2709:     my ($cmd, $tail, $client) = @_;
                   2710: 
                   2711: 
                   2712:     my $userinput= "$cmd:$tail";
                   2713: 
                   2714:     my ($udom,$uname,$what)=split(/:/,$tail);
                   2715:     chomp($what);
                   2716:     my $proname=&propath($udom,$uname);
                   2717:     my $now=time;
                   2718:     my $hfh;
                   2719:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   2720: 	print $hfh "$now:$clientname:$what\n";
                   2721: 	&Reply( $client, "ok\n", $userinput); 
                   2722:     } else {
                   2723: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   2724: 		 ."while attempting log\n", 
                   2725: 		 $userinput);
                   2726:     }
                   2727: 
                   2728:     return 1;
                   2729: }
1.263     albertel 2730: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     2731: 
                   2732: #
                   2733: #   Put a namespace entry in a user profile hash.
                   2734: #   My druthers would be for this to be an encrypted interaction too.
                   2735: #   anything that might be an inadvertent covert channel about either
                   2736: #   user authentication or user personal information....
                   2737: #
                   2738: # Parameters:
                   2739: #    $cmd      - The command that got us here.
                   2740: #    $tail     - Tail of the command (remaining parameters).
                   2741: #    $client   - File descriptor connected to client.
                   2742: # Returns
                   2743: #     0        - Requested to exit, caller should shut down.
                   2744: #     1        - Continue processing.
                   2745: #
                   2746: sub put_user_profile_entry {
                   2747:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     2748: 
1.230     foxr     2749:     my $userinput = "$cmd:$tail";
                   2750:     
1.242     raeburn  2751:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     2752:     if ($namespace ne 'roles') {
                   2753: 	chomp($what);
                   2754: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2755: 				  &GDBM_WRCREAT(),"P",$what);
                   2756: 	if($hashref) {
                   2757: 	    my @pairs=split(/\&/,$what);
                   2758: 	    foreach my $pair (@pairs) {
                   2759: 		my ($key,$value)=split(/=/,$pair);
                   2760: 		$hashref->{$key}=$value;
                   2761: 	    }
1.311     albertel 2762: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     2763: 		&Reply( $client, "ok\n", $userinput);
                   2764: 	    } else {
                   2765: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2766: 			"while attempting put\n", 
                   2767: 			$userinput);
                   2768: 	    }
                   2769: 	} else {
1.316     albertel 2770: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     2771: 		     "while attempting put\n", $userinput);
                   2772: 	}
                   2773:     } else {
                   2774:         &Failure( $client, "refused\n", $userinput);
                   2775:     }
                   2776:     
                   2777:     return 1;
                   2778: }
                   2779: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   2780: 
1.283     albertel 2781: #   Put a piece of new data in hash, returns error if entry already exists
                   2782: # Parameters:
                   2783: #    $cmd      - The command that got us here.
                   2784: #    $tail     - Tail of the command (remaining parameters).
                   2785: #    $client   - File descriptor connected to client.
                   2786: # Returns
                   2787: #     0        - Requested to exit, caller should shut down.
                   2788: #     1        - Continue processing.
                   2789: #
                   2790: sub newput_user_profile_entry {
                   2791:     my ($cmd, $tail, $client)  = @_;
                   2792: 
                   2793:     my $userinput = "$cmd:$tail";
                   2794: 
                   2795:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   2796:     if ($namespace eq 'roles') {
                   2797:         &Failure( $client, "refused\n", $userinput);
                   2798: 	return 1;
                   2799:     }
                   2800: 
                   2801:     chomp($what);
                   2802: 
                   2803:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2804: 				 &GDBM_WRCREAT(),"N",$what);
                   2805:     if(!$hashref) {
1.316     albertel 2806: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 2807: 		  "while attempting put\n", $userinput);
                   2808: 	return 1;
                   2809:     }
                   2810: 
                   2811:     my @pairs=split(/\&/,$what);
                   2812:     foreach my $pair (@pairs) {
                   2813: 	my ($key,$value)=split(/=/,$pair);
                   2814: 	if (exists($hashref->{$key})) {
                   2815: 	    &Failure($client, "key_exists: ".$key."\n",$userinput);
                   2816: 	    return 1;
                   2817: 	}
                   2818:     }
                   2819: 
                   2820:     foreach my $pair (@pairs) {
                   2821: 	my ($key,$value)=split(/=/,$pair);
                   2822: 	$hashref->{$key}=$value;
                   2823:     }
                   2824: 
1.311     albertel 2825:     if (&untie_user_hash($hashref)) {
1.283     albertel 2826: 	&Reply( $client, "ok\n", $userinput);
                   2827:     } else {
                   2828: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2829: 		 "while attempting put\n", 
                   2830: 		 $userinput);
                   2831:     }
                   2832:     return 1;
                   2833: }
                   2834: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   2835: 
1.230     foxr     2836: # 
                   2837: #   Increment a profile entry in the user history file.
                   2838: #   The history contains keyword value pairs.  In this case,
                   2839: #   The value itself is a pair of numbers.  The first, the current value
                   2840: #   the second an increment that this function applies to the current
                   2841: #   value.
                   2842: #
                   2843: # Parameters:
                   2844: #    $cmd      - The command that got us here.
                   2845: #    $tail     - Tail of the command (remaining parameters).
                   2846: #    $client   - File descriptor connected to client.
                   2847: # Returns
                   2848: #     0        - Requested to exit, caller should shut down.
                   2849: #     1        - Continue processing.
                   2850: #
                   2851: sub increment_user_value_handler {
                   2852:     my ($cmd, $tail, $client) = @_;
                   2853:     
                   2854:     my $userinput   = "$cmd:$tail";
                   2855:     
                   2856:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   2857:     if ($namespace ne 'roles') {
                   2858:         chomp($what);
                   2859: 	my $hashref = &tie_user_hash($udom, $uname,
                   2860: 				     $namespace, &GDBM_WRCREAT(),
                   2861: 				     "P",$what);
                   2862: 	if ($hashref) {
                   2863: 	    my @pairs=split(/\&/,$what);
                   2864: 	    foreach my $pair (@pairs) {
                   2865: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  2866:                 $value = &unescape($value);
1.230     foxr     2867: 		# We could check that we have a number...
                   2868: 		if (! defined($value) || $value eq '') {
                   2869: 		    $value = 1;
                   2870: 		}
                   2871: 		$hashref->{$key}+=$value;
1.284     raeburn  2872:                 if ($namespace eq 'nohist_resourcetracker') {
                   2873:                     if ($hashref->{$key} < 0) {
                   2874:                         $hashref->{$key} = 0;
                   2875:                     }
                   2876:                 }
1.230     foxr     2877: 	    }
1.311     albertel 2878: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     2879: 		&Reply( $client, "ok\n", $userinput);
                   2880: 	    } else {
                   2881: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2882: 			 "while attempting inc\n", $userinput);
                   2883: 	    }
                   2884: 	} else {
                   2885: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2886: 		     "while attempting inc\n", $userinput);
                   2887: 	}
                   2888:     } else {
                   2889: 	&Failure($client, "refused\n", $userinput);
                   2890:     }
                   2891:     
                   2892:     return 1;
                   2893: }
                   2894: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   2895: 
                   2896: #
                   2897: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   2898: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   2899: #   for a person grants the permissions packaged with that role
                   2900: #   to that user when the role is selected.
                   2901: #
                   2902: # Parameters:
                   2903: #    $cmd       - The command string (rolesput).
                   2904: #    $tail      - The remainder of the request line.  For rolesput this
                   2905: #                 consists of a colon separated list that contains:
                   2906: #                 The domain and user that is granting the role (logged).
                   2907: #                 The domain and user that is getting the role.
                   2908: #                 The roles being granted as a set of & separated pairs.
                   2909: #                 each pair a key value pair.
                   2910: #    $client    - File descriptor connected to the client.
                   2911: # Returns:
                   2912: #     0         - If the daemon should exit
                   2913: #     1         - To continue processing.
                   2914: #
                   2915: #
                   2916: sub roles_put_handler {
                   2917:     my ($cmd, $tail, $client) = @_;
                   2918: 
                   2919:     my $userinput  = "$cmd:$tail";
                   2920: 
                   2921:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   2922:     
                   2923: 
                   2924:     my $namespace='roles';
                   2925:     chomp($what);
                   2926:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2927: 				 &GDBM_WRCREAT(), "P",
                   2928: 				 "$exedom:$exeuser:$what");
                   2929:     #
                   2930:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   2931:     #  handle is open for the minimal amount of time.  Since the flush
                   2932:     #  is done on close this improves the chances the log will be an un-
                   2933:     #  corrupted ordered thing.
                   2934:     if ($hashref) {
1.261     foxr     2935: 	my $pass_entry = &get_auth_type($udom, $uname);
                   2936: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   2937: 	$auth_type = $auth_type.":";
1.230     foxr     2938: 	my @pairs=split(/\&/,$what);
                   2939: 	foreach my $pair (@pairs) {
                   2940: 	    my ($key,$value)=split(/=/,$pair);
                   2941: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     2942: 			       $auth_type);
1.230     foxr     2943: 	    $hashref->{$key}=$value;
                   2944: 	}
1.311     albertel 2945: 	if (&untie_user_hash($hashref)) {
1.230     foxr     2946: 	    &Reply($client, "ok\n", $userinput);
                   2947: 	} else {
                   2948: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2949: 		     "while attempting rolesput\n", $userinput);
                   2950: 	}
                   2951:     } else {
                   2952: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2953: 		 "while attempting rolesput\n", $userinput);
                   2954:     }
                   2955:     return 1;
                   2956: }
                   2957: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   2958: 
                   2959: #
1.231     foxr     2960: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   2961: #  a permissions package associated with the role from the user's profile.
                   2962: #
                   2963: # Parameters:
                   2964: #     $cmd                 - The command (rolesdel)
                   2965: #     $tail                - The remainder of the request line. This consists
                   2966: #                             of:
                   2967: #                             The domain and user requesting the change (logged)
                   2968: #                             The domain and user being changed.
                   2969: #                             The roles being revoked.  These are shipped to us
                   2970: #                             as a bunch of & separated role name keywords.
                   2971: #     $client              - The file handle open on the client.
                   2972: # Returns:
                   2973: #     1                    - Continue processing
                   2974: #     0                    - Exit.
                   2975: #
                   2976: sub roles_delete_handler {
                   2977:     my ($cmd, $tail, $client)  = @_;
                   2978: 
                   2979:     my $userinput    = "$cmd:$tail";
                   2980:    
                   2981:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   2982:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   2983: 	   "what = ".$what);
                   2984:     my $namespace='roles';
                   2985:     chomp($what);
                   2986:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2987: 				 &GDBM_WRCREAT(), "D",
                   2988: 				 "$exedom:$exeuser:$what");
                   2989:     
                   2990:     if ($hashref) {
                   2991: 	my @rolekeys=split(/\&/,$what);
                   2992: 	
                   2993: 	foreach my $key (@rolekeys) {
                   2994: 	    delete $hashref->{$key};
                   2995: 	}
1.315     albertel 2996: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2997: 	    &Reply($client, "ok\n", $userinput);
                   2998: 	} else {
                   2999: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3000: 		     "while attempting rolesdel\n", $userinput);
                   3001: 	}
                   3002:     } else {
                   3003:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3004: 		 "while attempting rolesdel\n", $userinput);
                   3005:     }
                   3006:     
                   3007:     return 1;
                   3008: }
                   3009: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3010: 
                   3011: # Unencrypted get from a user's profile database.  See 
                   3012: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3013: # This function retrieves a keyed item from a specific named database in the
                   3014: # user's directory.
                   3015: #
                   3016: # Parameters:
                   3017: #   $cmd             - Command request keyword (get).
                   3018: #   $tail            - Tail of the command.  This is a colon separated list
                   3019: #                      consisting of the domain and username that uniquely
                   3020: #                      identifies the profile,
                   3021: #                      The 'namespace' which selects the gdbm file to 
                   3022: #                      do the lookup in, 
                   3023: #                      & separated list of keys to lookup.  Note that
                   3024: #                      the values are returned as an & separated list too.
                   3025: #   $client          - File descriptor open on the client.
                   3026: # Returns:
                   3027: #   1       - Continue processing.
                   3028: #   0       - Exit.
                   3029: #
                   3030: sub get_profile_entry {
                   3031:     my ($cmd, $tail, $client) = @_;
                   3032: 
                   3033:     my $userinput= "$cmd:$tail";
                   3034:    
                   3035:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3036:     chomp($what);
1.255     foxr     3037: 
1.390     raeburn  3038: 
1.255     foxr     3039:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3040:     my ($first) = split(/:/,$replystring);
                   3041:     if($first ne "error") {
1.387     albertel 3042: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3043:     } else {
1.255     foxr     3044: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3045:     }
                   3046:     return 1;
1.255     foxr     3047: 
                   3048: 
1.231     foxr     3049: }
                   3050: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3051: 
                   3052: #
                   3053: #  Process the encrypted get request.  Note that the request is sent
                   3054: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3055: #  information about the sensitive keys is given to the snooper.  Just not
                   3056: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3057: #  know these I'd snoop for the egets. Get the profile item names from them
                   3058: #  and then issue a get for them since there's no enforcement of the
                   3059: #  requirement of an encrypted get for particular profile items.  If I
                   3060: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3061: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3062: #  that would prevent any covert channel snooping.
                   3063: #
                   3064: #  Parameters:
                   3065: #     $cmd               - Command keyword of request (eget).
                   3066: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
                   3067: #     $client            - File open on the client.
                   3068: #  Returns:
                   3069: #     1      - Continue processing
                   3070: #     0      - server should exit.
                   3071: sub get_profile_entry_encrypted {
                   3072:     my ($cmd, $tail, $client) = @_;
                   3073: 
                   3074:     my $userinput = "$cmd:$tail";
                   3075:    
1.339     albertel 3076:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3077:     chomp($what);
1.255     foxr     3078:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3079:     my ($first) = split(/:/, $qresult);
                   3080:     if($first ne "error") {
                   3081: 	
                   3082: 	if ($cipher) {
                   3083: 	    my $cmdlength=length($qresult);
                   3084: 	    $qresult.="         ";
                   3085: 	    my $encqresult='';
                   3086: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3087: 		$encqresult.= unpack("H16", 
                   3088: 				     $cipher->encrypt(substr($qresult,
                   3089: 							     $encidx,
                   3090: 							     8)));
                   3091: 	    }
                   3092: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3093: 	} else {
1.231     foxr     3094: 		&Failure( $client, "error:no_key\n", $userinput);
                   3095: 	    }
                   3096:     } else {
1.255     foxr     3097: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3098: 
1.231     foxr     3099:     }
                   3100:     
                   3101:     return 1;
                   3102: }
1.255     foxr     3103: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3104: 
1.231     foxr     3105: #
                   3106: #   Deletes a key in a user profile database.
                   3107: #   
                   3108: #   Parameters:
                   3109: #       $cmd                  - Command keyword (del).
                   3110: #       $tail                 - Command tail.  IN this case a colon
                   3111: #                               separated list containing:
                   3112: #                               The domain and user that identifies uniquely
                   3113: #                               the identity of the user.
                   3114: #                               The profile namespace (name of the profile
                   3115: #                               database file).
                   3116: #                               & separated list of keywords to delete.
                   3117: #       $client              - File open on client socket.
                   3118: # Returns:
                   3119: #     1   - Continue processing
                   3120: #     0   - Exit server.
                   3121: #
                   3122: #
                   3123: sub delete_profile_entry {
                   3124:     my ($cmd, $tail, $client) = @_;
                   3125: 
                   3126:     my $userinput = "cmd:$tail";
                   3127: 
                   3128:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3129:     chomp($what);
                   3130:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3131: 				 &GDBM_WRCREAT(),
                   3132: 				 "D",$what);
                   3133:     if ($hashref) {
                   3134:         my @keys=split(/\&/,$what);
                   3135: 	foreach my $key (@keys) {
                   3136: 	    delete($hashref->{$key});
                   3137: 	}
1.315     albertel 3138: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3139: 	    &Reply($client, "ok\n", $userinput);
                   3140: 	} else {
                   3141: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3142: 		    "while attempting del\n", $userinput);
                   3143: 	}
                   3144:     } else {
                   3145: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3146: 		 "while attempting del\n", $userinput);
                   3147:     }
                   3148:     return 1;
                   3149: }
                   3150: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3151: 
1.231     foxr     3152: #
                   3153: #  List the set of keys that are defined in a profile database file.
                   3154: #  A successful reply from this will contain an & separated list of
                   3155: #  the keys. 
                   3156: # Parameters:
                   3157: #     $cmd              - Command request (keys).
                   3158: #     $tail             - Remainder of the request, a colon separated
                   3159: #                         list containing domain/user that identifies the
                   3160: #                         user being queried, and the database namespace
                   3161: #                         (database filename essentially).
                   3162: #     $client           - File open on the client.
                   3163: #  Returns:
                   3164: #    1    - Continue processing.
                   3165: #    0    - Exit the server.
                   3166: #
                   3167: sub get_profile_keys {
                   3168:     my ($cmd, $tail, $client) = @_;
                   3169: 
                   3170:     my $userinput = "$cmd:$tail";
                   3171: 
                   3172:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3173:     my $qresult='';
                   3174:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3175: 				  &GDBM_READER());
                   3176:     if ($hashref) {
                   3177: 	foreach my $key (keys %$hashref) {
                   3178: 	    $qresult.="$key&";
                   3179: 	}
1.315     albertel 3180: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3181: 	    $qresult=~s/\&$//;
1.387     albertel 3182: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3183: 	} else {
                   3184: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3185: 		    "while attempting keys\n", $userinput);
                   3186: 	}
                   3187:     } else {
                   3188: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3189: 		 "while attempting keys\n", $userinput);
                   3190:     }
                   3191:    
                   3192:     return 1;
                   3193: }
                   3194: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3195: 
                   3196: #
                   3197: #   Dump the contents of a user profile database.
                   3198: #   Note that this constitutes a very large covert channel too since
                   3199: #   the dump will return sensitive information that is not encrypted.
                   3200: #   The naive security assumption is that the session negotiation ensures
                   3201: #   our client is trusted and I don't believe that's assured at present.
                   3202: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3203: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3204: # 
                   3205: #  Parameters:
                   3206: #     $cmd           - The command request keyword (currentdump).
                   3207: #     $tail          - Remainder of the request, consisting of a colon
                   3208: #                      separated list that has the domain/username and
                   3209: #                      the namespace to dump (database file).
                   3210: #     $client        - file open on the remote client.
                   3211: # Returns:
                   3212: #     1    - Continue processing.
                   3213: #     0    - Exit the server.
                   3214: #
                   3215: sub dump_profile_database {
                   3216:     my ($cmd, $tail, $client) = @_;
                   3217: 
                   3218:     my $userinput = "$cmd:$tail";
                   3219:    
                   3220:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3221:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3222: 				 &GDBM_READER());
                   3223:     if ($hashref) {
                   3224: 	# Structure of %data:
                   3225: 	# $data{$symb}->{$parameter}=$value;
                   3226: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3227: 	# since $parameter will be unescaped, we do not
                   3228:  	# have to worry about silly parameter names...
                   3229: 	
                   3230:         my $qresult='';
                   3231: 	my %data = ();                     # A hash of anonymous hashes..
                   3232: 	while (my ($key,$value) = each(%$hashref)) {
                   3233: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3234: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3235: 	    next if (exists($data{$symb}) && 
                   3236: 		     exists($data{$symb}->{$param}) &&
                   3237: 		     $data{$symb}->{'v.'.$param} > $v);
                   3238: 	    $data{$symb}->{$param}=$value;
                   3239: 	    $data{$symb}->{'v.'.$param}=$v;
                   3240: 	}
1.311     albertel 3241: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3242: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3243: 		while(my ($param,$value) = each (%$param_hash)){
                   3244: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3245: 		    #
                   3246: 		    #   Just dump the symb=value pairs separated by &
                   3247: 		    #
                   3248: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3249: 		}
                   3250: 	    }
                   3251: 	    chop($qresult);
1.387     albertel 3252: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3253: 	} else {
                   3254: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3255: 		     "while attempting currentdump\n", $userinput);
                   3256: 	}
                   3257:     } else {
                   3258: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3259: 		"while attempting currentdump\n", $userinput);
                   3260:     }
                   3261: 
                   3262:     return 1;
                   3263: }
                   3264: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3265: 
                   3266: #
                   3267: #   Dump a profile database with an optional regular expression
                   3268: #   to match against the keys.  In this dump, no effort is made
                   3269: #   to separate symb from version information. Presumably the
                   3270: #   databases that are dumped by this command are of a different
                   3271: #   structure.  Need to look at this and improve the documentation of
                   3272: #   both this and the currentdump handler.
                   3273: # Parameters:
                   3274: #    $cmd                     - The command keyword.
                   3275: #    $tail                    - All of the characters after the $cmd:
                   3276: #                               These are expected to be a colon
                   3277: #                               separated list containing:
                   3278: #                               domain/user - identifying the user.
                   3279: #                               namespace   - identifying the database.
                   3280: #                               regexp      - optional regular expression
                   3281: #                                             that is matched against
                   3282: #                                             database keywords to do
                   3283: #                                             selective dumps.
1.488     raeburn  3284: #                               range       - optional range of entries
                   3285: #                                             e.g., 10-20 would return the
                   3286: #                                             10th to 19th items, etc.  
1.231     foxr     3287: #   $client                   - Channel open on the client.
                   3288: # Returns:
                   3289: #    1    - Continue processing.
                   3290: # Side effects:
                   3291: #    response is written to $client.
                   3292: #
                   3293: sub dump_with_regexp {
                   3294:     my ($cmd, $tail, $client) = @_;
                   3295: 
1.489.2.4  raeburn  3296:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.231     foxr     3297: 
1.489.2.4  raeburn  3298:     if ($res =~ /^error:/) {
                   3299:         &Failure($client, \$res, "$cmd:$tail");
1.231     foxr     3300:     } else {
1.489.2.4  raeburn  3301:         &Reply($client, \$res, "$cmd:$tail");
1.231     foxr     3302:     }
                   3303: 
                   3304:     return 1;
                   3305: }
                   3306: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3307: 
                   3308: #  Store a set of key=value pairs associated with a versioned name.
                   3309: #
                   3310: #  Parameters:
                   3311: #    $cmd                - Request command keyword.
                   3312: #    $tail               - Tail of the request.  This is a colon
                   3313: #                          separated list containing:
                   3314: #                          domain/user - User and authentication domain.
                   3315: #                          namespace   - Name of the database being modified
                   3316: #                          rid         - Resource keyword to modify.
                   3317: #                          what        - new value associated with rid.
                   3318: #
                   3319: #    $client             - Socket open on the client.
                   3320: #
                   3321: #
                   3322: #  Returns:
                   3323: #      1 (keep on processing).
                   3324: #  Side-Effects:
                   3325: #    Writes to the client
                   3326: sub store_handler {
                   3327:     my ($cmd, $tail, $client) = @_;
                   3328:  
                   3329:     my $userinput = "$cmd:$tail";
                   3330: 
                   3331:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
                   3332:     if ($namespace ne 'roles') {
                   3333: 
                   3334: 	chomp($what);
                   3335: 	my @pairs=split(/\&/,$what);
                   3336: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3337: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3338: 				       "$rid:$what");
                   3339: 	if ($hashref) {
                   3340: 	    my $now = time;
                   3341: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
                   3342: 	    my $key;
                   3343: 	    $hashref->{"version:$rid"}++;
                   3344: 	    my $version=$hashref->{"version:$rid"};
                   3345: 	    my $allkeys=''; 
                   3346: 	    foreach my $pair (@pairs) {
                   3347: 		my ($key,$value)=split(/=/,$pair);
                   3348: 		$allkeys.=$key.':';
                   3349: 		$hashref->{"$version:$rid:$key"}=$value;
                   3350: 	    }
                   3351: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3352: 	    $allkeys.='timestamp';
                   3353: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3354: 	    if (&untie_user_hash($hashref)) {
1.231     foxr     3355: 		&Reply($client, "ok\n", $userinput);
                   3356: 	    } else {
                   3357: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3358: 			"while attempting store\n", $userinput);
                   3359: 	    }
                   3360: 	} else {
                   3361: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3362: 		     "while attempting store\n", $userinput);
                   3363: 	}
                   3364:     } else {
                   3365: 	&Failure($client, "refused\n", $userinput);
                   3366:     }
                   3367: 
                   3368:     return 1;
                   3369: }
                   3370: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3371: 
1.323     albertel 3372: #  Modify a set of key=value pairs associated with a versioned name.
                   3373: #
                   3374: #  Parameters:
                   3375: #    $cmd                - Request command keyword.
                   3376: #    $tail               - Tail of the request.  This is a colon
                   3377: #                          separated list containing:
                   3378: #                          domain/user - User and authentication domain.
                   3379: #                          namespace   - Name of the database being modified
                   3380: #                          rid         - Resource keyword to modify.
                   3381: #                          v           - Version item to modify
                   3382: #                          what        - new value associated with rid.
                   3383: #
                   3384: #    $client             - Socket open on the client.
                   3385: #
                   3386: #
                   3387: #  Returns:
                   3388: #      1 (keep on processing).
                   3389: #  Side-Effects:
                   3390: #    Writes to the client
                   3391: sub putstore_handler {
                   3392:     my ($cmd, $tail, $client) = @_;
                   3393:  
                   3394:     my $userinput = "$cmd:$tail";
                   3395: 
                   3396:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3397:     if ($namespace ne 'roles') {
                   3398: 
                   3399: 	chomp($what);
                   3400: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3401: 				       &GDBM_WRCREAT(), "M",
                   3402: 				       "$rid:$v:$what");
                   3403: 	if ($hashref) {
                   3404: 	    my $now = time;
                   3405: 	    my %data = &hash_extract($what);
                   3406: 	    my @allkeys;
                   3407: 	    while (my($key,$value) = each(%data)) {
                   3408: 		push(@allkeys,$key);
                   3409: 		$hashref->{"$v:$rid:$key"} = $value;
                   3410: 	    }
                   3411: 	    my $allkeys = join(':',@allkeys);
                   3412: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3413: 
                   3414: 	    if (&untie_user_hash($hashref)) {
                   3415: 		&Reply($client, "ok\n", $userinput);
                   3416: 	    } else {
                   3417: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3418: 			"while attempting store\n", $userinput);
                   3419: 	    }
                   3420: 	} else {
                   3421: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3422: 		     "while attempting store\n", $userinput);
                   3423: 	}
                   3424:     } else {
                   3425: 	&Failure($client, "refused\n", $userinput);
                   3426:     }
                   3427: 
                   3428:     return 1;
                   3429: }
                   3430: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3431: 
                   3432: sub hash_extract {
                   3433:     my ($str)=@_;
                   3434:     my %hash;
                   3435:     foreach my $pair (split(/\&/,$str)) {
                   3436: 	my ($key,$value)=split(/=/,$pair);
                   3437: 	$hash{$key}=$value;
                   3438:     }
                   3439:     return (%hash);
                   3440: }
                   3441: sub hash_to_str {
                   3442:     my ($hash_ref)=@_;
                   3443:     my $str;
                   3444:     foreach my $key (keys(%$hash_ref)) {
                   3445: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3446:     }
                   3447:     $str=~s/\&$//;
                   3448:     return $str;
                   3449: }
                   3450: 
1.231     foxr     3451: #
                   3452: #  Dump out all versions of a resource that has key=value pairs associated
                   3453: # with it for each version.  These resources are built up via the store
                   3454: # command.
                   3455: #
                   3456: #  Parameters:
                   3457: #     $cmd               - Command keyword.
                   3458: #     $tail              - Remainder of the request which consists of:
                   3459: #                          domain/user   - User and auth. domain.
                   3460: #                          namespace     - name of resource database.
                   3461: #                          rid           - Resource id.
                   3462: #    $client             - socket open on the client.
                   3463: #
                   3464: # Returns:
                   3465: #      1  indicating the caller should not yet exit.
                   3466: # Side-effects:
                   3467: #   Writes a reply to the client.
                   3468: #   The reply is a string of the following shape:
                   3469: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3470: #    Where the 1 above represents version 1.
                   3471: #    this continues for all pairs of keys in all versions.
                   3472: #
                   3473: #
                   3474: #    
                   3475: #
                   3476: sub restore_handler {
                   3477:     my ($cmd, $tail, $client) = @_;
                   3478: 
                   3479:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 3480:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 3481:     $namespace=~s/\//\_/g;
1.350     albertel 3482:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 3483: 
1.231     foxr     3484:     chomp($rid);
                   3485:     my $qresult='';
1.309     albertel 3486:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3487:     if ($hashref) {
                   3488: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3489: 	$qresult.="version=$version&";
                   3490: 	my $scope;
                   3491: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3492: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3493: 	    my @keys=split(/:/,$vkeys);
                   3494: 	    my $key;
                   3495: 	    $qresult.="$scope:keys=$vkeys&";
                   3496: 	    foreach $key (@keys) {
1.309     albertel 3497: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3498: 	    }                                  
                   3499: 	}
1.311     albertel 3500: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3501: 	    $qresult=~s/\&$//;
1.387     albertel 3502: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     3503: 	} else {
                   3504: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3505: 		    "while attempting restore\n", $userinput);
                   3506: 	}
                   3507:     } else {
                   3508: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3509: 		"while attempting restore\n", $userinput);
                   3510:     }
                   3511:   
                   3512:     return 1;
                   3513: 
                   3514: 
                   3515: }
                   3516: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3517: 
                   3518: #
1.324     raeburn  3519: #   Add a chat message to a synchronous discussion board.
1.234     foxr     3520: #
                   3521: # Parameters:
                   3522: #    $cmd                - Request keyword.
                   3523: #    $tail               - Tail of the command. A colon separated list
                   3524: #                          containing:
                   3525: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  3526: #                          cnum    - Course containing the chat board.
                   3527: #                          newpost - Body of the posting.
                   3528: #                          group   - Optional group, if chat board is only 
                   3529: #                                    accessible in a group within the course 
1.234     foxr     3530: #   $client              - Socket open on the client.
                   3531: # Returns:
                   3532: #   1    - Indicating caller should keep on processing.
                   3533: #
                   3534: # Side-effects:
                   3535: #   writes a reply to the client.
                   3536: #
                   3537: #
                   3538: sub send_chat_handler {
                   3539:     my ($cmd, $tail, $client) = @_;
                   3540: 
                   3541:     
                   3542:     my $userinput = "$cmd:$tail";
                   3543: 
1.324     raeburn  3544:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   3545:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     3546:     &Reply($client, "ok\n", $userinput);
                   3547: 
                   3548:     return 1;
                   3549: }
                   3550: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3551: 
1.234     foxr     3552: #
1.324     raeburn  3553: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     3554: #
                   3555: #  Parameters:
                   3556: #    $cmd             - Command keyword that initiated the request.
                   3557: #    $tail            - Remainder of the request after the command
                   3558: #                       keyword.  In this case a colon separated list of
                   3559: #                       chat domain    - Which discussion board.
                   3560: #                       chat id        - Discussion thread(?)
                   3561: #                       domain/user    - Authentication domain and username
                   3562: #                                        of the requesting person.
1.324     raeburn  3563: #                       group          - Optional course group containing
                   3564: #                                        the board.      
1.234     foxr     3565: #   $client           - Socket open on the client program.
                   3566: # Returns:
                   3567: #    1     - continue processing
                   3568: # Side effects:
                   3569: #    Response is written to the client.
                   3570: #
                   3571: sub retrieve_chat_handler {
                   3572:     my ($cmd, $tail, $client) = @_;
                   3573: 
                   3574: 
                   3575:     my $userinput = "$cmd:$tail";
                   3576: 
1.324     raeburn  3577:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     3578:     my $reply='';
1.324     raeburn  3579:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     3580: 	$reply.=&escape($_).':';
                   3581:     }
                   3582:     $reply=~s/\:$//;
1.387     albertel 3583:     &Reply($client, \$reply, $userinput);
1.234     foxr     3584: 
                   3585: 
                   3586:     return 1;
                   3587: }
                   3588: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3589: 
                   3590: #
                   3591: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3592: #  a file for later retrieval.  This prevents sql query results from
                   3593: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3594: #  less of an issue since multiple outstanding requests can be concurrently
                   3595: #  serviced.
                   3596: #
                   3597: #  Parameters:
                   3598: #     $cmd       - COmmand keyword that initiated the request.
                   3599: #     $tail      - Remainder of the command after the keyword.
                   3600: #                  For this function, this consists of a query and
                   3601: #                  3 arguments that are self-documentingly labelled
                   3602: #                  in the original arg1, arg2, arg3.
                   3603: #     $client    - Socket open on the client.
                   3604: # Return:
                   3605: #    1   - Indicating processing should continue.
                   3606: # Side-effects:
                   3607: #    a reply is written to $client.
                   3608: #
                   3609: sub send_query_handler {
                   3610:     my ($cmd, $tail, $client) = @_;
                   3611: 
                   3612: 
                   3613:     my $userinput = "$cmd:$tail";
                   3614: 
                   3615:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3616:     $query=~s/\n*$//g;
                   3617:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   3618: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   3619: 	  $userinput);
                   3620:     
                   3621:     return 1;
                   3622: }
                   3623: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   3624: 
                   3625: #
                   3626: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   3627: #   The query is submitted via a "querysend" transaction.
                   3628: #   There it is passed on to the lonsql daemon, queued and issued to
                   3629: #   mysql.
                   3630: #     This transaction is invoked when the sql transaction is complete
                   3631: #   it stores the query results in flie and indicates query completion.
                   3632: #   presumably local software then fetches this response... I'm guessing
                   3633: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   3634: #   lonsql on completion of the query interacts with the lond of our
                   3635: #   client to do a query reply storing two files:
                   3636: #    - id     - The results of the query.
                   3637: #    - id.end - Indicating the transaction completed. 
                   3638: #    NOTE: id is a unique id assigned to the query and querysend time.
                   3639: # Parameters:
                   3640: #    $cmd        - Command keyword that initiated this request.
                   3641: #    $tail       - Remainder of the tail.  In this case that's a colon
                   3642: #                  separated list containing the query Id and the 
                   3643: #                  results of the query.
                   3644: #    $client     - Socket open on the client.
                   3645: # Return:
                   3646: #    1           - Indicating that we should continue processing.
                   3647: # Side effects:
                   3648: #    ok written to the client.
                   3649: #
                   3650: sub reply_query_handler {
                   3651:     my ($cmd, $tail, $client) = @_;
                   3652: 
                   3653: 
                   3654:     my $userinput = "$cmd:$tail";
                   3655: 
1.339     albertel 3656:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     3657:     my $store;
                   3658:     my $execdir=$perlvar{'lonDaemons'};
                   3659:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   3660: 	$reply=~s/\&/\n/g;
                   3661: 	print $store $reply;
                   3662: 	close $store;
                   3663: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   3664: 	print $store2 "done\n";
                   3665: 	close $store2;
                   3666: 	&Reply($client, "ok\n", $userinput);
                   3667:     } else {
                   3668: 	&Failure($client, "error: ".($!+0)
                   3669: 		." IO::File->new Failed ".
                   3670: 		"while attempting queryreply\n", $userinput);
                   3671:     }
                   3672:  
                   3673: 
                   3674:     return 1;
                   3675: }
                   3676: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   3677: 
                   3678: #
                   3679: #  Process the courseidput request.  Not quite sure what this means
                   3680: #  at the system level sense.  It appears a gdbm file in the 
                   3681: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   3682: #  a set of entries made in that database.
                   3683: #
                   3684: # Parameters:
                   3685: #   $cmd      - The command keyword that initiated this request.
                   3686: #   $tail     - Tail of the command.  In this case consists of a colon
                   3687: #               separated list contaning the domain to apply this to and
                   3688: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  3689: #               Each value is a colon separated list that includes:  
                   3690: #               description, institutional code and course owner.
                   3691: #               For backward compatibility with versions included
                   3692: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   3693: #               code and/or course owner are preserved from the existing 
                   3694: #               record when writing a new record in response to 1.1 or 
                   3695: #               1.2 implementations of lonnet::flushcourselogs().   
                   3696: #                      
1.234     foxr     3697: #   $client   - Socket open on the client.
                   3698: # Returns:
                   3699: #   1    - indicating that processing should continue
                   3700: #
                   3701: # Side effects:
                   3702: #   reply is written to the client.
                   3703: #
                   3704: sub put_course_id_handler {
                   3705:     my ($cmd, $tail, $client) = @_;
                   3706: 
                   3707: 
                   3708:     my $userinput = "$cmd:$tail";
                   3709: 
1.266     raeburn  3710:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     3711:     chomp($what);
                   3712:     my $now=time;
                   3713:     my @pairs=split(/\&/,$what);
                   3714: 
                   3715:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3716:     if ($hashref) {
                   3717: 	foreach my $pair (@pairs) {
1.271     raeburn  3718:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   3719:             $courseinfo =~ s/=/:/g;
1.384     raeburn  3720:             if (defined($hashref->{$key})) {
                   3721:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   3722:                 if (ref($value) eq 'HASH') {
                   3723:                     my @items = ('description','inst_code','owner','type');
                   3724:                     my @new_items = split(/:/,$courseinfo,-1);
                   3725:                     my %storehash; 
                   3726:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  3727:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  3728:                     }
                   3729:                     $hashref->{$key} = 
                   3730:                         &Apache::lonnet::freeze_escape(\%storehash);
                   3731:                     my $unesc_key = &unescape($key);
                   3732:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   3733:                     next;
1.383     raeburn  3734:                 }
1.384     raeburn  3735:             }
                   3736:             my @current_items = split(/:/,$hashref->{$key},-1);
                   3737:             shift(@current_items); # remove description
                   3738:             pop(@current_items);   # remove last access
                   3739:             my $numcurrent = scalar(@current_items);
                   3740:             if ($numcurrent > 3) {
                   3741:                 $numcurrent = 3;
                   3742:             }
                   3743:             my @new_items = split(/:/,$courseinfo,-1);
                   3744:             my $numnew = scalar(@new_items);
                   3745:             if ($numcurrent > 0) {
                   3746:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   3747:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   3748:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  3749:                     }
1.272     raeburn  3750:                 }
                   3751:             }
1.384     raeburn  3752:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     3753: 	}
1.311     albertel 3754: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     3755: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     3756: 	} else {
1.253     foxr     3757: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     3758: 		     ." untie(GDBM) Failed ".
                   3759: 		     "while attempting courseidput\n", $userinput);
                   3760: 	}
                   3761:     } else {
1.253     foxr     3762: 	&Failure($client, "error: ".($!+0)
1.234     foxr     3763: 		 ." tie(GDBM) Failed ".
                   3764: 		 "while attempting courseidput\n", $userinput);
                   3765:     }
                   3766: 
                   3767:     return 1;
                   3768: }
                   3769: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   3770: 
1.383     raeburn  3771: sub put_course_id_hash_handler {
                   3772:     my ($cmd, $tail, $client) = @_;
                   3773:     my $userinput = "$cmd:$tail";
1.384     raeburn  3774:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  3775:     chomp($what);
                   3776:     my $now=time;
                   3777:     my @pairs=split(/\&/,$what);
1.384     raeburn  3778:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  3779:     if ($hashref) {
                   3780:         foreach my $pair (@pairs) {
                   3781:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  3782:             my $unesc_key = &unescape($key);
                   3783:             if ($mode ne 'timeonly') {
                   3784:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   3785:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   3786:                     if (ref($curritems) ne 'HASH') {
                   3787:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   3788:                         my $lasttime = pop(@current_items);
                   3789:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   3790:                     } else {
                   3791:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   3792:                     }
                   3793:                 } 
                   3794:                 $hashref->{$key} = $value;
                   3795:             }
                   3796:             if ($mode ne 'notime') {
                   3797:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   3798:             }
1.383     raeburn  3799:         }
                   3800:         if (&untie_domain_hash($hashref)) {
                   3801:             &Reply($client, "ok\n", $userinput);
                   3802:         } else {
                   3803:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3804:                      "while attempting courseidputhash\n", $userinput);
                   3805:         }
                   3806:     } else {
                   3807:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3808:                   "while attempting courseidputhash\n", $userinput);
                   3809:     }
                   3810:     return 1;
                   3811: }
                   3812: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   3813: 
1.234     foxr     3814: #  Retrieves the value of a course id resource keyword pattern
                   3815: #  defined since a starting date.  Both the starting date and the
                   3816: #  keyword pattern are optional.  If the starting date is not supplied it
                   3817: #  is treated as the beginning of time.  If the pattern is not found,
                   3818: #  it is treatred as "." matching everything.
                   3819: #
                   3820: #  Parameters:
                   3821: #     $cmd     - Command keyword that resulted in us being dispatched.
                   3822: #     $tail    - The remainder of the command that, in this case, consists
                   3823: #                of a colon separated list of:
                   3824: #                 domain   - The domain in which the course database is 
                   3825: #                            defined.
                   3826: #                 since    - Optional parameter describing the minimum
                   3827: #                            time of definition(?) of the resources that
                   3828: #                            will match the dump.
                   3829: #                 description - regular expression that is used to filter
                   3830: #                            the dump.  Only keywords matching this regexp
                   3831: #                            will be used.
1.272     raeburn  3832: #                 institutional code - optional supplied code to filter 
                   3833: #                            the dump. Only courses with an institutional code 
                   3834: #                            that match the supplied code will be returned.
1.336     raeburn  3835: #                 owner    - optional supplied username and domain of owner to
                   3836: #                            filter the dump.  Only courses for which the course
                   3837: #                            owner matches the supplied username and/or domain
                   3838: #                            will be returned. Pre-2.2.0 legacy entries from 
                   3839: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  3840: #                 type     - optional parameter for selection 
1.418     raeburn  3841: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   3842: #                            filter to behave as a regular expression:
                   3843: #	                      1 will not exclude the course if the instcode matches the RE 
                   3844: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  3845: #                 rtn_as_hash - whether to return the information available for
                   3846: #                            each matched item as a frozen hash of all 
                   3847: #                            key, value pairs in the item's hash, or as a 
                   3848: #                            colon-separated list of (in order) description,
                   3849: #                            institutional code, and course owner.
1.404     raeburn  3850: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   3851: #                                  now or in the future (selfenrollonly = 1).
                   3852: #                 catfilter - filter by course category, assigned to a course 
                   3853: #                             using manually defined categories (i.e., not
1.407     raeburn  3854: #                             self-cataloging based on on institutional code).   
1.404     raeburn  3855: #                 showhidden - include course in results even if course  
1.407     raeburn  3856: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  3857: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   3858: #                           from course catalog will be excluded from results (unless
                   3859: #                           overridden by "showhidden".
1.427     raeburn  3860: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  3861: #                          clone).
                   3862: #                 cc_clone_list - escaped comma separated list of courses for which 
                   3863: #                                 course cloner has active CC role (and so can clone
                   3864: #                                 automatically).
1.427     raeburn  3865: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   3866: #                 createdbefore - include courses for which creation date preceeded this date.
                   3867: #                 createdafter - include courses for which creation date followed this date.
                   3868: #                 creationcontext - include courses created in specified context 
1.404     raeburn  3869: #
1.445     raeburn  3870: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.489.2.11  raeburn  3871: #                             If so, ability to clone course is automatic.
                   3872: #                 hasuniquecode - filter by courses for which a six character unique code has
                   3873: #                                 been set.
1.445     raeburn  3874: #
1.234     foxr     3875: #     $client  - The socket open on the client.
                   3876: # Returns:
                   3877: #    1     - Continue processing.
                   3878: # Side Effects:
                   3879: #   a reply is written to $client.
                   3880: sub dump_course_id_handler {
                   3881:     my ($cmd, $tail, $client) = @_;
                   3882:     my $userinput = "$cmd:$tail";
                   3883: 
1.333     raeburn  3884:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  3885:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  3886:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.489.2.11  raeburn  3887:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  3888:     my $now = time;
1.419     raeburn  3889:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     3890:     if (defined($description)) {
                   3891: 	$description=&unescape($description);
                   3892:     } else {
                   3893: 	$description='.';
                   3894:     }
1.266     raeburn  3895:     if (defined($instcodefilter)) {
                   3896:         $instcodefilter=&unescape($instcodefilter);
                   3897:     } else {
                   3898:         $instcodefilter='.';
                   3899:     }
1.336     raeburn  3900:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  3901:     if (defined($ownerfilter)) {
                   3902:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  3903:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   3904:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   3905:                  $ownerunamefilter = $1;
                   3906:                  $ownerdomfilter = $2;
                   3907:             } else {
                   3908:                 $ownerunamefilter = $ownerfilter;
                   3909:                 $ownerdomfilter = '';
                   3910:             }
                   3911:         }
1.266     raeburn  3912:     } else {
                   3913:         $ownerfilter='.';
                   3914:     }
1.336     raeburn  3915: 
1.282     raeburn  3916:     if (defined($coursefilter)) {
                   3917:         $coursefilter=&unescape($coursefilter);
                   3918:     } else {
                   3919:         $coursefilter='.';
                   3920:     }
1.333     raeburn  3921:     if (defined($typefilter)) {
                   3922:         $typefilter=&unescape($typefilter);
                   3923:     } else {
                   3924:         $typefilter='.';
                   3925:     }
1.344     raeburn  3926:     if (defined($regexp_ok)) {
                   3927:         $regexp_ok=&unescape($regexp_ok);
                   3928:     }
1.401     raeburn  3929:     if (defined($catfilter)) {
                   3930:         $catfilter=&unescape($catfilter);
                   3931:     }
1.419     raeburn  3932:     if (defined($cloner)) {
                   3933:         $cloner = &unescape($cloner);
                   3934:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   3935:     }
                   3936:     if (defined($cc_clone_list)) {
                   3937:         $cc_clone_list = &unescape($cc_clone_list);
                   3938:         my @cc_cloners = split('&',$cc_clone_list);
                   3939:         foreach my $cid (@cc_cloners) {
                   3940:             my ($clonedom,$clonenum) = split(':',$cid);
                   3941:             next if ($clonedom ne $udom); 
                   3942:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   3943:         } 
                   3944:     }
1.431     raeburn  3945:     if ($createdbefore ne '') {
1.427     raeburn  3946:         $createdbefore = &unescape($createdbefore);
                   3947:     } else {
                   3948:        $createdbefore = 0;
                   3949:     }
1.431     raeburn  3950:     if ($createdafter ne '') {
1.427     raeburn  3951:         $createdafter = &unescape($createdafter);
                   3952:     } else {
                   3953:         $createdafter = 0;
                   3954:     }
1.431     raeburn  3955:     if ($creationcontext ne '') {
1.427     raeburn  3956:         $creationcontext = &unescape($creationcontext);
                   3957:     } else {
                   3958:         $creationcontext = '.';
                   3959:     }
1.489.2.11  raeburn  3960:     unless ($hasuniquecode) {
                   3961:         $hasuniquecode = '.';
                   3962:     }
1.384     raeburn  3963:     my $unpack = 1;
1.485     raeburn  3964:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  3965:         $typefilter eq '.') {
                   3966:         $unpack = 0;
                   3967:     }
                   3968:     if (!defined($since)) { $since=0; }
1.234     foxr     3969:     my $qresult='';
                   3970:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3971:     if ($hashref) {
1.384     raeburn  3972: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  3973:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  3974:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   3975:                 $context);
1.384     raeburn  3976:             $unesc_key = &unescape($key);
                   3977:             if ($unesc_key =~ /^lasttime:/) {
                   3978:                 next;
                   3979:             } else {
                   3980:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   3981:             }
                   3982:             if ($hashref->{$lasttime_key} ne '') {
                   3983:                 $lasttime = $hashref->{$lasttime_key};
                   3984:                 next if ($lasttime<$since);
                   3985:             }
1.419     raeburn  3986:             my ($canclone,$valchange);
1.384     raeburn  3987:             my $items = &Apache::lonnet::thaw_unescape($value);
                   3988:             if (ref($items) eq 'HASH') {
1.429     raeburn  3989:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  3990:                     next if ($since > 1);
1.429     raeburn  3991:                 }
1.384     raeburn  3992:                 $is_hash =  1;
1.445     raeburn  3993:                 if ($domcloner) {
                   3994:                     $canclone = 1;
                   3995:                 } elsif (defined($clonerudom)) {
1.419     raeburn  3996:                     if ($items->{'cloners'}) {
                   3997:                         my @cloneable = split(',',$items->{'cloners'});
                   3998:                         if (@cloneable) {
                   3999:                             if (grep(/^\*$/,@cloneable))  {
                   4000:                                 $canclone = 1;
                   4001:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4002:                                 $canclone = 1;
                   4003:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4004:                                 $canclone = 1;
                   4005:                             }
                   4006:                         }
                   4007:                         unless ($canclone) {
                   4008:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4009:                                 if ($cc_clone{$unesc_key}) {
                   4010:                                     $canclone = 1;
                   4011:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4012:                                                            $clonerudom;
                   4013:                                     $valchange = 1;
                   4014:                                 }
                   4015:                             }
                   4016:                         }
                   4017:                     } elsif (defined($cloneruname)) {
                   4018:                         if ($cc_clone{$unesc_key}) {
                   4019:                             $canclone = 1;
                   4020:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4021:                             $valchange = 1;
                   4022:                         }
1.437     raeburn  4023:                         unless ($canclone) {
                   4024:                             if ($items->{'owner'} =~ /:/) {
                   4025:                                 if ($items->{'owner'} eq $cloner) {
                   4026:                                     $canclone = 1;
                   4027:                                 }
1.444     raeburn  4028:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4029:                                 $canclone = 1;
                   4030:                             }
                   4031:                             if ($canclone) {
                   4032:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4033:                                 $valchange = 1;
                   4034:                             }
                   4035:                         }
1.419     raeburn  4036:                     }
                   4037:                 }
1.384     raeburn  4038:                 if ($unpack || !$rtn_as_hash) {
                   4039:                     $unesc_val{'descr'} = $items->{'description'};
                   4040:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4041:                     $unesc_val{'owner'} = $items->{'owner'};
                   4042:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4043:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4044:                     $unesc_val{'created'} = $items->{'created'};
                   4045:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4046:                 }
                   4047:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4048:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4049:                 $created = $items->{'created'};
                   4050:                 $context = $items->{'context'};
1.489.2.11  raeburn  4051:                 if ($hasuniquecode ne '.') {
                   4052:                     next unless ($items->{'uniquecode'});
                   4053:                 }
1.404     raeburn  4054:                 if ($selfenrollonly) {
                   4055:                     next if (!$selfenroll_types);
                   4056:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4057:                         next;
1.397     raeburn  4058:                     }
1.404     raeburn  4059:                 }
1.427     raeburn  4060:                 if ($creationcontext ne '.') {
                   4061:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4062:                 }
                   4063:                 if ($createdbefore > 0) {
                   4064:                     next if (($created eq '') || ($created > $createdbefore));   
                   4065:                 }
                   4066:                 if ($createdafter > 0) {
                   4067:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4068:                 }
1.404     raeburn  4069:                 if ($catfilter ne '') {
1.406     raeburn  4070:                     next if ($items->{'categories'} eq '');
                   4071:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4072:                     next if (@categories == 0);
                   4073:                     my @subcats = split('&',$catfilter);
                   4074:                     my $matchcat = 0;
                   4075:                     foreach my $cat (@categories) {
                   4076:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4077:                             $matchcat = 1;
                   4078:                             last;
                   4079:                         }
                   4080:                     }
                   4081:                     next if (!$matchcat);
1.404     raeburn  4082:                 }
                   4083:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4084:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4085:                         next if !$showhidden;
1.401     raeburn  4086:                     }
1.384     raeburn  4087:                 }
1.383     raeburn  4088:             } else {
1.401     raeburn  4089:                 next if ($catfilter ne '');
1.419     raeburn  4090:                 next if ($selfenrollonly);
1.427     raeburn  4091:                 next if ($createdbefore || $createdafter);
                   4092:                 next if ($creationcontext ne '.');
1.419     raeburn  4093:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4094:                     if ($cc_clone{$unesc_key}) {
                   4095:                         $canclone = 1;
                   4096:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4097:                     }
                   4098:                 }
1.384     raeburn  4099:                 $is_hash =  0;
1.388     raeburn  4100:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4101:                 $lasttime = pop(@courseitems);
1.402     raeburn  4102:                 if ($hashref->{$lasttime_key} eq '') {
                   4103:                     next if ($lasttime<$since);
                   4104:                 }
1.384     raeburn  4105: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4106:             }
1.419     raeburn  4107:             if ($cloneonly) {
                   4108:                next unless ($canclone);
                   4109:             }
1.266     raeburn  4110:             my $match = 1;
1.384     raeburn  4111: 	    if ($description ne '.') {
                   4112:                 if (!$is_hash) {
                   4113:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4114:                 }
                   4115:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4116:                     $match = 0;
1.384     raeburn  4117:                 }
1.266     raeburn  4118:             }
1.384     raeburn  4119:             if ($instcodefilter ne '.') {
                   4120:                 if (!$is_hash) {
                   4121:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4122:                 }
1.418     raeburn  4123:                 if ($regexp_ok == 1) {
1.384     raeburn  4124:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4125:                         $match = 0;
                   4126:                     }
1.418     raeburn  4127:                 } elsif ($regexp_ok == -1) {
                   4128:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4129:                         $match = 0;
                   4130:                     }
1.344     raeburn  4131:                 } else {
1.384     raeburn  4132:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4133:                         $match = 0;
                   4134:                     }
1.266     raeburn  4135:                 }
1.234     foxr     4136: 	    }
1.384     raeburn  4137:             if ($ownerfilter ne '.') {
                   4138:                 if (!$is_hash) {
                   4139:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4140:                 }
1.336     raeburn  4141:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4142:                     if ($unesc_val{'owner'} =~ /:/) {
                   4143:                         if (eval{$unesc_val{'owner'} !~ 
                   4144:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4145:                             $match = 0;
                   4146:                         } 
                   4147:                     } else {
1.384     raeburn  4148:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4149:                             $match = 0;
                   4150:                         }
                   4151:                     }
                   4152:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4153:                     if ($unesc_val{'owner'} =~ /:/) {
                   4154:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4155:                              $match = 0;
                   4156:                         }
                   4157:                     } else {
1.384     raeburn  4158:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4159:                             $match = 0;
                   4160:                         }
                   4161:                     }
                   4162:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4163:                     if ($unesc_val{'owner'} =~ /:/) {
                   4164:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4165:                              $match = 0;
                   4166:                         }
                   4167:                     } else {
                   4168:                         if ($ownerdomfilter ne $udom) {
                   4169:                             $match = 0;
                   4170:                         }
                   4171:                     }
1.266     raeburn  4172:                 }
                   4173:             }
1.384     raeburn  4174:             if ($coursefilter ne '.') {
                   4175:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4176:                     $match = 0;
                   4177:                 }
                   4178:             }
1.384     raeburn  4179:             if ($typefilter ne '.') {
                   4180:                 if (!$is_hash) {
                   4181:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4182:                 }
                   4183:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4184:                     if ($typefilter ne 'Course') {
                   4185:                         $match = 0;
                   4186:                     }
1.383     raeburn  4187:                 } else {
1.384     raeburn  4188:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4189:                         $match = 0;
                   4190:                     }
                   4191:                 }
                   4192:             }
1.266     raeburn  4193:             if ($match == 1) {
1.384     raeburn  4194:                 if ($rtn_as_hash) {
                   4195:                     if ($is_hash) {
1.419     raeburn  4196:                         if ($valchange) {
                   4197:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4198:                             $qresult.=$key.'='.$newvalue.'&';
                   4199:                         } else {
                   4200:                             $qresult.=$key.'='.$value.'&';
                   4201:                         }
1.384     raeburn  4202:                     } else {
1.388     raeburn  4203:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4204:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4205:                                         'owner'     => &unescape($val{'owner'}),
                   4206:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4207:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4208:                                       );
                   4209:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4210:                         $qresult.=$key.'='.$items.'&';
                   4211:                     }
1.383     raeburn  4212:                 } else {
1.384     raeburn  4213:                     if ($is_hash) {
                   4214:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4215:                                     &escape($unesc_val{'inst_code'}).':'.
                   4216:                                     &escape($unesc_val{'owner'}).'&';
                   4217:                     } else {
                   4218:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4219:                                     ':'.$val{'owner'}.'&';
                   4220:                     }
1.383     raeburn  4221:                 }
1.266     raeburn  4222:             }
1.234     foxr     4223: 	}
1.311     albertel 4224: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4225: 	    chop($qresult);
1.387     albertel 4226: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4227: 	} else {
                   4228: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4229: 		    "while attempting courseiddump\n", $userinput);
                   4230: 	}
                   4231:     } else {
                   4232: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4233: 		"while attempting courseiddump\n", $userinput);
                   4234:     }
                   4235:     return 1;
                   4236: }
                   4237: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4238: 
1.438     raeburn  4239: sub course_lastaccess_handler {
                   4240:     my ($cmd, $tail, $client) = @_;
                   4241:     my $userinput = "$cmd:$tail";
                   4242:     my ($cdom,$cnum) = split(':',$tail); 
                   4243:     my (%lastaccess,$qresult);
                   4244:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4245:     if ($hashref) {
                   4246:         while (my ($key,$value) = each(%$hashref)) {
                   4247:             my ($unesc_key,$lasttime);
                   4248:             $unesc_key = &unescape($key);
                   4249:             if ($cnum) {
                   4250:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4251:             }
                   4252:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4253:                 $lastaccess{$1} = $value;
                   4254:             } else {
                   4255:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4256:                 if (ref($items) eq 'HASH') {
                   4257:                     unless ($lastaccess{$unesc_key}) {
                   4258:                         $lastaccess{$unesc_key} = '';
                   4259:                     }
                   4260:                 } else {
                   4261:                     my @courseitems = split(':',$value);
                   4262:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4263:                 }
                   4264:             }
                   4265:         }
                   4266:         foreach my $cid (sort(keys(%lastaccess))) {
                   4267:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4268:         }
                   4269:         if (&untie_domain_hash($hashref)) {
                   4270:             if ($qresult) {
                   4271:                 chop($qresult);
                   4272:             }
                   4273:             &Reply($client, \$qresult, $userinput);
                   4274:         } else {
                   4275:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4276:                     "while attempting lastacourseaccess\n", $userinput);
                   4277:         }
                   4278:     } else {
                   4279:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4280:                 "while attempting lastcourseaccess\n", $userinput);
                   4281:     }
                   4282:     return 1;
                   4283: }
                   4284: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4285: 
1.238     foxr     4286: #
1.348     raeburn  4287: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4288: #
                   4289: # Parameters:
                   4290: #    $cmd      - The command that got us here.
                   4291: #    $tail     - Tail of the command (remaining parameters).
                   4292: #    $client   - File descriptor connected to client.
                   4293: # Returns
                   4294: #     0        - Requested to exit, caller should shut down.
                   4295: #     1        - Continue processing.
                   4296: #  Side effects:
                   4297: #     reply is written to $client.
                   4298: #
                   4299: sub put_domain_handler {
                   4300:     my ($cmd,$tail,$client) = @_;
                   4301: 
                   4302:     my $userinput = "$cmd:$tail";
                   4303: 
                   4304:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4305:     chomp($what);
                   4306:     my @pairs=split(/\&/,$what);
                   4307:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4308:                                    "P", $what);
                   4309:     if ($hashref) {
                   4310:         foreach my $pair (@pairs) {
                   4311:             my ($key,$value)=split(/=/,$pair);
                   4312:             $hashref->{$key}=$value;
                   4313:         }
                   4314:         if (&untie_domain_hash($hashref)) {
                   4315:             &Reply($client, "ok\n", $userinput);
                   4316:         } else {
                   4317:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4318:                      "while attempting putdom\n", $userinput);
                   4319:         }
                   4320:     } else {
                   4321:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4322:                   "while attempting putdom\n", $userinput);
                   4323:     }
                   4324: 
                   4325:     return 1;
                   4326: }
                   4327: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4328: 
                   4329: # Unencrypted get from the namespace database file at the domain level.
                   4330: # This function retrieves a keyed item from a specific named database in the
                   4331: # domain directory.
                   4332: #
                   4333: # Parameters:
                   4334: #   $cmd             - Command request keyword (get).
                   4335: #   $tail            - Tail of the command.  This is a colon separated list
                   4336: #                      consisting of the domain and the 'namespace' 
                   4337: #                      which selects the gdbm file to do the lookup in,
                   4338: #                      & separated list of keys to lookup.  Note that
                   4339: #                      the values are returned as an & separated list too.
                   4340: #   $client          - File descriptor open on the client.
                   4341: # Returns:
                   4342: #   1       - Continue processing.
                   4343: #   0       - Exit.
                   4344: #  Side effects:
                   4345: #     reply is written to $client.
                   4346: #
                   4347: 
                   4348: sub get_domain_handler {
                   4349:     my ($cmd, $tail, $client) = @_;
                   4350: 
1.461     foxr     4351: 
1.348     raeburn  4352:     my $userinput = "$client:$tail";
                   4353: 
                   4354:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4355:     chomp($what);
                   4356:     my @queries=split(/\&/,$what);
                   4357:     my $qresult='';
                   4358:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4359:     if ($hashref) {
                   4360:         for (my $i=0;$i<=$#queries;$i++) {
                   4361:             $qresult.="$hashref->{$queries[$i]}&";
                   4362:         }
                   4363:         if (&untie_domain_hash($hashref)) {
                   4364:             $qresult=~s/\&$//;
1.387     albertel 4365:             &Reply($client, \$qresult, $userinput);
1.348     raeburn  4366:         } else {
                   4367:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4368:                       "while attempting getdom\n",$userinput);
                   4369:         }
                   4370:     } else {
                   4371:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4372:                  "while attempting getdom\n",$userinput);
                   4373:     }
                   4374: 
                   4375:     return 1;
                   4376: }
1.360     raeburn  4377: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
1.348     raeburn  4378: 
1.420     raeburn  4379: #
1.238     foxr     4380: #  Puts an id to a domains id database. 
                   4381: #
                   4382: #  Parameters:
                   4383: #   $cmd     - The command that triggered us.
                   4384: #   $tail    - Remainder of the request other than the command. This is a 
                   4385: #              colon separated list containing:
                   4386: #              $domain  - The domain for which we are writing the id.
                   4387: #              $pairs  - The id info to write... this is and & separated list
                   4388: #                        of keyword=value.
                   4389: #   $client  - Socket open on the client.
                   4390: #  Returns:
                   4391: #    1   - Continue processing.
                   4392: #  Side effects:
                   4393: #     reply is written to $client.
                   4394: #
                   4395: sub put_id_handler {
                   4396:     my ($cmd,$tail,$client) = @_;
                   4397: 
                   4398: 
                   4399:     my $userinput = "$cmd:$tail";
                   4400: 
                   4401:     my ($udom,$what)=split(/:/,$tail);
                   4402:     chomp($what);
                   4403:     my @pairs=split(/\&/,$what);
                   4404:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   4405: 				   "P", $what);
                   4406:     if ($hashref) {
                   4407: 	foreach my $pair (@pairs) {
                   4408: 	    my ($key,$value)=split(/=/,$pair);
                   4409: 	    $hashref->{$key}=$value;
                   4410: 	}
1.311     albertel 4411: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     4412: 	    &Reply($client, "ok\n", $userinput);
                   4413: 	} else {
                   4414: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4415: 		     "while attempting idput\n", $userinput);
                   4416: 	}
                   4417:     } else {
                   4418: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4419: 		  "while attempting idput\n", $userinput);
                   4420:     }
                   4421: 
                   4422:     return 1;
                   4423: }
1.263     albertel 4424: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     4425: 
                   4426: #
                   4427: #  Retrieves a set of id values from the id database.
                   4428: #  Returns an & separated list of results, one for each requested id to the
                   4429: #  client.
                   4430: #
                   4431: # Parameters:
                   4432: #   $cmd       - Command keyword that caused us to be dispatched.
                   4433: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4434: #               domain - the domain whose id table we dump
                   4435: #               ids      Consists of an & separated list of
                   4436: #                        id keywords whose values will be fetched.
                   4437: #                        nonexisting keywords will have an empty value.
                   4438: #   $client    - Socket open on the client.
                   4439: #
                   4440: # Returns:
                   4441: #    1 - indicating processing should continue.
                   4442: # Side effects:
                   4443: #   An & separated list of results is written to $client.
                   4444: #
                   4445: sub get_id_handler {
                   4446:     my ($cmd, $tail, $client) = @_;
                   4447: 
                   4448:     
                   4449:     my $userinput = "$client:$tail";
                   4450:     
                   4451:     my ($udom,$what)=split(/:/,$tail);
                   4452:     chomp($what);
                   4453:     my @queries=split(/\&/,$what);
                   4454:     my $qresult='';
                   4455:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   4456:     if ($hashref) {
                   4457: 	for (my $i=0;$i<=$#queries;$i++) {
                   4458: 	    $qresult.="$hashref->{$queries[$i]}&";
                   4459: 	}
1.311     albertel 4460: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     4461: 	    $qresult=~s/\&$//;
1.387     albertel 4462: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     4463: 	} else {
                   4464: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4465: 		      "while attempting idget\n",$userinput);
                   4466: 	}
                   4467:     } else {
                   4468: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4469: 		 "while attempting idget\n",$userinput);
                   4470:     }
                   4471:     
                   4472:     return 1;
                   4473: }
1.263     albertel 4474: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     4475: 
1.489.2.7  raeburn  4476: #   Deletes one or more ids in a domain's id database.
1.489.2.6  raeburn  4477: #
                   4478: #   Parameters:
                   4479: #       $cmd                  - Command keyword (iddel).
                   4480: #       $tail                 - Command tail.  In this case a colon
                   4481: #                               separated list containing:
                   4482: #                               The domain for which we are deleting the id(s).
                   4483: #                               &-separated list of id(s) to delete.
                   4484: #       $client               - File open on client socket.
                   4485: # Returns:
                   4486: #     1   - Continue processing
                   4487: #     0   - Exit server.
                   4488: #
                   4489: #
                   4490: 
                   4491: sub del_id_handler {
                   4492:     my ($cmd,$tail,$client) = @_;
                   4493: 
                   4494:     my $userinput = "$cmd:$tail";
                   4495: 
                   4496:     my ($udom,$what)=split(/:/,$tail);
                   4497:     chomp($what);
                   4498:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   4499:                                    "D", $what);
                   4500:     if ($hashref) {
                   4501:         my @keys=split(/\&/,$what);
                   4502:         foreach my $key (@keys) {
                   4503:             delete($hashref->{$key});
                   4504:         }
                   4505:         if (&untie_user_hash($hashref)) {
                   4506:             &Reply($client, "ok\n", $userinput);
                   4507:         } else {
                   4508:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4509:                     "while attempting iddel\n", $userinput);
                   4510:         }
                   4511:     } else {
                   4512:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4513:                  "while attempting iddel\n", $userinput);
                   4514:     }
                   4515:     return 1;
                   4516: }
                   4517: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   4518: 
1.238     foxr     4519: #
1.299     raeburn  4520: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   4521: #
                   4522: # Parameters
                   4523: #   $cmd       - Command keyword that caused us to be dispatched.
                   4524: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4525: #               domain - the domain whose dcmail we are recording
                   4526: #               email    Consists of key=value pair 
                   4527: #                        where key is unique msgid
                   4528: #                        and value is message (in XML)
                   4529: #   $client    - Socket open on the client.
                   4530: #
                   4531: # Returns:
                   4532: #    1 - indicating processing should continue.
                   4533: # Side effects
                   4534: #     reply is written to $client.
                   4535: #
                   4536: sub put_dcmail_handler {
                   4537:     my ($cmd,$tail,$client) = @_;
                   4538:     my $userinput = "$cmd:$tail";
1.463     foxr     4539: 
                   4540: 
1.299     raeburn  4541:     my ($udom,$what)=split(/:/,$tail);
                   4542:     chomp($what);
                   4543:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   4544:     if ($hashref) {
                   4545:         my ($key,$value)=split(/=/,$what);
                   4546:         $hashref->{$key}=$value;
                   4547:     }
1.311     albertel 4548:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  4549:         &Reply($client, "ok\n", $userinput);
                   4550:     } else {
                   4551:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4552:                  "while attempting dcmailput\n", $userinput);
                   4553:     }
                   4554:     return 1;
                   4555: }
                   4556: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   4557: 
                   4558: #
                   4559: # Retrieves broadcast e-mail from nohist_dcmail database
                   4560: # Returns to client an & separated list of key=value pairs,
                   4561: # where key is msgid and value is message information.
                   4562: #
                   4563: # Parameters
                   4564: #   $cmd       - Command keyword that caused us to be dispatched.
                   4565: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4566: #               domain - the domain whose dcmail table we dump
                   4567: #               startfilter - beginning of time window 
                   4568: #               endfilter - end of time window
                   4569: #               sendersfilter - & separated list of username:domain 
                   4570: #                 for senders to search for.
                   4571: #   $client    - Socket open on the client.
                   4572: #
                   4573: # Returns:
                   4574: #    1 - indicating processing should continue.
                   4575: # Side effects
                   4576: #     reply (& separated list of msgid=messageinfo pairs) is 
                   4577: #     written to $client.
                   4578: #
                   4579: sub dump_dcmail_handler {
                   4580:     my ($cmd, $tail, $client) = @_;
                   4581:                                                                                 
                   4582:     my $userinput = "$cmd:$tail";
                   4583:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   4584:     chomp($sendersfilter);
                   4585:     my @senders = ();
                   4586:     if (defined($startfilter)) {
                   4587:         $startfilter=&unescape($startfilter);
                   4588:     } else {
                   4589:         $startfilter='.';
                   4590:     }
                   4591:     if (defined($endfilter)) {
                   4592:         $endfilter=&unescape($endfilter);
                   4593:     } else {
                   4594:         $endfilter='.';
                   4595:     }
                   4596:     if (defined($sendersfilter)) {
                   4597:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 4598: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  4599:     }
                   4600: 
                   4601:     my $qresult='';
                   4602:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   4603:     if ($hashref) {
                   4604:         while (my ($key,$value) = each(%$hashref)) {
                   4605:             my $match = 1;
1.303     albertel 4606:             my ($timestamp,$subj,$uname,$udom) = 
                   4607: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  4608:             $subj = &unescape($subj);
                   4609:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   4610:                 if ($timestamp < $startfilter) {
                   4611:                     $match = 0;
                   4612:                 }
                   4613:             }
                   4614:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   4615:                 if ($timestamp > $endfilter) {
                   4616:                     $match = 0;
                   4617:                 }
                   4618:             }
                   4619:             unless (@senders < 1) {
                   4620:                 unless (grep/^$uname:$udom$/,@senders) {
                   4621:                     $match = 0;
                   4622:                 }
                   4623:             }
                   4624:             if ($match == 1) {
                   4625:                 $qresult.=$key.'='.$value.'&';
                   4626:             }
                   4627:         }
1.311     albertel 4628:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  4629:             chop($qresult);
1.387     albertel 4630:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  4631:         } else {
                   4632:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4633:                     "while attempting dcmaildump\n", $userinput);
                   4634:         }
                   4635:     } else {
                   4636:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4637:                 "while attempting dcmaildump\n", $userinput);
                   4638:     }
                   4639:     return 1;
                   4640: }
                   4641: 
                   4642: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   4643: 
                   4644: #
                   4645: # Puts domain roles in nohist_domainroles database
                   4646: #
                   4647: # Parameters
                   4648: #   $cmd       - Command keyword that caused us to be dispatched.
                   4649: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4650: #               domain - the domain whose roles we are recording  
                   4651: #               role -   Consists of key=value pair
                   4652: #                        where key is unique role
                   4653: #                        and value is start/end date information
                   4654: #   $client    - Socket open on the client.
                   4655: #
                   4656: # Returns:
                   4657: #    1 - indicating processing should continue.
                   4658: # Side effects
                   4659: #     reply is written to $client.
                   4660: #
                   4661: 
                   4662: sub put_domainroles_handler {
                   4663:     my ($cmd,$tail,$client) = @_;
                   4664: 
                   4665:     my $userinput = "$cmd:$tail";
                   4666:     my ($udom,$what)=split(/:/,$tail);
                   4667:     chomp($what);
                   4668:     my @pairs=split(/\&/,$what);
                   4669:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   4670:     if ($hashref) {
                   4671:         foreach my $pair (@pairs) {
                   4672:             my ($key,$value)=split(/=/,$pair);
                   4673:             $hashref->{$key}=$value;
                   4674:         }
1.311     albertel 4675:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  4676:             &Reply($client, "ok\n", $userinput);
                   4677:         } else {
                   4678:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4679:                      "while attempting domroleput\n", $userinput);
                   4680:         }
                   4681:     } else {
                   4682:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4683:                   "while attempting domroleput\n", $userinput);
                   4684:     }
                   4685:                                                                                   
                   4686:     return 1;
                   4687: }
                   4688: 
                   4689: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   4690: 
                   4691: #
                   4692: # Retrieves domain roles from nohist_domainroles database
                   4693: # Returns to client an & separated list of key=value pairs,
                   4694: # where key is role and value is start and end date information.
                   4695: #
                   4696: # Parameters
                   4697: #   $cmd       - Command keyword that caused us to be dispatched.
                   4698: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4699: #               domain - the domain whose domain roles table we dump
                   4700: #   $client    - Socket open on the client.
                   4701: #
                   4702: # Returns:
                   4703: #    1 - indicating processing should continue.
                   4704: # Side effects
                   4705: #     reply (& separated list of role=start/end info pairs) is
                   4706: #     written to $client.
                   4707: #
                   4708: sub dump_domainroles_handler {
                   4709:     my ($cmd, $tail, $client) = @_;
                   4710:                                                                                            
                   4711:     my $userinput = "$cmd:$tail";
                   4712:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   4713:     chomp($rolesfilter);
                   4714:     my @roles = ();
                   4715:     if (defined($startfilter)) {
                   4716:         $startfilter=&unescape($startfilter);
                   4717:     } else {
                   4718:         $startfilter='.';
                   4719:     }
                   4720:     if (defined($endfilter)) {
                   4721:         $endfilter=&unescape($endfilter);
                   4722:     } else {
                   4723:         $endfilter='.';
                   4724:     }
                   4725:     if (defined($rolesfilter)) {
                   4726:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 4727: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  4728:     }
1.421     raeburn  4729: 
1.299     raeburn  4730:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   4731:     if ($hashref) {
                   4732:         my $qresult = '';
                   4733:         while (my ($key,$value) = each(%$hashref)) {
                   4734:             my $match = 1;
1.421     raeburn  4735:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  4736:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  4737:             unless (@roles < 1) {
                   4738:                 unless (grep/^\Q$trole\E$/,@roles) {
                   4739:                     $match = 0;
                   4740:                     next;
                   4741:                 }
                   4742:             }
1.299     raeburn  4743:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  4744:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  4745:                     $match = 0;
1.421     raeburn  4746:                     next;
1.299     raeburn  4747:                 }
                   4748:             }
                   4749:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  4750:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  4751:                     $match = 0;
1.421     raeburn  4752:                     next;
1.299     raeburn  4753:                 }
                   4754:             }
                   4755:             if ($match == 1) {
                   4756:                 $qresult.=$key.'='.$value.'&';
                   4757:             }
                   4758:         }
1.311     albertel 4759:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  4760:             chop($qresult);
1.387     albertel 4761:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  4762:         } else {
                   4763:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4764:                     "while attempting domrolesdump\n", $userinput);
                   4765:         }
                   4766:     } else {
                   4767:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4768:                 "while attempting domrolesdump\n", $userinput);
                   4769:     }
                   4770:     return 1;
                   4771: }
                   4772: 
                   4773: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   4774: 
                   4775: 
1.238     foxr     4776: #  Process the tmpput command I'm not sure what this does.. Seems to
                   4777: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   4778: # where Id is the client's ip concatenated with a sequence number.
                   4779: # The file will contain some value that is passed in.  Is this e.g.
                   4780: # a login token?
                   4781: #
                   4782: # Parameters:
                   4783: #    $cmd     - The command that got us dispatched.
                   4784: #    $tail    - The remainder of the request following $cmd:
                   4785: #               In this case this will be the contents of the file.
                   4786: #    $client  - Socket connected to the client.
                   4787: # Returns:
                   4788: #    1 indicating processing can continue.
                   4789: # Side effects:
                   4790: #   A file is created in the local filesystem.
                   4791: #   A reply is sent to the client.
                   4792: sub tmp_put_handler {
                   4793:     my ($cmd, $what, $client) = @_;
                   4794: 
                   4795:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   4796: 
1.347     raeburn  4797:     my ($record,$context) = split(/:/,$what);
                   4798:     if ($context ne '') {
                   4799:         chomp($context);
                   4800:         $context = &unescape($context);
                   4801:     }
                   4802:     my ($id,$store);
1.238     foxr     4803:     $tmpsnum++;
1.454     raeburn  4804:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  4805:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   4806:     } else {
                   4807:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   4808:     }
1.238     foxr     4809:     $id=~s/\W/\_/g;
1.347     raeburn  4810:     $record=~s/\n//g;
1.238     foxr     4811:     my $execdir=$perlvar{'lonDaemons'};
                   4812:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  4813: 	print $store $record;
1.238     foxr     4814: 	close $store;
1.387     albertel 4815: 	&Reply($client, \$id, $userinput);
1.238     foxr     4816:     } else {
                   4817: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   4818: 		  "while attempting tmpput\n", $userinput);
                   4819:     }
                   4820:     return 1;
                   4821:   
                   4822: }
                   4823: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 4824: 
1.238     foxr     4825: #   Processes the tmpget command.  This command returns the contents
                   4826: #  of a temporary resource file(?) created via tmpput.
                   4827: #
                   4828: # Paramters:
                   4829: #    $cmd      - Command that got us dispatched.
                   4830: #    $id       - Tail of the command, contain the id of the resource
                   4831: #                we want to fetch.
                   4832: #    $client   - socket open on the client.
                   4833: # Return:
                   4834: #    1         - Inidcating processing can continue.
                   4835: # Side effects:
                   4836: #   A reply is sent to the client.
                   4837: #
                   4838: sub tmp_get_handler {
                   4839:     my ($cmd, $id, $client) = @_;
                   4840: 
                   4841:     my $userinput = "$cmd:$id"; 
                   4842:     
                   4843: 
                   4844:     $id=~s/\W/\_/g;
                   4845:     my $store;
                   4846:     my $execdir=$perlvar{'lonDaemons'};
                   4847:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   4848: 	my $reply=<$store>;
1.387     albertel 4849: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     4850: 	close $store;
                   4851:     } else {
                   4852: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   4853: 		  "while attempting tmpget\n", $userinput);
                   4854:     }
                   4855: 
                   4856:     return 1;
                   4857: }
                   4858: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 4859: 
1.238     foxr     4860: #
                   4861: #  Process the tmpdel command.  This command deletes a temp resource
                   4862: #  created by the tmpput command.
                   4863: #
                   4864: # Parameters:
                   4865: #   $cmd      - Command that got us here.
                   4866: #   $id       - Id of the temporary resource created.
                   4867: #   $client   - socket open on the client process.
                   4868: #
                   4869: # Returns:
                   4870: #   1     - Indicating processing should continue.
                   4871: # Side Effects:
                   4872: #   A file is deleted
                   4873: #   A reply is sent to the client.
                   4874: sub tmp_del_handler {
                   4875:     my ($cmd, $id, $client) = @_;
                   4876:     
                   4877:     my $userinput= "$cmd:$id";
                   4878:     
                   4879:     chomp($id);
                   4880:     $id=~s/\W/\_/g;
                   4881:     my $execdir=$perlvar{'lonDaemons'};
                   4882:     if (unlink("$execdir/tmp/$id.tmp")) {
                   4883: 	&Reply($client, "ok\n", $userinput);
                   4884:     } else {
                   4885: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   4886: 		  "while attempting tmpdel\n", $userinput);
                   4887:     }
                   4888:     
                   4889:     return 1;
                   4890: 
                   4891: }
                   4892: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 4893: 
1.238     foxr     4894: #
1.246     foxr     4895: #   Processes the setannounce command.  This command
                   4896: #   creates a file named announce.txt in the top directory of
                   4897: #   the documentn root and sets its contents.  The announce.txt file is
                   4898: #   printed in its entirety at the LonCAPA login page.  Note:
                   4899: #   once the announcement.txt fileis created it cannot be deleted.
                   4900: #   However, setting the contents of the file to empty removes the
                   4901: #   announcement from the login page of loncapa so who cares.
                   4902: #
                   4903: # Parameters:
                   4904: #    $cmd          - The command that got us dispatched.
                   4905: #    $announcement - The text of the announcement.
                   4906: #    $client       - Socket open on the client process.
                   4907: # Retunrns:
                   4908: #   1             - Indicating request processing should continue
                   4909: # Side Effects:
                   4910: #   The file {DocRoot}/announcement.txt is created.
                   4911: #   A reply is sent to $client.
                   4912: #
                   4913: sub set_announce_handler {
                   4914:     my ($cmd, $announcement, $client) = @_;
                   4915:   
                   4916:     my $userinput    = "$cmd:$announcement";
                   4917: 
                   4918:     chomp($announcement);
                   4919:     $announcement=&unescape($announcement);
                   4920:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   4921: 				'/announcement.txt')) {
                   4922: 	print $store $announcement;
                   4923: 	close $store;
                   4924: 	&Reply($client, "ok\n", $userinput);
                   4925:     } else {
                   4926: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   4927:     }
                   4928: 
                   4929:     return 1;
                   4930: }
                   4931: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 4932: 
1.246     foxr     4933: #
                   4934: #  Return the version of the daemon.  This can be used to determine
                   4935: #  the compatibility of cross version installations or, alternatively to
                   4936: #  simply know who's out of date and who isn't.  Note that the version
                   4937: #  is returned concatenated with the tail.
                   4938: # Parameters:
                   4939: #   $cmd        - the request that dispatched to us.
                   4940: #   $tail       - Tail of the request (client's version?).
                   4941: #   $client     - Socket open on the client.
                   4942: #Returns:
                   4943: #   1 - continue processing requests.
                   4944: # Side Effects:
                   4945: #   Replies with version to $client.
                   4946: sub get_version_handler {
                   4947:     my ($cmd, $tail, $client) = @_;
                   4948: 
                   4949:     my $userinput  = $cmd.$tail;
                   4950:     
                   4951:     &Reply($client, &version($userinput)."\n", $userinput);
                   4952: 
                   4953: 
                   4954:     return 1;
                   4955: }
                   4956: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 4957: 
1.246     foxr     4958: #  Set the current host and domain.  This is used to support
                   4959: #  multihomed systems.  Each IP of the system, or even separate daemons
                   4960: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   4961: #  machine.  This command selects the virtual lonCAPA.  The client always
                   4962: #  knows the right one since it is lonc and it is selecting the domain/system
                   4963: #  from the hosts.tab file.
                   4964: # Parameters:
                   4965: #    $cmd      - Command that dispatched us.
                   4966: #    $tail     - Tail of the command (domain/host requested).
                   4967: #    $socket   - Socket open on the client.
                   4968: #
                   4969: # Returns:
                   4970: #     1   - Indicates the program should continue to process requests.
                   4971: # Side-effects:
                   4972: #     The default domain/system context is modified for this daemon.
                   4973: #     a reply is sent to the client.
                   4974: #
                   4975: sub set_virtual_host_handler {
                   4976:     my ($cmd, $tail, $socket) = @_;
                   4977:   
                   4978:     my $userinput  ="$cmd:$tail";
                   4979: 
                   4980:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   4981: 
                   4982: 
                   4983:     return 1;
                   4984: }
1.247     albertel 4985: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     4986: 
                   4987: #  Process a request to exit:
                   4988: #   - "bye" is sent to the client.
                   4989: #   - The client socket is shutdown and closed.
                   4990: #   - We indicate to the caller that we should exit.
                   4991: # Formal Parameters:
                   4992: #   $cmd                - The command that got us here.
                   4993: #   $tail               - Tail of the command (empty).
                   4994: #   $client             - Socket open on the tail.
                   4995: # Returns:
                   4996: #   0      - Indicating the program should exit!!
                   4997: #
                   4998: sub exit_handler {
                   4999:     my ($cmd, $tail, $client) = @_;
                   5000: 
                   5001:     my $userinput = "$cmd:$tail";
                   5002: 
                   5003:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5004:     &Reply($client, "bye\n", $userinput);
                   5005:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5006:     $client->close();
                   5007: 
                   5008:     return 0;
                   5009: }
1.248     foxr     5010: &register_handler("exit", \&exit_handler, 0,1,1);
                   5011: &register_handler("init", \&exit_handler, 0,1,1);
                   5012: &register_handler("quit", \&exit_handler, 0,1,1);
                   5013: 
                   5014: #  Determine if auto-enrollment is enabled.
                   5015: #  Note that the original had what I believe to be a defect.
                   5016: #  The original returned 0 if the requestor was not a registerd client.
                   5017: #  It should return "refused".
                   5018: # Formal Parameters:
                   5019: #   $cmd       - The command that invoked us.
                   5020: #   $tail      - The tail of the command (Extra command parameters.
                   5021: #   $client    - The socket open on the client that issued the request.
                   5022: # Returns:
                   5023: #    1         - Indicating processing should continue.
                   5024: #
                   5025: sub enrollment_enabled_handler {
                   5026:     my ($cmd, $tail, $client) = @_;
                   5027:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5028: 
                   5029:     
1.337     albertel 5030:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5031: 
1.248     foxr     5032:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5033:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5034: 
                   5035:     return 1;
                   5036: }
                   5037: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5038: 
1.417     raeburn  5039: #
1.423     raeburn  5040: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5041: #
                   5042: # Formal Parameters:
                   5043: #   $cmd          - The command request that got us dispatched.
                   5044: #   $tail         - The tail of the command.  In this case,
                   5045: #                   this is a colon separated set of words that will be split
                   5046: #                   into:
1.424     raeburn  5047: #                        $dom      - The domain for which the check of 
                   5048: #                                    institutional course code will occur.
                   5049: #
                   5050: #                        $instcode - The institutional code for the course
                   5051: #                                    being requested, or validated for rights
                   5052: #                                    to request.
                   5053: #
                   5054: #                        $owner    - The course requestor (who will be the
                   5055: #                                    course owner, in the form username:domain
                   5056: #
1.417     raeburn  5057: #   $client       - Socket open on the client.
                   5058: # Returns:
                   5059: #    1           - Indicating processing should continue.
                   5060: #
                   5061: sub validate_instcode_handler {
                   5062:     my ($cmd, $tail, $client) = @_;
                   5063:     my $userinput = "$cmd:$tail";
1.423     raeburn  5064:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5065:     $instcode = &unescape($instcode);
                   5066:     $owner = &unescape($owner);
1.489.2.3  raeburn  5067:     my ($outcome,$description,$credits) = 
1.426     raeburn  5068:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.489.2.3  raeburn  5069:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5070:                  &escape($credits);
1.426     raeburn  5071:     &Reply($client, \$result, $userinput);
1.417     raeburn  5072: 
                   5073:     return 1;
                   5074: }
                   5075: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5076: 
1.248     foxr     5077: #   Get the official sections for which auto-enrollment is possible.
                   5078: #   Since the admin people won't know about 'unofficial sections' 
                   5079: #   we cannot auto-enroll on them.
                   5080: # Formal Parameters:
                   5081: #    $cmd     - The command request that got us dispatched here.
                   5082: #    $tail    - The remainder of the request.  In our case this
                   5083: #               will be split into:
                   5084: #               $coursecode   - The course name from the admin point of view.
                   5085: #               $cdom         - The course's domain(?).
                   5086: #    $client  - Socket open on the client.
                   5087: # Returns:
                   5088: #    1    - Indiciting processing should continue.
                   5089: #
                   5090: sub get_sections_handler {
                   5091:     my ($cmd, $tail, $client) = @_;
                   5092:     my $userinput = "$cmd:$tail";
                   5093: 
                   5094:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5095:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5096:     my $seclist = &escape(join(':',@secs));
                   5097: 
1.387     albertel 5098:     &Reply($client, \$seclist, $userinput);
1.248     foxr     5099:     
                   5100: 
                   5101:     return 1;
                   5102: }
                   5103: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   5104: 
                   5105: #   Validate the owner of a new course section.  
                   5106: #
                   5107: # Formal Parameters:
                   5108: #   $cmd      - Command that got us dispatched.
                   5109: #   $tail     - the remainder of the command.  For us this consists of a
                   5110: #               colon separated string containing:
                   5111: #                  $inst    - Course Id from the institutions point of view.
                   5112: #                  $owner   - Proposed owner of the course.
                   5113: #                  $cdom    - Domain of the course (from the institutions
                   5114: #                             point of view?)..
                   5115: #   $client   - Socket open on the client.
                   5116: #
                   5117: # Returns:
                   5118: #   1        - Processing should continue.
                   5119: #
                   5120: sub validate_course_owner_handler {
                   5121:     my ($cmd, $tail, $client)  = @_;
                   5122:     my $userinput = "$cmd:$tail";
1.470     raeburn  5123:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   5124:     
1.336     raeburn  5125:     $owner = &unescape($owner);
1.470     raeburn  5126:     $coowners = &unescape($coowners);
                   5127:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 5128:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5129: 
                   5130: 
                   5131: 
                   5132:     return 1;
                   5133: }
                   5134: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 5135: 
1.248     foxr     5136: #
                   5137: #   Validate a course section in the official schedule of classes
                   5138: #   from the institutions point of view (part of autoenrollment).
                   5139: #
                   5140: # Formal Parameters:
                   5141: #   $cmd          - The command request that got us dispatched.
                   5142: #   $tail         - The tail of the command.  In this case,
                   5143: #                   this is a colon separated set of words that will be split
                   5144: #                   into:
                   5145: #                        $inst_course_id - The course/section id from the
                   5146: #                                          institutions point of view.
                   5147: #                        $cdom           - The domain from the institutions
                   5148: #                                          point of view.
                   5149: #   $client       - Socket open on the client.
                   5150: # Returns:
                   5151: #    1           - Indicating processing should continue.
                   5152: #
                   5153: sub validate_course_section_handler {
                   5154:     my ($cmd, $tail, $client) = @_;
                   5155:     my $userinput = "$cmd:$tail";
                   5156:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   5157: 
                   5158:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 5159:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5160: 
                   5161: 
                   5162:     return 1;
                   5163: }
                   5164: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   5165: 
                   5166: #
1.340     raeburn  5167: #   Validate course owner's access to enrollment data for specific class section. 
                   5168: #   
                   5169: #
                   5170: # Formal Parameters:
                   5171: #    $cmd     - The command request that got us dispatched.
                   5172: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5173: #               set of words that will be split into:
                   5174: #               $inst_class  - Institutional code for the specific class section   
                   5175: #               $courseowner - The escaped username:domain of the course owner 
                   5176: #               $cdom        - The domain of the course from the institution's
                   5177: #                              point of view.
                   5178: #    $client  - The socket open on the client.
                   5179: # Returns:
                   5180: #    1 - continue processing.
                   5181: #
                   5182: 
                   5183: sub validate_class_access_handler {
                   5184:     my ($cmd, $tail, $client) = @_;
                   5185:     my $userinput = "$cmd:$tail";
1.383     raeburn  5186:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  5187:     my $owners = &unescape($ownerlist);
1.341     albertel 5188:     my $outcome;
                   5189:     eval {
                   5190: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  5191: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 5192:     };
1.387     albertel 5193:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  5194: 
                   5195:     return 1;
                   5196: }
                   5197: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   5198: 
                   5199: #
                   5200: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   5201: #   Only used for case where authentication method for new user is localauth
1.248     foxr     5202: #
                   5203: # Formal Parameters:
                   5204: #    $cmd     - The command request that got us dispatched.
                   5205: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5206: #               set of words that will be split into:
1.340     raeburn  5207: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     5208: #               $cdom      - The domain of the course from the institution's
                   5209: #                            point of view.
                   5210: #    $client  - The socket open on the client.
                   5211: # Returns:
                   5212: #    1 - continue processing.
                   5213: #
                   5214: sub create_auto_enroll_password_handler {
                   5215:     my ($cmd, $tail, $client) = @_;
                   5216:     my $userinput = "$cmd:$tail";
                   5217: 
                   5218:     my ($authparam, $cdom) = split(/:/, $userinput);
                   5219: 
                   5220:     my ($create_passwd,$authchk);
                   5221:     ($authparam,
                   5222:      $create_passwd,
                   5223:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   5224: 
                   5225:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   5226: 	   $userinput);
                   5227: 
                   5228: 
                   5229:     return 1;
                   5230: }
                   5231: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   5232: 		  0, 1, 0);
                   5233: 
                   5234: #   Retrieve and remove temporary files created by/during autoenrollment.
                   5235: #
                   5236: # Formal Parameters:
                   5237: #    $cmd      - The command that got us dispatched.
                   5238: #    $tail     - The tail of the command.  In our case this is a colon 
                   5239: #                separated list that will be split into:
                   5240: #                $filename - The name of the file to remove.
                   5241: #                            The filename is given as a path relative to
                   5242: #                            the LonCAPA temp file directory.
                   5243: #    $client   - Socket open on the client.
                   5244: #
                   5245: # Returns:
                   5246: #   1     - Continue processing.
                   5247: sub retrieve_auto_file_handler {
                   5248:     my ($cmd, $tail, $client)    = @_;
                   5249:     my $userinput                = "cmd:$tail";
                   5250: 
                   5251:     my ($filename)   = split(/:/, $tail);
                   5252: 
                   5253:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
                   5254:     if ( (-e $source) && ($filename ne '') ) {
                   5255: 	my $reply = '';
                   5256: 	if (open(my $fh,$source)) {
                   5257: 	    while (<$fh>) {
                   5258: 		chomp($_);
                   5259: 		$_ =~ s/^\s+//g;
                   5260: 		$_ =~ s/\s+$//g;
                   5261: 		$reply .= $_;
                   5262: 	    }
                   5263: 	    close($fh);
                   5264: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   5265: 
                   5266: #   Does this have to be uncommented??!?  (RF).
                   5267: #
                   5268: #                                unlink($source);
                   5269: 	} else {
                   5270: 	    &Failure($client, "error\n", $userinput);
                   5271: 	}
                   5272:     } else {
                   5273: 	&Failure($client, "error\n", $userinput);
                   5274:     }
                   5275:     
                   5276: 
                   5277:     return 1;
                   5278: }
                   5279: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   5280: 
1.423     raeburn  5281: sub crsreq_checks_handler {
                   5282:     my ($cmd, $tail, $client) = @_;
                   5283:     my $userinput = "$cmd:$tail";
                   5284:     my $dom = $tail;
                   5285:     my $result;
1.489.2.12  raeburn  5286:     my @reqtypes = ('official','unofficial','community','textbook');
1.423     raeburn  5287:     eval {
                   5288:         local($SIG{__DIE__})='DEFAULT';
                   5289:         my %validations;
1.424     raeburn  5290:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   5291:                                                    \%validations);
1.423     raeburn  5292:         if ($response eq 'ok') { 
                   5293:             foreach my $key (keys(%validations)) {
                   5294:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   5295:             }
                   5296:             $result =~ s/\&$//;
                   5297:         } else {
                   5298:             $result = 'error';
                   5299:         }
                   5300:     };
                   5301:     if (!$@) {
                   5302:         &Reply($client, \$result, $userinput);
                   5303:     } else {
                   5304:         &Failure($client,"unknown_cmd\n",$userinput);
                   5305:     }
                   5306:     return 1;
                   5307: }
                   5308: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   5309: 
                   5310: sub validate_crsreq_handler {
                   5311:     my ($cmd, $tail, $client) = @_;
                   5312:     my $userinput = "$cmd:$tail";
1.489.2.13  raeburn  5313:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  5314:     $instcode = &unescape($instcode);
                   5315:     $owner = &unescape($owner);
                   5316:     $crstype = &unescape($crstype);
                   5317:     $inststatuslist = &unescape($inststatuslist);
                   5318:     $instcode = &unescape($instcode);
                   5319:     $instseclist = &unescape($instseclist);
1.489.2.13  raeburn  5320:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  5321:     my $outcome;
                   5322:     eval {
                   5323:         local($SIG{__DIE__})='DEFAULT';
                   5324:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   5325:                                                  $inststatuslist,$instcode,
1.489.2.13  raeburn  5326:                                                  $instseclist,$custominfo);
1.423     raeburn  5327:     };
                   5328:     if (!$@) {
                   5329:         &Reply($client, \$outcome, $userinput);
                   5330:     } else {
                   5331:         &Failure($client,"unknown_cmd\n",$userinput);
                   5332:     }
                   5333:     return 1;
                   5334: }
                   5335: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   5336: 
1.489.2.11  raeburn  5337: sub crsreq_update_handler {
                   5338:     my ($cmd, $tail, $client) = @_;
                   5339:     my $userinput = "$cmd:$tail";
1.489.2.14  raeburn  5340:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   5341:         $accessstart,$accessend,$infohashref) =
1.489.2.11  raeburn  5342:         split(/:/, $tail);
                   5343:     $crstype = &unescape($crstype);
                   5344:     $action = &unescape($action);
                   5345:     $ownername = &unescape($ownername);
                   5346:     $ownerdomain = &unescape($ownerdomain);
                   5347:     $fullname = &unescape($fullname);
                   5348:     $title = &unescape($title);
                   5349:     $code = &unescape($code);
1.489.2.14  raeburn  5350:     $accessstart = &unescape($accessstart);
                   5351:     $accessend = &unescape($accessend);
1.489.2.11  raeburn  5352:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   5353:     my ($result,$outcome);
                   5354:     eval {
                   5355:         local($SIG{__DIE__})='DEFAULT';
                   5356:         my %rtnhash;
                   5357:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   5358:                                                 $ownername,$ownerdomain,$fullname,
1.489.2.14  raeburn  5359:                                                 $title,$code,$accessstart,$accessend,
                   5360:                                                 $incoming,\%rtnhash);
1.489.2.11  raeburn  5361:         if ($outcome eq 'ok') {
                   5362:             my @posskeys = qw(createdweb createdmsg queuedweb queuedmsg formitems reviewweb);
                   5363:             foreach my $key (keys(%rtnhash)) {
                   5364:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   5365:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   5366:                 }
                   5367:             }
                   5368:             $result =~ s/\&$//;
                   5369:         }
                   5370:     };
                   5371:     if (!$@) {
                   5372:         if ($outcome eq 'ok') {
                   5373:             &Reply($client, \$result, $userinput);
                   5374:         } else {
                   5375:             &Reply($client, "format_error\n", $userinput);
                   5376:         }
                   5377:     } else {
                   5378:         &Failure($client,"unknown_cmd\n",$userinput);
                   5379:     }
                   5380:     return 1;
                   5381: }
                   5382: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   5383: 
1.248     foxr     5384: #
                   5385: #   Read and retrieve institutional code format (for support form).
                   5386: # Formal Parameters:
                   5387: #    $cmd        - Command that dispatched us.
                   5388: #    $tail       - Tail of the command.  In this case it conatins 
                   5389: #                  the course domain and the coursename.
                   5390: #    $client     - Socket open on the client.
                   5391: # Returns:
                   5392: #    1     - Continue processing.
                   5393: #
                   5394: sub get_institutional_code_format_handler {
                   5395:     my ($cmd, $tail, $client)   = @_;
                   5396:     my $userinput               = "$cmd:$tail";
                   5397: 
                   5398:     my $reply;
                   5399:     my($cdom,$course) = split(/:/,$tail);
                   5400:     my @pairs = split/\&/,$course;
                   5401:     my %instcodes = ();
                   5402:     my %codes = ();
                   5403:     my @codetitles = ();
                   5404:     my %cat_titles = ();
                   5405:     my %cat_order = ();
                   5406:     foreach (@pairs) {
                   5407: 	my ($key,$value) = split/=/,$_;
                   5408: 	$instcodes{&unescape($key)} = &unescape($value);
                   5409:     }
                   5410:     my $formatreply = &localenroll::instcode_format($cdom,
                   5411: 						    \%instcodes,
                   5412: 						    \%codes,
                   5413: 						    \@codetitles,
                   5414: 						    \%cat_titles,
                   5415: 						    \%cat_order);
                   5416:     if ($formatreply eq 'ok') {
1.365     albertel 5417: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   5418: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   5419: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   5420: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     5421: 	&Reply($client,
                   5422: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   5423: 	       .$cat_order_str."\n",
                   5424: 	       $userinput);
                   5425:     } else {
                   5426: 	# this else branch added by RF since if not ok, lonc will
                   5427: 	# hang waiting on reply until timeout.
                   5428: 	#
                   5429: 	&Reply($client, "format_error\n", $userinput);
                   5430:     }
                   5431:     
                   5432:     return 1;
                   5433: }
1.265     albertel 5434: &register_handler("autoinstcodeformat",
                   5435: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     5436: 
1.345     raeburn  5437: sub get_institutional_defaults_handler {
                   5438:     my ($cmd, $tail, $client)   = @_;
                   5439:     my $userinput               = "$cmd:$tail";
                   5440: 
                   5441:     my $dom = $tail;
                   5442:     my %defaults_hash;
                   5443:     my @code_order;
                   5444:     my $outcome;
                   5445:     eval {
                   5446:         local($SIG{__DIE__})='DEFAULT';
                   5447:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   5448:                                                    \@code_order);
                   5449:     };
                   5450:     if (!$@) {
                   5451:         if ($outcome eq 'ok') {
                   5452:             my $result='';
                   5453:             while (my ($key,$value) = each(%defaults_hash)) {
                   5454:                 $result.=&escape($key).'='.&escape($value).'&';
                   5455:             }
                   5456:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 5457:             &Reply($client,\$result,$userinput);
1.345     raeburn  5458:         } else {
                   5459:             &Reply($client,"error\n", $userinput);
                   5460:         }
                   5461:     } else {
                   5462:         &Failure($client,"unknown_cmd\n",$userinput);
                   5463:     }
                   5464: }
                   5465: &register_handler("autoinstcodedefaults",
                   5466:                   \&get_institutional_defaults_handler,0,1,0);
                   5467: 
1.416     raeburn  5468: sub get_possible_instcodes_handler {
                   5469:     my ($cmd, $tail, $client)   = @_;
                   5470:     my $userinput               = "$cmd:$tail";
                   5471: 
                   5472:     my $reply;
                   5473:     my $cdom = $tail;
1.417     raeburn  5474:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  5475:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   5476:                                                        \@codetitles,
                   5477:                                                        \%cat_titles,
1.417     raeburn  5478:                                                        \%cat_order,
                   5479:                                                        \@code_order);
1.416     raeburn  5480:     if ($formatreply eq 'ok') {
                   5481:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  5482:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  5483:         foreach my $key (keys(%cat_titles)) {
                   5484:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   5485:         }
                   5486:         $result =~ s/\&$//;
                   5487:         $result .= ':';
                   5488:         foreach my $key (keys(%cat_order)) {
                   5489:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   5490:         }
                   5491:         $result =~ s/\&$//;
                   5492:         &Reply($client,\$result,$userinput);
                   5493:     } else {
                   5494:         &Reply($client, "format_error\n", $userinput);
                   5495:     }
                   5496:     return 1;
                   5497: }
                   5498: &register_handler("autopossibleinstcodes",
                   5499:                   \&get_possible_instcodes_handler,0,1,0);
                   5500: 
1.381     raeburn  5501: sub get_institutional_user_rules {
                   5502:     my ($cmd, $tail, $client)   = @_;
                   5503:     my $userinput               = "$cmd:$tail";
                   5504:     my $dom = &unescape($tail);
                   5505:     my (%rules_hash,@rules_order);
                   5506:     my $outcome;
                   5507:     eval {
                   5508:         local($SIG{__DIE__})='DEFAULT';
                   5509:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   5510:     };
                   5511:     if (!$@) {
                   5512:         if ($outcome eq 'ok') {
                   5513:             my $result;
                   5514:             foreach my $key (keys(%rules_hash)) {
                   5515:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   5516:             }
                   5517:             $result =~ s/\&$//;
                   5518:             $result .= ':';
                   5519:             if (@rules_order > 0) {
                   5520:                 foreach my $item (@rules_order) {
                   5521:                     $result .= &escape($item).'&';
                   5522:                 }
                   5523:             }
                   5524:             $result =~ s/\&$//;
1.387     albertel 5525:             &Reply($client,\$result,$userinput);
1.381     raeburn  5526:         } else {
                   5527:             &Reply($client,"error\n", $userinput);
                   5528:         }
                   5529:     } else {
                   5530:         &Failure($client,"unknown_cmd\n",$userinput);
                   5531:     }
                   5532: }
                   5533: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   5534: 
1.389     raeburn  5535: sub get_institutional_id_rules {
                   5536:     my ($cmd, $tail, $client)   = @_;
                   5537:     my $userinput               = "$cmd:$tail";
                   5538:     my $dom = &unescape($tail);
                   5539:     my (%rules_hash,@rules_order);
                   5540:     my $outcome;
                   5541:     eval {
                   5542:         local($SIG{__DIE__})='DEFAULT';
                   5543:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   5544:     };
                   5545:     if (!$@) {
                   5546:         if ($outcome eq 'ok') {
                   5547:             my $result;
                   5548:             foreach my $key (keys(%rules_hash)) {
                   5549:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   5550:             }
                   5551:             $result =~ s/\&$//;
                   5552:             $result .= ':';
                   5553:             if (@rules_order > 0) {
                   5554:                 foreach my $item (@rules_order) {
                   5555:                     $result .= &escape($item).'&';
                   5556:                 }
                   5557:             }
                   5558:             $result =~ s/\&$//;
                   5559:             &Reply($client,\$result,$userinput);
                   5560:         } else {
                   5561:             &Reply($client,"error\n", $userinput);
                   5562:         }
                   5563:     } else {
                   5564:         &Failure($client,"unknown_cmd\n",$userinput);
                   5565:     }
                   5566: }
                   5567: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   5568: 
1.397     raeburn  5569: sub get_institutional_selfcreate_rules {
1.396     raeburn  5570:     my ($cmd, $tail, $client)   = @_;
                   5571:     my $userinput               = "$cmd:$tail";
                   5572:     my $dom = &unescape($tail);
                   5573:     my (%rules_hash,@rules_order);
                   5574:     my $outcome;
                   5575:     eval {
                   5576:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  5577:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  5578:     };
                   5579:     if (!$@) {
                   5580:         if ($outcome eq 'ok') {
                   5581:             my $result;
                   5582:             foreach my $key (keys(%rules_hash)) {
                   5583:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   5584:             }
                   5585:             $result =~ s/\&$//;
                   5586:             $result .= ':';
                   5587:             if (@rules_order > 0) {
                   5588:                 foreach my $item (@rules_order) {
                   5589:                     $result .= &escape($item).'&';
                   5590:                 }
                   5591:             }
                   5592:             $result =~ s/\&$//;
                   5593:             &Reply($client,\$result,$userinput);
                   5594:         } else {
                   5595:             &Reply($client,"error\n", $userinput);
                   5596:         }
                   5597:     } else {
                   5598:         &Failure($client,"unknown_cmd\n",$userinput);
                   5599:     }
                   5600: }
1.397     raeburn  5601: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  5602: 
1.381     raeburn  5603: 
                   5604: sub institutional_username_check {
                   5605:     my ($cmd, $tail, $client)   = @_;
                   5606:     my $userinput               = "$cmd:$tail";
                   5607:     my %rulecheck;
                   5608:     my $outcome;
                   5609:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   5610:     $udom = &unescape($udom);
                   5611:     $uname = &unescape($uname);
                   5612:     @rules = map {&unescape($_);} (@rules);
                   5613:     eval {
                   5614:         local($SIG{__DIE__})='DEFAULT';
                   5615:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   5616:     };
                   5617:     if (!$@) {
                   5618:         if ($outcome eq 'ok') {
                   5619:             my $result='';
                   5620:             foreach my $key (keys(%rulecheck)) {
                   5621:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   5622:             }
1.387     albertel 5623:             &Reply($client,\$result,$userinput);
1.381     raeburn  5624:         } else {
                   5625:             &Reply($client,"error\n", $userinput);
                   5626:         }
                   5627:     } else {
                   5628:         &Failure($client,"unknown_cmd\n",$userinput);
                   5629:     }
                   5630: }
                   5631: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   5632: 
1.389     raeburn  5633: sub institutional_id_check {
                   5634:     my ($cmd, $tail, $client)   = @_;
                   5635:     my $userinput               = "$cmd:$tail";
                   5636:     my %rulecheck;
                   5637:     my $outcome;
                   5638:     my ($udom,$id,@rules) = split(/:/,$tail);
                   5639:     $udom = &unescape($udom);
                   5640:     $id = &unescape($id);
                   5641:     @rules = map {&unescape($_);} (@rules);
                   5642:     eval {
                   5643:         local($SIG{__DIE__})='DEFAULT';
                   5644:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   5645:     };
                   5646:     if (!$@) {
                   5647:         if ($outcome eq 'ok') {
                   5648:             my $result='';
                   5649:             foreach my $key (keys(%rulecheck)) {
                   5650:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   5651:             }
                   5652:             &Reply($client,\$result,$userinput);
                   5653:         } else {
                   5654:             &Reply($client,"error\n", $userinput);
                   5655:         }
                   5656:     } else {
                   5657:         &Failure($client,"unknown_cmd\n",$userinput);
                   5658:     }
                   5659: }
                   5660: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  5661: 
1.397     raeburn  5662: sub institutional_selfcreate_check {
1.396     raeburn  5663:     my ($cmd, $tail, $client)   = @_;
                   5664:     my $userinput               = "$cmd:$tail";
                   5665:     my %rulecheck;
                   5666:     my $outcome;
                   5667:     my ($udom,$email,@rules) = split(/:/,$tail);
                   5668:     $udom = &unescape($udom);
                   5669:     $email = &unescape($email);
                   5670:     @rules = map {&unescape($_);} (@rules);
                   5671:     eval {
                   5672:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  5673:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  5674:     };
                   5675:     if (!$@) {
                   5676:         if ($outcome eq 'ok') {
                   5677:             my $result='';
                   5678:             foreach my $key (keys(%rulecheck)) {
                   5679:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   5680:             }
                   5681:             &Reply($client,\$result,$userinput);
                   5682:         } else {
                   5683:             &Reply($client,"error\n", $userinput);
                   5684:         }
                   5685:     } else {
                   5686:         &Failure($client,"unknown_cmd\n",$userinput);
                   5687:     }
                   5688: }
1.397     raeburn  5689: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  5690: 
1.317     raeburn  5691: # Get domain specific conditions for import of student photographs to a course
                   5692: #
                   5693: # Retrieves information from photo_permission subroutine in localenroll.
                   5694: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   5695: # required to accept conditions of use (yes/no).
                   5696: #
                   5697: #    
                   5698: sub photo_permission_handler {
                   5699:     my ($cmd, $tail, $client)   = @_;
                   5700:     my $userinput               = "$cmd:$tail";
                   5701:     my $cdom = $tail;
                   5702:     my ($perm_reqd,$conditions);
1.320     albertel 5703:     my $outcome;
                   5704:     eval {
                   5705: 	local($SIG{__DIE__})='DEFAULT';
                   5706: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   5707: 						  \$conditions);
                   5708:     };
                   5709:     if (!$@) {
                   5710: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   5711: 	       $userinput);
                   5712:     } else {
                   5713: 	&Failure($client,"unknown_cmd\n",$userinput);
                   5714:     }
                   5715:     return 1;
1.317     raeburn  5716: }
                   5717: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   5718: 
                   5719: #
                   5720: # Checks if student photo is available for a user in the domain, in the user's
                   5721: # directory (in /userfiles/internal/studentphoto.jpg).
                   5722: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   5723: # the student's photo.   
                   5724: 
                   5725: sub photo_check_handler {
                   5726:     my ($cmd, $tail, $client)   = @_;
                   5727:     my $userinput               = "$cmd:$tail";
                   5728:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   5729:     $udom = &unescape($udom);
                   5730:     $uname = &unescape($uname);
                   5731:     $pid = &unescape($pid);
                   5732:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   5733:     if (!-e $path) {
                   5734:         &mkpath($path);
                   5735:     }
                   5736:     my $response;
                   5737:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   5738:     $result .= ':'.$response;
                   5739:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 5740:     return 1;
1.317     raeburn  5741: }
                   5742: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   5743: 
                   5744: #
                   5745: # Retrieve information from localenroll about whether to provide a button     
                   5746: # for users who have enbled import of student photos to initiate an 
                   5747: # update of photo files for registered students. Also include 
                   5748: # comment to display alongside button.  
                   5749: 
                   5750: sub photo_choice_handler {
                   5751:     my ($cmd, $tail, $client) = @_;
                   5752:     my $userinput             = "$cmd:$tail";
                   5753:     my $cdom                  = &unescape($tail);
1.320     albertel 5754:     my ($update,$comment);
                   5755:     eval {
                   5756: 	local($SIG{__DIE__})='DEFAULT';
                   5757: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   5758:     };
                   5759:     if (!$@) {
                   5760: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   5761:     } else {
                   5762: 	&Failure($client,"unknown_cmd\n",$userinput);
                   5763:     }
                   5764:     return 1;
1.317     raeburn  5765: }
                   5766: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   5767: 
1.265     albertel 5768: #
                   5769: # Gets a student's photo to exist (in the correct image type) in the user's 
                   5770: # directory.
                   5771: # Formal Parameters:
                   5772: #    $cmd     - The command request that got us dispatched.
                   5773: #    $tail    - A colon separated set of words that will be split into:
                   5774: #               $domain - student's domain
                   5775: #               $uname  - student username
                   5776: #               $type   - image type desired
                   5777: #    $client  - The socket open on the client.
                   5778: # Returns:
                   5779: #    1 - continue processing.
1.317     raeburn  5780: 
1.265     albertel 5781: sub student_photo_handler {
                   5782:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  5783:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 5784: 
1.317     raeburn  5785:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   5786:     my $filename = 'studentphoto.'.$ext;
                   5787:     if ($type eq 'thumbnail') {
                   5788:         $filename = 'studentphoto_tn.'.$ext;
                   5789:     }
                   5790:     if (-e $path.$filename) {
1.265     albertel 5791: 	&Reply($client,"ok\n","$cmd:$tail");
                   5792: 	return 1;
                   5793:     }
                   5794:     &mkpath($path);
1.317     raeburn  5795:     my $file;
                   5796:     if ($type eq 'thumbnail') {
1.320     albertel 5797: 	eval {
                   5798: 	    local($SIG{__DIE__})='DEFAULT';
                   5799: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   5800: 	};
1.317     raeburn  5801:     } else {
                   5802:         $file=&localstudentphoto::fetch($domain,$uname);
                   5803:     }
1.265     albertel 5804:     if (!$file) {
                   5805: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   5806: 	return 1;
                   5807:     }
1.317     raeburn  5808:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   5809:     if (-e $path.$filename) {
1.265     albertel 5810: 	&Reply($client,"ok\n","$cmd:$tail");
                   5811: 	return 1;
                   5812:     }
                   5813:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   5814:     return 1;
                   5815: }
                   5816: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     5817: 
1.361     raeburn  5818: sub inst_usertypes_handler {
                   5819:     my ($cmd, $domain, $client) = @_;
                   5820:     my $res;
                   5821:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 5822:     my (%typeshash,@order,$result);
                   5823:     eval {
                   5824: 	local($SIG{__DIE__})='DEFAULT';
                   5825: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   5826:     };
                   5827:     if ($result eq 'ok') {
1.361     raeburn  5828:         if (keys(%typeshash) > 0) {
                   5829:             foreach my $key (keys(%typeshash)) {
                   5830:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   5831:             }
                   5832:         }
                   5833:         $res=~s/\&$//;
                   5834:         $res .= ':';
                   5835:         if (@order > 0) {
                   5836:             foreach my $item (@order) {
                   5837:                 $res .= &escape($item).'&';
                   5838:             }
                   5839:         }
                   5840:         $res=~s/\&$//;
                   5841:     }
1.387     albertel 5842:     &Reply($client, \$res, $userinput);
1.361     raeburn  5843:     return 1;
                   5844: }
                   5845: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   5846: 
1.264     albertel 5847: # mkpath makes all directories for a file, expects an absolute path with a
                   5848: # file or a trailing / if just a dir is passed
                   5849: # returns 1 on success 0 on failure
                   5850: sub mkpath {
                   5851:     my ($file)=@_;
                   5852:     my @parts=split(/\//,$file,-1);
                   5853:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   5854:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 5855: 	$now.='/'.$parts[$i]; 
1.264     albertel 5856: 	if (!-e $now) {
                   5857: 	    if  (!mkdir($now,0770)) { return 0; }
                   5858: 	}
                   5859:     }
                   5860:     return 1;
                   5861: }
                   5862: 
1.207     foxr     5863: #---------------------------------------------------------------
                   5864: #
                   5865: #   Getting, decoding and dispatching requests:
                   5866: #
                   5867: #
                   5868: #   Get a Request:
                   5869: #   Gets a Request message from the client.  The transaction
                   5870: #   is defined as a 'line' of text.  We remove the new line
                   5871: #   from the text line.  
1.226     foxr     5872: #
1.211     albertel 5873: sub get_request {
1.207     foxr     5874:     my $input = <$client>;
                   5875:     chomp($input);
1.226     foxr     5876: 
1.234     foxr     5877:     &Debug("get_request: Request = $input\n");
1.207     foxr     5878: 
                   5879:     &status('Processing '.$clientname.':'.$input);
                   5880: 
                   5881:     return $input;
                   5882: }
1.212     foxr     5883: #---------------------------------------------------------------
                   5884: #
                   5885: #  Process a request.  This sub should shrink as each action
                   5886: #  gets farmed out into a separat sub that is registered 
                   5887: #  with the dispatch hash.  
                   5888: #
                   5889: # Parameters:
                   5890: #    user_input   - The request received from the client (lonc).
                   5891: # Returns:
                   5892: #    true to keep processing, false if caller should exit.
                   5893: #
                   5894: sub process_request {
                   5895:     my ($userinput) = @_;      # Easier for now to break style than to
                   5896:                                 # fix all the userinput -> user_input.
                   5897:     my $wasenc    = 0;		# True if request was encrypted.
                   5898: # ------------------------------------------------------------ See if encrypted
1.322     albertel 5899:     # for command
                   5900:     # sethost:<server>
                   5901:     # <command>:<args>
                   5902:     #   we just send it to the processor
                   5903:     # for
                   5904:     # sethost:<server>:<command>:<args>
                   5905:     #  we do the implict set host and then do the command
                   5906:     if ($userinput =~ /^sethost:/) {
                   5907: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   5908: 	if (defined($userinput)) {
                   5909: 	    &sethost("$cmd:$newid");
                   5910: 	} else {
                   5911: 	    $userinput = "$cmd:$newid";
                   5912: 	}
                   5913:     }
                   5914: 
1.212     foxr     5915:     if ($userinput =~ /^enc/) {
                   5916: 	$userinput = decipher($userinput);
                   5917: 	$wasenc=1;
                   5918: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     5919: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     5920: 	    return 0;
                   5921: 	}
                   5922:     }
                   5923:     Debug("process_request: $userinput\n");
                   5924:     
1.213     foxr     5925:     #  
                   5926:     #   The 'correct way' to add a command to lond is now to
                   5927:     #   write a sub to execute it and Add it to the command dispatch
                   5928:     #   hash via a call to register_handler..  The comments to that
                   5929:     #   sub should give you enough to go on to show how to do this
                   5930:     #   along with the examples that are building up as this code
                   5931:     #   is getting refactored.   Until all branches of the
                   5932:     #   if/elseif monster below have been factored out into
                   5933:     #   separate procesor subs, if the dispatch hash is missing
                   5934:     #   the command keyword, we will fall through to the remainder
                   5935:     #   of the if/else chain below in order to keep this thing in 
                   5936:     #   working order throughout the transmogrification.
                   5937: 
                   5938:     my ($command, $tail) = split(/:/, $userinput, 2);
                   5939:     chomp($command);
                   5940:     chomp($tail);
                   5941:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     5942:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   5943:     if(!$tail) {
                   5944: 	$tail ="";		# defined but blank.
                   5945:     }
1.213     foxr     5946: 
                   5947:     &Debug("Command received: $command, encoded = $wasenc");
                   5948: 
                   5949:     if(defined $Dispatcher{$command}) {
                   5950: 
                   5951: 	my $dispatch_info = $Dispatcher{$command};
                   5952: 	my $handler       = $$dispatch_info[0];
                   5953: 	my $need_encode   = $$dispatch_info[1];
                   5954: 	my $client_types  = $$dispatch_info[2];
                   5955: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   5956: 	      ."ClientType $client_types");
                   5957:       
                   5958: 	#  Validate the request:
                   5959:       
                   5960: 	my $ok = 1;
                   5961: 	my $requesterprivs = 0;
                   5962: 	if(&isClient()) {
                   5963: 	    $requesterprivs |= $CLIENT_OK;
                   5964: 	}
                   5965: 	if(&isManager()) {
                   5966: 	    $requesterprivs |= $MANAGER_OK;
                   5967: 	}
                   5968: 	if($need_encode && (!$wasenc)) {
                   5969: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   5970: 	    $ok = 0;
                   5971: 	}
                   5972: 	if(($client_types & $requesterprivs) == 0) {
                   5973: 	    Debug("Client not privileged to do this operation");
                   5974: 	    $ok = 0;
                   5975: 	}
                   5976: 
                   5977: 	if($ok) {
                   5978: 	    Debug("Dispatching to handler $command $tail");
                   5979: 	    my $keep_going = &$handler($command, $tail, $client);
                   5980: 	    return $keep_going;
                   5981: 	} else {
                   5982: 	    Debug("Refusing to dispatch because client did not match requirements");
                   5983: 	    Failure($client, "refused\n", $userinput);
                   5984: 	    return 1;
                   5985: 	}
                   5986: 
                   5987:     }    
                   5988: 
1.262     foxr     5989:     print $client "unknown_cmd\n";
1.212     foxr     5990: # -------------------------------------------------------------------- complete
                   5991:     Debug("process_request - returning 1");
                   5992:     return 1;
                   5993: }
1.207     foxr     5994: #
                   5995: #   Decipher encoded traffic
                   5996: #  Parameters:
                   5997: #     input      - Encoded data.
                   5998: #  Returns:
                   5999: #     Decoded data or undef if encryption key was not yet negotiated.
                   6000: #  Implicit input:
                   6001: #     cipher  - This global holds the negotiated encryption key.
                   6002: #
1.211     albertel 6003: sub decipher {
1.207     foxr     6004:     my ($input)  = @_;
                   6005:     my $output = '';
1.212     foxr     6006:     
                   6007:     
1.207     foxr     6008:     if($cipher) {
                   6009: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   6010: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   6011: 	    $output .= 
                   6012: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   6013: 	}
                   6014: 	return substr($output, 0, $enclength);
                   6015:     } else {
                   6016: 	return undef;
                   6017:     }
                   6018: }
                   6019: 
                   6020: #
                   6021: #   Register a command processor.  This function is invoked to register a sub
                   6022: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   6023: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   6024: #   as well:
                   6025: #    - Is the keyword recognized.
                   6026: #    - Is the proper client type attempting the request.
                   6027: #    - Is the request encrypted if it has to be.
                   6028: #   Parameters:
                   6029: #    $request_name         - Name of the request being registered.
                   6030: #                           This is the command request that will match
                   6031: #                           against the hash keywords to lookup the information
                   6032: #                           associated with the dispatch information.
                   6033: #    $procedure           - Reference to a sub to call to process the request.
                   6034: #                           All subs get called as follows:
                   6035: #                             Procedure($cmd, $tail, $replyfd, $key)
                   6036: #                             $cmd    - the actual keyword that invoked us.
                   6037: #                             $tail   - the tail of the request that invoked us.
                   6038: #                             $replyfd- File descriptor connected to the client
                   6039: #    $must_encode          - True if the request must be encoded to be good.
                   6040: #    $client_ok            - True if it's ok for a client to request this.
                   6041: #    $manager_ok           - True if it's ok for a manager to request this.
                   6042: # Side effects:
                   6043: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   6044: #      - On failure, the program will die as it's a bad internal bug to try to 
                   6045: #        register a duplicate command handler.
                   6046: #
1.211     albertel 6047: sub register_handler {
1.212     foxr     6048:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     6049: 
                   6050:     #  Don't allow duplication#
                   6051:    
                   6052:     if (defined $Dispatcher{$request_name}) {
                   6053: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   6054:     }
                   6055:     #   Build the client type mask:
                   6056:     
                   6057:     my $client_type_mask = 0;
                   6058:     if($client_ok) {
                   6059: 	$client_type_mask  |= $CLIENT_OK;
                   6060:     }
                   6061:     if($manager_ok) {
                   6062: 	$client_type_mask  |= $MANAGER_OK;
                   6063:     }
                   6064:    
                   6065:     #  Enter the hash:
                   6066:       
                   6067:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   6068:    
                   6069:     $Dispatcher{$request_name} = \@entry;
                   6070:    
                   6071: }
                   6072: 
                   6073: 
                   6074: #------------------------------------------------------------------
                   6075: 
                   6076: 
                   6077: 
                   6078: 
1.141     foxr     6079: #
1.96      foxr     6080: #  Convert an error return code from lcpasswd to a string value.
                   6081: #
                   6082: sub lcpasswdstrerror {
                   6083:     my $ErrorCode = shift;
1.97      foxr     6084:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     6085: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   6086:     } else {
1.98      foxr     6087: 	return $passwderrors[$ErrorCode];
1.96      foxr     6088:     }
                   6089: }
                   6090: 
1.23      harris41 6091: # grabs exception and records it to log before exiting
                   6092: sub catchexception {
1.27      albertel 6093:     my ($error)=@_;
1.25      www      6094:     $SIG{'QUIT'}='DEFAULT';
                   6095:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 6096:     &status("Catching exception");
1.190     albertel 6097:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 6098:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 6099:      ."a crash with this error msg->[$error]</font>");
1.57      www      6100:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 6101:     if ($client) { print $client "error: $error\n"; }
1.59      www      6102:     $server->close();
1.27      albertel 6103:     die($error);
1.23      harris41 6104: }
1.63      www      6105: sub timeout {
1.165     albertel 6106:     &status("Handling Timeout");
1.190     albertel 6107:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      6108:     &catchexception('Timeout');
                   6109: }
1.22      harris41 6110: # -------------------------------- Set signal handlers to record abnormal exits
                   6111: 
1.226     foxr     6112: 
1.22      harris41 6113: $SIG{'QUIT'}=\&catchexception;
                   6114: $SIG{__DIE__}=\&catchexception;
                   6115: 
1.81      matthew  6116: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 6117: &status("Read loncapa.conf and loncapa_apache.conf");
                   6118: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     6119: %perlvar=%{$perlvarref};
1.80      harris41 6120: undef $perlvarref;
1.19      www      6121: 
1.35      harris41 6122: # ----------------------------- Make sure this process is running from user=www
                   6123: my $wwwid=getpwnam('www');
                   6124: if ($wwwid!=$<) {
1.134     albertel 6125:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   6126:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 6127:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 6128:  mailto $emailto -s '$subj' > /dev/null");
                   6129:    exit 1;
                   6130: }
                   6131: 
1.19      www      6132: # --------------------------------------------- Check if other instance running
                   6133: 
                   6134: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   6135: 
                   6136: if (-e $pidfile) {
                   6137:    my $lfh=IO::File->new("$pidfile");
                   6138:    my $pide=<$lfh>;
                   6139:    chomp($pide);
1.29      harris41 6140:    if (kill 0 => $pide) { die "already running"; }
1.19      www      6141: }
1.1       albertel 6142: 
                   6143: # ------------------------------------------------------------- Read hosts file
                   6144: 
                   6145: 
                   6146: 
                   6147: # establish SERVER socket, bind and listen.
                   6148: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   6149:                                 Type      => SOCK_STREAM,
                   6150:                                 Proto     => 'tcp',
1.469     foxr     6151:                                 ReuseAddr     => 1,
1.1       albertel 6152:                                 Listen    => 10 )
1.29      harris41 6153:   or die "making socket: $@\n";
1.1       albertel 6154: 
                   6155: # --------------------------------------------------------- Do global variables
                   6156: 
                   6157: # global variables
                   6158: 
1.134     albertel 6159: my %children               = ();       # keys are current child process IDs
1.1       albertel 6160: 
                   6161: sub REAPER {                        # takes care of dead children
                   6162:     $SIG{CHLD} = \&REAPER;
1.165     albertel 6163:     &status("Handling child death");
1.178     foxr     6164:     my $pid;
                   6165:     do {
                   6166: 	$pid = waitpid(-1,&WNOHANG());
                   6167: 	if (defined($children{$pid})) {
                   6168: 	    &logthis("Child $pid died");
                   6169: 	    delete($children{$pid});
1.183     albertel 6170: 	} elsif ($pid > 0) {
1.178     foxr     6171: 	    &logthis("Unknown Child $pid died");
                   6172: 	}
                   6173:     } while ( $pid > 0 );
                   6174:     foreach my $child (keys(%children)) {
                   6175: 	$pid = waitpid($child,&WNOHANG());
                   6176: 	if ($pid > 0) {
                   6177: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   6178: 	    delete($children{$pid});
                   6179: 	}
1.176     albertel 6180:     }
1.165     albertel 6181:     &status("Finished Handling child death");
1.1       albertel 6182: }
                   6183: 
                   6184: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 6185:     &status("Killing children (INT)");
1.1       albertel 6186:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   6187:     kill 'INT' => keys %children;
1.59      www      6188:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 6189:     my $execdir=$perlvar{'lonDaemons'};
                   6190:     unlink("$execdir/logs/lond.pid");
1.190     albertel 6191:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 6192:     &status("Done killing children");
1.1       albertel 6193:     exit;                           # clean up with dignity
                   6194: }
                   6195: 
                   6196: sub HUPSMAN {                      # signal handler for SIGHUP
                   6197:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 6198:     &status("Killing children for restart (HUP)");
1.1       albertel 6199:     kill 'INT' => keys %children;
1.59      www      6200:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 6201:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 6202:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 6203:     unlink("$execdir/logs/lond.pid");
1.165     albertel 6204:     &status("Restarting self (HUP)");
1.1       albertel 6205:     exec("$execdir/lond");         # here we go again
                   6206: }
                   6207: 
1.144     foxr     6208: #
1.148     foxr     6209: #  Reload the Apache daemon's state.
1.150     foxr     6210: #  This is done by invoking /home/httpd/perl/apachereload
                   6211: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     6212: #
                   6213: sub ReloadApache {
1.473     raeburn  6214: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  6215:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   6216:         my $execdir = $perlvar{'lonDaemons'};
                   6217:         my $script  = $execdir."/apachereload";
                   6218:         system($script);
                   6219:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   6220:     }
1.148     foxr     6221: }
                   6222: 
                   6223: #
1.144     foxr     6224: #   Called in response to a USR2 signal.
                   6225: #   - Reread hosts.tab
                   6226: #   - All children connected to hosts that were removed from hosts.tab
                   6227: #     are killed via SIGINT
                   6228: #   - All children connected to previously existing hosts are sent SIGUSR1
                   6229: #   - Our internal hosts hash is updated to reflect the new contents of
                   6230: #     hosts.tab causing connections from hosts added to hosts.tab to
                   6231: #     now be honored.
                   6232: #
                   6233: sub UpdateHosts {
1.165     albertel 6234:     &status("Reload hosts.tab");
1.147     foxr     6235:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     6236:     #
                   6237:     #  The %children hash has the set of IP's we currently have children
                   6238:     #  on.  These need to be matched against records in the hosts.tab
                   6239:     #  Any ip's no longer in the table get killed off they correspond to
                   6240:     #  either dropped or changed hosts.  Note that the re-read of the table
                   6241:     #  will take care of new and changed hosts as connections come into being.
                   6242: 
1.371     albertel 6243:     &Apache::lonnet::reset_hosts_info();
1.148     foxr     6244: 
1.368     albertel 6245:     foreach my $child (keys(%children)) {
1.148     foxr     6246: 	my $childip = $children{$child};
1.374     albertel 6247: 	if ($childip ne '127.0.0.1'
                   6248: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     6249: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   6250: 		    ." $child for ip $childip </font>");
1.148     foxr     6251: 	    kill('INT', $child);
1.149     foxr     6252: 	} else {
                   6253: 	    logthis('<font color="green"> keeping child for ip '
                   6254: 		    ." $childip (pid=$child) </font>");
1.148     foxr     6255: 	}
                   6256:     }
                   6257:     ReloadApache;
1.165     albertel 6258:     &status("Finished reloading hosts.tab");
1.144     foxr     6259: }
                   6260: 
1.148     foxr     6261: 
1.57      www      6262: sub checkchildren {
1.165     albertel 6263:     &status("Checking on the children (sending signals)");
1.57      www      6264:     &initnewstatus();
                   6265:     &logstatus();
                   6266:     &logthis('Going to check on the children');
1.134     albertel 6267:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 6268:     foreach (sort keys %children) {
1.221     albertel 6269: 	#sleep 1;
1.57      www      6270:         unless (kill 'USR1' => $_) {
                   6271: 	    &logthis ('Child '.$_.' is dead');
                   6272:             &logstatus($$.' is dead');
1.221     albertel 6273: 	    delete($children{$_});
1.57      www      6274:         } 
1.61      harris41 6275:     }
1.63      www      6276:     sleep 5;
1.212     foxr     6277:     $SIG{ALRM} = sub { Debug("timeout"); 
                   6278: 		       die "timeout";  };
1.113     albertel 6279:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 6280:     &status("Checking on the children (waiting for reports)");
1.63      www      6281:     foreach (sort keys %children) {
                   6282:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 6283:           eval {
                   6284:             alarm(300);
1.63      www      6285: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 6286: 	    kill 9 => $_;
1.131     albertel 6287: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   6288: 	    #$subj="LON: $currenthostid killed lond process $_";
                   6289: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   6290: 	    #$execdir=$perlvar{'lonDaemons'};
                   6291: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 6292: 	    delete($children{$_});
1.113     albertel 6293: 	    alarm(0);
                   6294: 	  }
1.63      www      6295:         }
                   6296:     }
1.113     albertel 6297:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 6298:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 6299:     &status("Finished checking children");
1.221     albertel 6300:     &logthis('Finished Checking children');
1.57      www      6301: }
                   6302: 
1.1       albertel 6303: # --------------------------------------------------------------------- Logging
                   6304: 
                   6305: sub logthis {
                   6306:     my $message=shift;
                   6307:     my $execdir=$perlvar{'lonDaemons'};
                   6308:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   6309:     my $now=time;
                   6310:     my $local=localtime($now);
1.58      www      6311:     $lastlog=$local.': '.$message;
1.1       albertel 6312:     print $fh "$local ($$): $message\n";
                   6313: }
                   6314: 
1.77      foxr     6315: # ------------------------- Conditional log if $DEBUG true.
                   6316: sub Debug {
                   6317:     my $message = shift;
                   6318:     if($DEBUG) {
                   6319: 	&logthis($message);
                   6320:     }
                   6321: }
1.161     foxr     6322: 
                   6323: #
                   6324: #   Sub to do replies to client.. this gives a hook for some
                   6325: #   debug tracing too:
                   6326: #  Parameters:
                   6327: #     fd      - File open on client.
                   6328: #     reply   - Text to send to client.
                   6329: #     request - Original request from client.
                   6330: #
                   6331: sub Reply {
1.192     foxr     6332:     my ($fd, $reply, $request) = @_;
1.387     albertel 6333:     if (ref($reply)) {
                   6334: 	print $fd $$reply;
                   6335: 	print $fd "\n";
                   6336: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   6337:     } else {
                   6338: 	print $fd $reply;
                   6339: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   6340:     }
1.212     foxr     6341:     $Transactions++;
                   6342: }
                   6343: 
                   6344: 
                   6345: #
                   6346: #    Sub to report a failure.
                   6347: #    This function:
                   6348: #     -   Increments the failure statistic counters.
                   6349: #     -   Invokes Reply to send the error message to the client.
                   6350: # Parameters:
                   6351: #    fd       - File descriptor open on the client
                   6352: #    reply    - Reply text to emit.
                   6353: #    request  - The original request message (used by Reply
                   6354: #               to debug if that's enabled.
                   6355: # Implicit outputs:
                   6356: #    $Failures- The number of failures is incremented.
                   6357: #    Reply (invoked here) sends a message to the 
                   6358: #    client:
                   6359: #
                   6360: sub Failure {
                   6361:     my $fd      = shift;
                   6362:     my $reply   = shift;
                   6363:     my $request = shift;
                   6364:    
                   6365:     $Failures++;
                   6366:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     6367: }
1.57      www      6368: # ------------------------------------------------------------------ Log status
                   6369: 
                   6370: sub logstatus {
1.178     foxr     6371:     &status("Doing logging");
                   6372:     my $docdir=$perlvar{'lonDocRoot'};
                   6373:     {
                   6374: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  6375:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     6376:         $fh->close();
                   6377:     }
1.221     albertel 6378:     &status("Finished $$.txt");
                   6379:     {
                   6380: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   6381: 	flock(LOG,LOCK_EX);
                   6382: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   6383: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 6384: 	flock(LOG,LOCK_UN);
1.221     albertel 6385: 	close(LOG);
                   6386:     }
1.178     foxr     6387:     &status("Finished logging");
1.57      www      6388: }
                   6389: 
                   6390: sub initnewstatus {
                   6391:     my $docdir=$perlvar{'lonDocRoot'};
                   6392:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     6393:     my $now=time();
1.57      www      6394:     my $local=localtime($now);
                   6395:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      6396:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 6397:     while (my $filename=readdir(DIR)) {
1.64      www      6398:         unlink("$docdir/lon-status/londchld/$filename");
                   6399:     }
                   6400:     closedir(DIR);
1.57      www      6401: }
                   6402: 
                   6403: # -------------------------------------------------------------- Status setting
                   6404: 
                   6405: sub status {
                   6406:     my $what=shift;
                   6407:     my $now=time;
                   6408:     my $local=localtime($now);
1.178     foxr     6409:     $status=$local.': '.$what;
                   6410:     $0='lond: '.$what.' '.$local;
1.57      www      6411: }
1.11      www      6412: 
1.13      www      6413: # -------------------------------------------------------------- Talk to lonsql
                   6414: 
1.234     foxr     6415: sub sql_reply {
1.12      harris41 6416:     my ($cmd)=@_;
1.234     foxr     6417:     my $answer=&sub_sql_reply($cmd);
                   6418:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 6419:     return $answer;
                   6420: }
                   6421: 
1.234     foxr     6422: sub sub_sql_reply {
1.12      harris41 6423:     my ($cmd)=@_;
                   6424:     my $unixsock="mysqlsock";
                   6425:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   6426:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   6427:                                       Type    => SOCK_STREAM,
                   6428:                                       Timeout => 10)
                   6429:        or return "con_lost";
1.319     www      6430:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 6431:     my $answer=<$sclient>;
                   6432:     chomp($answer);
                   6433:     if (!$answer) { $answer="con_lost"; }
                   6434:     return $answer;
                   6435: }
                   6436: 
1.1       albertel 6437: # --------------------------------------- Is this the home server of an author?
1.11      www      6438: 
1.1       albertel 6439: sub ishome {
                   6440:     my $author=shift;
                   6441:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   6442:     my ($udom,$uname)=split(/\//,$author);
                   6443:     my $proname=propath($udom,$uname);
                   6444:     if (-e $proname) {
                   6445: 	return 'owner';
                   6446:     } else {
                   6447:         return 'not_owner';
                   6448:     }
                   6449: }
                   6450: 
                   6451: # ======================================================= Continue main program
                   6452: # ---------------------------------------------------- Fork once and dissociate
                   6453: 
1.134     albertel 6454: my $fpid=fork;
1.1       albertel 6455: exit if $fpid;
1.29      harris41 6456: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 6457: 
1.29      harris41 6458: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 6459: 
                   6460: # ------------------------------------------------------- Write our PID on disk
                   6461: 
1.134     albertel 6462: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 6463: open (PIDSAVE,">$execdir/logs/lond.pid");
                   6464: print PIDSAVE "$$\n";
                   6465: close(PIDSAVE);
1.190     albertel 6466: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      6467: &status('Starting');
1.1       albertel 6468: 
1.106     foxr     6469: 
1.1       albertel 6470: 
                   6471: # ----------------------------------------------------- Install signal handlers
                   6472: 
1.57      www      6473: 
1.1       albertel 6474: $SIG{CHLD} = \&REAPER;
                   6475: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   6476: $SIG{HUP}  = \&HUPSMAN;
1.57      www      6477: $SIG{USR1} = \&checkchildren;
1.144     foxr     6478: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     6479: 
1.148     foxr     6480: #  Read the host hashes:
1.368     albertel 6481: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  6482: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     6483: 
1.480     raeburn  6484: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 6485: 
1.471     raeburn  6486: my $arch = `uname -i`;
1.475     raeburn  6487: chomp($arch);
1.471     raeburn  6488: if ($arch eq 'unknown') {
                   6489:     $arch = `uname -m`;
1.475     raeburn  6490:     chomp($arch);
1.471     raeburn  6491: }
                   6492: 
1.106     foxr     6493: # --------------------------------------------------------------
                   6494: #   Accept connections.  When a connection comes in, it is validated
                   6495: #   and if good, a child process is created to process transactions
                   6496: #   along the connection.
                   6497: 
1.1       albertel 6498: while (1) {
1.165     albertel 6499:     &status('Starting accept');
1.106     foxr     6500:     $client = $server->accept() or next;
1.165     albertel 6501:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 6502:     make_new_child($client);
1.165     albertel 6503:     &status('Finished spawning');
1.1       albertel 6504: }
                   6505: 
1.212     foxr     6506: sub make_new_child {
                   6507:     my $pid;
                   6508: #    my $cipher;     # Now global
                   6509:     my $sigset;
1.178     foxr     6510: 
1.212     foxr     6511:     $client = shift;
                   6512:     &status('Starting new child '.$client);
                   6513:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   6514: 	     ")</font>");    
                   6515:     # block signal for fork
                   6516:     $sigset = POSIX::SigSet->new(SIGINT);
                   6517:     sigprocmask(SIG_BLOCK, $sigset)
                   6518:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     6519: 
1.212     foxr     6520:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     6521: 
1.212     foxr     6522:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   6523: 	                               # connection liveness.
1.178     foxr     6524: 
1.212     foxr     6525:     #
                   6526:     #  Figure out who we're talking to so we can record the peer in 
                   6527:     #  the pid hash.
                   6528:     #
                   6529:     my $caller = getpeername($client);
                   6530:     my ($port,$iaddr);
                   6531:     if (defined($caller) && length($caller) > 0) {
                   6532: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   6533:     } else {
                   6534: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   6535:     }
                   6536:     if (defined($iaddr)) {
                   6537: 	$clientip  = inet_ntoa($iaddr);
                   6538: 	Debug("Connected with $clientip");
                   6539:     } else {
                   6540: 	&logthis("Unable to determine clientip");
                   6541: 	$clientip='Unavailable';
                   6542:     }
                   6543:     
                   6544:     if ($pid) {
                   6545:         # Parent records the child's birth and returns.
                   6546:         sigprocmask(SIG_UNBLOCK, $sigset)
                   6547:             or die "Can't unblock SIGINT for fork: $!\n";
                   6548:         $children{$pid} = $clientip;
                   6549:         &status('Started child '.$pid);
1.462     foxr     6550: 	close($client);
1.212     foxr     6551:         return;
                   6552:     } else {
                   6553:         # Child can *not* return from this subroutine.
                   6554:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   6555:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   6556:                                 #don't get intercepted
                   6557:         $SIG{USR1}= \&logstatus;
                   6558:         $SIG{ALRM}= \&timeout;
1.468     foxr     6559: 	#
                   6560: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   6561: 	# deal with that as a read faiure instead.
                   6562: 	#
                   6563: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   6564: 	sigprocmask(SIG_BLOCK, $blockset);
                   6565: 
1.212     foxr     6566:         $lastlog='Forked ';
                   6567:         $status='Forked';
1.178     foxr     6568: 
1.212     foxr     6569:         # unblock signals
                   6570:         sigprocmask(SIG_UNBLOCK, $sigset)
                   6571:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     6572: 
1.212     foxr     6573: #        my $tmpsnum=0;            # Now global
                   6574: #---------------------------------------------------- kerberos 5 initialization
                   6575:         &Authen::Krb5::init_context();
1.489.2.16! raeburn  6576: 
        !          6577:         my $no_ets;
        !          6578:         if ($dist =~ /^(?:centos|rhes)(\d+)$/) {
        !          6579:             if ($1 >= 7) {
        !          6580:                 $no_ets = 1;
        !          6581:             }
        !          6582:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
        !          6583:             if (($1 eq '9.3') || ($1 >= 12.2)) {
        !          6584:                 $no_ets = 1;
        !          6585:             }
        !          6586:         } elsif ($dist =~ /^fedora(\d+)$/) {
        !          6587:             if ($1 < 7) {
        !          6588:                 $no_ets = 1;
        !          6589:             }
        !          6590:         }
        !          6591:         unless ($no_ets) {
        !          6592:             &Authen::Krb5::init_ets();
        !          6593:         }
1.209     albertel 6594: 
1.212     foxr     6595: 	&status('Accepted connection');
                   6596: # =============================================================================
                   6597:             # do something with the connection
                   6598: # -----------------------------------------------------------------------------
                   6599: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     6600: 
1.278     albertel 6601: 	my $outsideip=$clientip;
                   6602: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 6603: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 6604: 	}
1.412     foxr     6605: 	&ReadManagerTable();
1.368     albertel 6606: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 6607: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  6608: 	$clientname  = "[unknown]";
1.212     foxr     6609: 	if($clientrec) {	# Establish client type.
                   6610: 	    $ConnectionType = "client";
1.368     albertel 6611: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     6612: 	    if($ismanager) {
                   6613: 		$ConnectionType = "both";
                   6614: 	    }
                   6615: 	} else {
                   6616: 	    $ConnectionType = "manager";
1.278     albertel 6617: 	    $clientname = $managers{$outsideip};
1.212     foxr     6618: 	}
                   6619: 	my $clientok;
1.178     foxr     6620: 
1.212     foxr     6621: 	if ($clientrec || $ismanager) {
                   6622: 	    &status("Waiting for init from $clientip $clientname");
                   6623: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   6624: 		     $clientip.
                   6625: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   6626: 	    &status("Connecting $clientip  ($clientname))"); 
                   6627: 	    my $remotereq=<$client>;
                   6628: 	    chomp($remotereq);
                   6629: 	    Debug("Got init: $remotereq");
1.337     albertel 6630: 
1.212     foxr     6631: 	    if ($remotereq =~ /^init/) {
                   6632: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   6633: 		#
                   6634: 		#  If the remote is attempting a local init... give that a try:
                   6635: 		#
1.432     raeburn  6636: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.489.2.4  raeburn  6637:                 # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   6638:                 # version when initiating the connection. For LON-CAPA 2.8 and older,
                   6639:                 # the version is retrieved from the global %loncaparevs in lonnet.pm.
                   6640:                 # $clientversion contains path to keyfile if $inittype eq 'local'
                   6641:                 # it's overridden below in this case
                   6642:                 $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 6643: 
1.212     foxr     6644: 		# If the connection type is ssl, but I didn't get my
                   6645: 		# certificate files yet, then I'll drop  back to 
                   6646: 		# insecure (if allowed).
                   6647: 		
                   6648: 		if($inittype eq "ssl") {
                   6649: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   6650: 		    my $kfile       = lonssl::KeyFile;
                   6651: 		    if((!$ca)   || 
                   6652: 		       (!$cert) || 
                   6653: 		       (!$kfile)) {
                   6654: 			$inittype = ""; # This forces insecure attempt.
                   6655: 			&logthis("<font color=\"blue\"> Certificates not "
                   6656: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     6657: 		    } else {	# SSL certificates are in place so
1.212     foxr     6658: 		    }		# Leave the inittype alone.
                   6659: 		}
                   6660: 
                   6661: 		if($inittype eq "local") {
1.432     raeburn  6662:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     6663: 		    my $key = LocalConnection($client, $remotereq);
                   6664: 		    if($key) {
                   6665: 			Debug("Got local key $key");
                   6666: 			$clientok     = 1;
                   6667: 			my $cipherkey = pack("H32", $key);
                   6668: 			$cipher       = new IDEA($cipherkey);
                   6669: 			print $client "ok:local\n";
1.442     www      6670: 			&logthis('<font color="green">'
1.212     foxr     6671: 				 . "Successful local authentication </font>");
                   6672: 			$keymode = "local"
1.178     foxr     6673: 		    } else {
1.212     foxr     6674: 			Debug("Failed to get local key");
                   6675: 			$clientok = 0;
                   6676: 			shutdown($client, 3);
                   6677: 			close $client;
1.178     foxr     6678: 		    }
1.212     foxr     6679: 		} elsif ($inittype eq "ssl") {
                   6680: 		    my $key = SSLConnection($client);
                   6681: 		    if ($key) {
                   6682: 			$clientok = 1;
                   6683: 			my $cipherkey = pack("H32", $key);
                   6684: 			$cipher       = new IDEA($cipherkey);
                   6685: 			&logthis('<font color="green">'
                   6686: 				 ."Successfull ssl authentication with $clientname </font>");
                   6687: 			$keymode = "ssl";
                   6688: 	     
1.178     foxr     6689: 		    } else {
1.212     foxr     6690: 			$clientok = 0;
                   6691: 			close $client;
1.178     foxr     6692: 		    }
1.212     foxr     6693: 	   
                   6694: 		} else {
                   6695: 		    my $ok = InsecureConnection($client);
                   6696: 		    if($ok) {
                   6697: 			$clientok = 1;
                   6698: 			&logthis('<font color="green">'
                   6699: 				 ."Successful insecure authentication with $clientname </font>");
                   6700: 			print $client "ok\n";
                   6701: 			$keymode = "insecure";
1.178     foxr     6702: 		    } else {
1.212     foxr     6703: 			&logthis('<font color="yellow">'
                   6704: 				  ."Attempted insecure connection disallowed </font>");
                   6705: 			close $client;
                   6706: 			$clientok = 0;
1.178     foxr     6707: 			
                   6708: 		    }
                   6709: 		}
1.212     foxr     6710: 	    } else {
                   6711: 		&logthis(
                   6712: 			 "<font color='blue'>WARNING: "
                   6713: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   6714: 		&status('No init '.$clientip);
                   6715: 	    }
                   6716: 	    
                   6717: 	} else {
                   6718: 	    &logthis(
                   6719: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   6720: 	    &status('Hung up on '.$clientip);
                   6721: 	}
                   6722:  
                   6723: 	if ($clientok) {
                   6724: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 6725: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 6726: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 6727: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     6728: 	    }
                   6729: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   6730: 	    &status('Will listen to '.$clientname);
                   6731: # ------------------------------------------------------------ Process requests
                   6732: 	    my $keep_going = 1;
                   6733: 	    my $user_input;
1.448     raeburn  6734:             my $clienthost = &Apache::lonnet::hostname($clientname);
                   6735:             my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   6736:             $clienthomedom = &Apache::lonnet::host_domain($clientserverhomeID);
1.212     foxr     6737: 	    while(($user_input = get_request) && $keep_going) {
                   6738: 		alarm(120);
                   6739: 		Debug("Main: Got $user_input\n");
                   6740: 		$keep_going = &process_request($user_input);
1.178     foxr     6741: 		alarm(0);
1.212     foxr     6742: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     6743: 	    }
1.212     foxr     6744: 
1.59      www      6745: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     6746: 	}  else {
1.161     foxr     6747: 	    print $client "refused\n";
                   6748: 	    $client->close();
1.190     albertel 6749: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     6750: 		     ."Rejected client $clientip, closing connection</font>");
                   6751: 	}
1.212     foxr     6752:     }            
1.161     foxr     6753:     
1.1       albertel 6754: # =============================================================================
1.161     foxr     6755:     
1.190     albertel 6756:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     6757: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   6758:     
                   6759:     
                   6760:     # this exit is VERY important, otherwise the child will become
                   6761:     # a producer of more and more children, forking yourself into
                   6762:     # process death.
                   6763:     exit;
1.106     foxr     6764:     
1.78      foxr     6765: }
1.261     foxr     6766: #
                   6767: #   Determine if a user is an author for the indicated domain.
                   6768: #
                   6769: # Parameters:
                   6770: #    domain          - domain to check in .
                   6771: #    user            - Name of user to check.
                   6772: #
                   6773: # Return:
                   6774: #     1             - User is an author for domain.
                   6775: #     0             - User is not an author for domain.
                   6776: sub is_author {
                   6777:     my ($domain, $user) = @_;
                   6778: 
                   6779:     &Debug("is_author: $user @ $domain");
                   6780: 
                   6781:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   6782: 				 &GDBM_READER());
                   6783: 
                   6784:     #  Author role should show up as a key /domain/_au
1.78      foxr     6785: 
1.321     albertel 6786:     my $value;
1.487     foxr     6787:     if ($hashref) {
1.78      foxr     6788: 
1.487     foxr     6789: 	my $key    = "/$domain/_au";
                   6790: 	if (defined($hashref)) {
                   6791: 	    $value = $hashref->{$key};
                   6792: 	    if(!untie_user_hash($hashref)) {
                   6793: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   6794: 	    }
                   6795: 	}
                   6796: 	
                   6797: 	if(defined($value)) {
                   6798: 	    &Debug("$user @ $domain is an author");
                   6799: 	}
                   6800:     } else {
                   6801: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     6802:     }
                   6803: 
                   6804:     return defined($value);
                   6805: }
1.78      foxr     6806: #
                   6807: #   Checks to see if the input roleput request was to set
1.482     www      6808: # an author role.  If so, creates construction space 
1.78      foxr     6809: # Parameters:
                   6810: #    request   - The request sent to the rolesput subchunk.
                   6811: #                We're looking for  /domain/_au
                   6812: #    domain    - The domain in which the user is having roles doctored.
                   6813: #    user      - Name of the user for which the role is being put.
                   6814: #    authtype  - The authentication type associated with the user.
                   6815: #
1.289     albertel 6816: sub manage_permissions {
1.192     foxr     6817:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     6818:     # See if the request is of the form /$domain/_au
1.289     albertel 6819:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  6820:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      6821:         unless (-e $path) {        
                   6822:            mkdir($path);
                   6823:         }
                   6824:         unless (-e $path.'/'.$user) {
                   6825:            mkdir($path.'/'.$user);
                   6826:         }
1.78      foxr     6827:     }
                   6828: }
1.222     foxr     6829: 
                   6830: 
                   6831: #
                   6832: #  Return the full path of a user password file, whether it exists or not.
                   6833: # Parameters:
                   6834: #   domain     - Domain in which the password file lives.
                   6835: #   user       - name of the user.
                   6836: # Returns:
                   6837: #    Full passwd path:
                   6838: #
                   6839: sub password_path {
                   6840:     my ($domain, $user) = @_;
1.264     albertel 6841:     return &propath($domain, $user).'/passwd';
1.222     foxr     6842: }
                   6843: 
                   6844: #   Password Filename
                   6845: #   Returns the path to a passwd file given domain and user... only if
                   6846: #  it exists.
                   6847: # Parameters:
                   6848: #   domain    - Domain in which to search.
                   6849: #   user      - username.
                   6850: # Returns:
                   6851: #   - If the password file exists returns its path.
                   6852: #   - If the password file does not exist, returns undefined.
                   6853: #
                   6854: sub password_filename {
                   6855:     my ($domain, $user) = @_;
                   6856: 
                   6857:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   6858: 
                   6859:     my $path  = &password_path($domain, $user);
                   6860:     Debug("PasswordFilename got path: $path");
                   6861:     if(-e $path) {
                   6862: 	return $path;
                   6863:     } else {
                   6864: 	return undef;
                   6865:     }
                   6866: }
                   6867: 
                   6868: #
                   6869: #   Rewrite the contents of the user's passwd file.
                   6870: #  Parameters:
                   6871: #    domain    - domain of the user.
                   6872: #    name      - User's name.
                   6873: #    contents  - New contents of the file.
                   6874: # Returns:
                   6875: #   0    - Failed.
                   6876: #   1    - Success.
                   6877: #
                   6878: sub rewrite_password_file {
                   6879:     my ($domain, $user, $contents) = @_;
                   6880: 
                   6881:     my $file = &password_filename($domain, $user);
                   6882:     if (defined $file) {
                   6883: 	my $pf = IO::File->new(">$file");
                   6884: 	if($pf) {
                   6885: 	    print $pf "$contents\n";
                   6886: 	    return 1;
                   6887: 	} else {
                   6888: 	    return 0;
                   6889: 	}
                   6890:     } else {
                   6891: 	return 0;
                   6892:     }
                   6893: 
                   6894: }
                   6895: 
1.78      foxr     6896: #
1.222     foxr     6897: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     6898: 
                   6899: #     Returns the authorization type or nouser if there is no such user.
                   6900: #
1.436     raeburn  6901: sub get_auth_type {
1.192     foxr     6902:     my ($domain, $user)  = @_;
1.78      foxr     6903: 
1.222     foxr     6904:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     6905:     my $proname    = &propath($domain, $user); 
                   6906:     my $passwdfile = "$proname/passwd";
                   6907:     if( -e $passwdfile ) {
                   6908: 	my $pf = IO::File->new($passwdfile);
                   6909: 	my $realpassword = <$pf>;
                   6910: 	chomp($realpassword);
1.79      foxr     6911: 	Debug("Password info = $realpassword\n");
1.78      foxr     6912: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     6913: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  6914: 	return "$authtype:$contentpwd";     
1.224     foxr     6915:     } else {
1.79      foxr     6916: 	Debug("Returning nouser");
1.78      foxr     6917: 	return "nouser";
                   6918:     }
1.1       albertel 6919: }
                   6920: 
1.220     foxr     6921: #
                   6922: #  Validate a user given their domain, name and password.  This utility
                   6923: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   6924: #  to validate the login credentials of a user.
                   6925: # Parameters:
                   6926: #    $domain    - The domain being logged into (this is required due to
                   6927: #                 the capability for multihomed systems.
                   6928: #    $user      - The name of the user being validated.
                   6929: #    $password  - The user's propoposed password.
                   6930: #
                   6931: # Returns:
                   6932: #     1        - The domain,user,pasword triplet corresponds to a valid
                   6933: #                user.
                   6934: #     0        - The domain,user,password triplet is not a valid user.
                   6935: #
                   6936: sub validate_user {
1.396     raeburn  6937:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     6938: 
                   6939:     # Why negative ~pi you may well ask?  Well this function is about
                   6940:     # authentication, and therefore very important to get right.
                   6941:     # I've initialized the flag that determines whether or not I've 
                   6942:     # validated correctly to a value it's not supposed to get.
                   6943:     # At the end of this function. I'll ensure that it's not still that
                   6944:     # value so we don't just wind up returning some accidental value
                   6945:     # as a result of executing an unforseen code path that
1.249     foxr     6946:     # did not set $validated.  At the end of valid execution paths,
                   6947:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     6948: 
                   6949:     my $validated = -3.14159;
                   6950: 
                   6951:     #  How we authenticate is determined by the type of authentication
                   6952:     #  the user has been assigned.  If the authentication type is
                   6953:     #  "nouser", the user does not exist so we will return 0.
                   6954: 
1.222     foxr     6955:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     6956:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   6957: 
                   6958:     my $null = pack("C",0);	# Used by kerberos auth types.
                   6959: 
1.395     raeburn  6960:     if ($howpwd eq 'nouser') {
1.396     raeburn  6961:         if ($checkdefauth) {
                   6962:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   6963:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   6964:                 $howpwd = $domdefaults{'auth_def'};
                   6965:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   6966:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   6967:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   6968:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   6969:                 $howpwd = $domdefaults{'auth_def'};
                   6970:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   6971:             }
1.395     raeburn  6972:         }
                   6973:     } 
1.220     foxr     6974:     if ($howpwd ne 'nouser') {
                   6975: 	if($howpwd eq "internal") { # Encrypted is in local password file.
                   6976: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
                   6977: 	}
                   6978: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   6979: 	    $contentpwd = (getpwnam($user))[1];
                   6980: 	    if($contentpwd) {
                   6981: 		if($contentpwd eq 'x') { # Shadow password file...
                   6982: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   6983: 		    open PWAUTH,  "|$pwauth_path" or
                   6984: 			die "Cannot invoke authentication";
                   6985: 		    print PWAUTH "$user\n$password\n";
                   6986: 		    close PWAUTH;
                   6987: 		    $validated = ! $?;
                   6988: 
                   6989: 		} else { 	         # Passwords in /etc/passwd. 
                   6990: 		    $validated = (crypt($password,
                   6991: 					$contentpwd) eq $contentpwd);
                   6992: 		}
                   6993: 	    } else {
                   6994: 		$validated = 0;
                   6995: 	    }
1.439     raeburn  6996: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   6997:             my $checkwithkrb5 = 0;
                   6998:             if ($dist =~/^fedora(\d+)$/) {
                   6999:                 if ($1 > 11) {
                   7000:                     $checkwithkrb5 = 1;
                   7001:                 }
                   7002:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   7003:                 if ($1 > 11.1) {
                   7004:                     $checkwithkrb5 = 1; 
                   7005:                 }
                   7006:             }
                   7007:             if ($checkwithkrb5) {
                   7008:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   7009:             } else {
                   7010:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   7011:             }
1.224     foxr     7012: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  7013:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     7014: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     7015: 	    #  Authenticate via installation specific authentcation method:
                   7016: 	    $validated = &localauth::localauth($user, 
                   7017: 					       $password, 
1.353     albertel 7018: 					       $contentpwd,
                   7019: 					       $domain);
1.358     albertel 7020: 	    if ($validated < 0) {
1.357     albertel 7021: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   7022: 		$validated = 0;
                   7023: 	    }
1.224     foxr     7024: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     7025: 	    $validated = 0;
                   7026: 	}
                   7027:     } else {
                   7028: 	$validated = 0;
                   7029:     }
                   7030:     #
                   7031:     #  $validated has the correct stat of the authentication:
                   7032:     #
                   7033: 
                   7034:     unless ($validated != -3.14159) {
1.249     foxr     7035: 	#  I >really really< want to know if this happens.
                   7036: 	#  since it indicates that user authentication is badly
                   7037: 	#  broken in some code path.
                   7038:         #
                   7039: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     7040:     }
                   7041:     return $validated;
                   7042: }
                   7043: 
1.439     raeburn  7044: sub krb4_authen {
                   7045:     my ($password,$null,$user,$contentpwd) = @_;
                   7046:     my $validated = 0;
                   7047:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   7048:         eval {
                   7049:             require Authen::Krb4;
                   7050:         };
                   7051:         if (!$@) {
                   7052:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   7053:                                                        "",
                   7054:                                                        $contentpwd,,
                   7055:                                                        'krbtgt',
                   7056:                                                        $contentpwd,
                   7057:                                                        1,
                   7058:                                                        $password);
                   7059:             if(!$k4error) {
                   7060:                 $validated = 1;
                   7061:             } else {
                   7062:                 $validated = 0;
                   7063:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   7064:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   7065:             }
                   7066:         } else {
                   7067:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   7068:         }
                   7069:     }
                   7070:     return $validated;
                   7071: }
                   7072: 
                   7073: sub krb5_authen {
                   7074:     my ($password,$null,$user,$contentpwd) = @_;
                   7075:     my $validated = 0;
                   7076:     if(!($password =~ /$null/)) { # Null password not allowed.
                   7077:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   7078:                                                   .$contentpwd);
                   7079:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   7080:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   7081:         my $credentials= &Authen::Krb5::cc_default();
                   7082:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   7083:                                                             .$contentpwd));
                   7084:         my $krbreturn;
                   7085:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   7086:             $krbreturn =
                   7087:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   7088:                                                           $krbservice);
                   7089:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   7090:         } else {
                   7091:             $krbreturn  =
                   7092:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   7093:                                                          $password,$credentials);
                   7094:             $validated = ($krbreturn == 1);
                   7095:         }
                   7096:         if (!$validated) {
                   7097:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   7098:                      &Authen::Krb5::error());
                   7099:         }
                   7100:     }
                   7101:     return $validated;
                   7102: }
1.220     foxr     7103: 
1.84      albertel 7104: sub addline {
                   7105:     my ($fname,$hostid,$ip,$newline)=@_;
                   7106:     my $contents;
                   7107:     my $found=0;
1.355     albertel 7108:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 7109:     my $sh;
1.84      albertel 7110:     if ($sh=IO::File->new("$fname.subscription")) {
                   7111: 	while (my $subline=<$sh>) {
                   7112: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   7113: 	}
                   7114: 	$sh->close();
                   7115:     }
                   7116:     $sh=IO::File->new(">$fname.subscription");
                   7117:     if ($contents) { print $sh $contents; }
                   7118:     if ($newline) { print $sh $newline; }
                   7119:     $sh->close();
                   7120:     return $found;
1.86      www      7121: }
                   7122: 
1.234     foxr     7123: sub get_chat {
1.324     raeburn  7124:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 7125: 
1.87      www      7126:     my @entries=();
1.324     raeburn  7127:     my $namespace = 'nohist_chatroom';
                   7128:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 7129:     if ($group ne '') {
1.324     raeburn  7130:         $namespace .= '_'.$group;
                   7131:         $namespace_inroom .= '_'.$group;
                   7132:     }
                   7133:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 7134: 				 &GDBM_READER());
                   7135:     if ($hashref) {
                   7136: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 7137: 	&untie_user_hash($hashref);
1.123     www      7138:     }
1.124     www      7139:     my @participants=();
1.134     albertel 7140:     my $cutoff=time-60;
1.324     raeburn  7141:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 7142: 			      &GDBM_WRCREAT());
                   7143:     if ($hashref) {
                   7144:         $hashref->{$uname.':'.$udom}=time;
                   7145:         foreach my $user (sort(keys(%$hashref))) {
                   7146: 	    if ($hashref->{$user}>$cutoff) {
                   7147: 		push(@participants, 'active_participant:'.$user);
1.123     www      7148:             }
                   7149:         }
1.311     albertel 7150:         &untie_user_hash($hashref);
1.86      www      7151:     }
1.124     www      7152:     return (@participants,@entries);
1.86      www      7153: }
                   7154: 
1.234     foxr     7155: sub chat_add {
1.324     raeburn  7156:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 7157:     my @entries=();
1.142     www      7158:     my $time=time;
1.324     raeburn  7159:     my $namespace = 'nohist_chatroom';
                   7160:     my $logfile = 'chatroom.log';
1.335     albertel 7161:     if ($group ne '') {
1.324     raeburn  7162:         $namespace .= '_'.$group;
                   7163:         $logfile = 'chatroom_'.$group.'.log';
                   7164:     }
                   7165:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 7166: 				 &GDBM_WRCREAT());
                   7167:     if ($hashref) {
                   7168: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 7169: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   7170: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   7171: 	my $newid=$time.'_000000';
                   7172: 	if ($thentime==$time) {
                   7173: 	    $idnum=~s/^0+//;
                   7174: 	    $idnum++;
                   7175: 	    $idnum=substr('000000'.$idnum,-6,6);
                   7176: 	    $newid=$time.'_'.$idnum;
                   7177: 	}
1.310     albertel 7178: 	$hashref->{$newid}=$newchat;
1.88      albertel 7179: 	my $expired=$time-3600;
1.310     albertel 7180: 	foreach my $comment (keys(%$hashref)) {
                   7181: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 7182: 	    if ($thistime<$expired) {
1.310     albertel 7183: 		delete $hashref->{$comment};
1.88      albertel 7184: 	    }
                   7185: 	}
1.310     albertel 7186: 	{
                   7187: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  7188: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 7189: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   7190: 	    }
                   7191: 	    close(CHATLOG);
1.142     www      7192: 	}
1.311     albertel 7193: 	&untie_user_hash($hashref);
1.86      www      7194:     }
1.84      albertel 7195: }
                   7196: 
                   7197: sub unsub {
                   7198:     my ($fname,$clientip)=@_;
                   7199:     my $result;
1.188     foxr     7200:     my $unsubs = 0;		# Number of successful unsubscribes:
                   7201: 
                   7202: 
                   7203:     # An old way subscriptions were handled was to have a 
                   7204:     # subscription marker file:
                   7205: 
                   7206:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     7207:     if (unlink("$fname.$clientname")) {
1.188     foxr     7208: 	$unsubs++;		# Successful unsub via marker file.
                   7209:     } 
                   7210: 
                   7211:     # The more modern way to do it is to have a subscription list
                   7212:     # file:
                   7213: 
1.84      albertel 7214:     if (-e "$fname.subscription") {
1.161     foxr     7215: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     7216: 	if ($found) { 
                   7217: 	    $unsubs++;
                   7218: 	}
                   7219:     } 
                   7220: 
                   7221:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   7222:     #  resource we can return ok:
                   7223: 
                   7224:     if($unsubs) {
                   7225: 	$result = "ok\n";
1.84      albertel 7226:     } else {
1.188     foxr     7227: 	$result = "not_subscribed\n";
1.84      albertel 7228:     }
1.188     foxr     7229: 
1.84      albertel 7230:     return $result;
                   7231: }
                   7232: 
1.101     www      7233: sub currentversion {
                   7234:     my $fname=shift;
                   7235:     my $version=-1;
                   7236:     my $ulsdir='';
                   7237:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   7238:        $ulsdir=$1;
                   7239:     }
1.114     albertel 7240:     my ($fnamere1,$fnamere2);
                   7241:     # remove version if already specified
1.101     www      7242:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 7243:     # get the bits that go before and after the version number
                   7244:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   7245: 	$fnamere1=$1;
                   7246: 	$fnamere2='.'.$2;
                   7247:     }
1.101     www      7248:     if (-e $fname) { $version=1; }
                   7249:     if (-e $ulsdir) {
1.134     albertel 7250: 	if(-d $ulsdir) {
                   7251: 	    if (opendir(LSDIR,$ulsdir)) {
                   7252: 		my $ulsfn;
                   7253: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      7254: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 7255: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   7256: 		    unless (-l $thisfile) {
1.160     www      7257: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 7258: 			    if ($1>$version) { $version=$1; }
                   7259: 			}
                   7260: 		    }
                   7261: 		}
                   7262: 		closedir(LSDIR);
                   7263: 		$version++;
                   7264: 	    }
                   7265: 	}
                   7266:     }
                   7267:     return $version;
1.101     www      7268: }
                   7269: 
                   7270: sub thisversion {
                   7271:     my $fname=shift;
                   7272:     my $version=-1;
                   7273:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   7274: 	$version=$1;
                   7275:     }
                   7276:     return $version;
                   7277: }
                   7278: 
1.84      albertel 7279: sub subscribe {
                   7280:     my ($userinput,$clientip)=@_;
                   7281:     my $result;
1.293     albertel 7282:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 7283:     my $ownership=&ishome($fname);
                   7284:     if ($ownership eq 'owner') {
1.101     www      7285: # explitly asking for the current version?
                   7286:         unless (-e $fname) {
                   7287:             my $currentversion=&currentversion($fname);
                   7288: 	    if (&thisversion($fname)==$currentversion) {
                   7289:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   7290: 		    my $root=$1;
                   7291:                     my $extension=$2;
                   7292:                     symlink($root.'.'.$extension,
                   7293:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      7294:                     unless ($extension=~/\.meta$/) {
                   7295:                        symlink($root.'.'.$extension.'.meta',
                   7296:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   7297: 		    }
1.101     www      7298:                 }
                   7299:             }
                   7300:         }
1.84      albertel 7301: 	if (-e $fname) {
                   7302: 	    if (-d $fname) {
                   7303: 		$result="directory\n";
                   7304: 	    } else {
1.161     foxr     7305: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 7306: 		my $now=time;
1.161     foxr     7307: 		my $found=&addline($fname,$clientname,$clientip,
                   7308: 				   "$clientname:$clientip:$now\n");
1.84      albertel 7309: 		if ($found) { $result="$fname\n"; }
                   7310: 		# if they were subscribed to only meta data, delete that
                   7311:                 # subscription, when you subscribe to a file you also get
                   7312:                 # the metadata
                   7313: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   7314: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  7315:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   7316:                 $protocol = 'http' if ($protocol ne 'https');
                   7317: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 7318: 		$result="$fname\n";
                   7319: 	    }
                   7320: 	} else {
                   7321: 	    $result="not_found\n";
                   7322: 	}
                   7323:     } else {
                   7324: 	$result="rejected\n";
                   7325:     }
                   7326:     return $result;
                   7327: }
1.287     foxr     7328: #  Change the passwd of a unix user.  The caller must have
                   7329: #  first verified that the user is a loncapa user.
                   7330: #
                   7331: # Parameters:
                   7332: #    user      - Unix user name to change.
                   7333: #    pass      - New password for the user.
                   7334: # Returns:
                   7335: #    ok    - if success
                   7336: #    other - Some meaningfule error message string.
                   7337: # NOTE:
                   7338: #    invokes a setuid script to change the passwd.
                   7339: sub change_unix_password {
                   7340:     my ($user, $pass) = @_;
                   7341: 
                   7342:     &Debug("change_unix_password");
                   7343:     my $execdir=$perlvar{'lonDaemons'};
                   7344:     &Debug("Opening lcpasswd pipeline");
                   7345:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   7346: 			   ."$perlvar{'lonDaemons'}"
                   7347: 			   ."/logs/lcpasswd.log");
                   7348:     print $pf "$user\n$pass\n$pass\n";
                   7349:     close $pf;
                   7350:     my $err = $?;
                   7351:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   7352: 	"pwchange_falure - unknown error";
                   7353: 
                   7354:     
                   7355: }
                   7356: 
1.91      albertel 7357: 
                   7358: sub make_passwd_file {
1.483     www      7359:     my ($uname,$udom,$umode,$npass,$passfilename)=@_;
1.390     raeburn  7360:     my $result="ok";
1.91      albertel 7361:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   7362: 	{
                   7363: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     7364: 	    if ($pf) {
                   7365: 		print $pf "$umode:$npass\n";
                   7366: 	    } else {
                   7367: 		$result = "pass_file_failed_error";
                   7368: 	    }
1.91      albertel 7369: 	}
                   7370:     } elsif ($umode eq 'internal') {
                   7371: 	my $salt=time;
                   7372: 	$salt=substr($salt,6,2);
                   7373: 	my $ncpass=crypt($npass,$salt);
                   7374: 	{
                   7375: 	    &Debug("Creating internal auth");
                   7376: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     7377: 	    if($pf) {
                   7378: 		print $pf "internal:$ncpass\n"; 
                   7379: 	    } else {
                   7380: 		$result = "pass_file_failed_error";
                   7381: 	    }
1.91      albertel 7382: 	}
                   7383:     } elsif ($umode eq 'localauth') {
                   7384: 	{
                   7385: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     7386: 	    if($pf) {
                   7387: 		print $pf "localauth:$npass\n";
                   7388: 	    } else {
                   7389: 		$result = "pass_file_failed_error";
                   7390: 	    }
1.91      albertel 7391: 	}
                   7392:     } elsif ($umode eq 'unix') {
1.489.2.8  raeburn  7393: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   7394: 	$result="no_new_unix_accounts";
1.91      albertel 7395:     } elsif ($umode eq 'none') {
                   7396: 	{
1.223     foxr     7397: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     7398: 	    if($pf) {
                   7399: 		print $pf "none:\n";
                   7400: 	    } else {
                   7401: 		$result = "pass_file_failed_error";
                   7402: 	    }
1.91      albertel 7403: 	}
                   7404:     } else {
1.390     raeburn  7405: 	$result="auth_mode_error";
1.91      albertel 7406:     }
                   7407:     return $result;
1.121     albertel 7408: }
                   7409: 
1.265     albertel 7410: sub convert_photo {
                   7411:     my ($start,$dest)=@_;
                   7412:     system("convert $start $dest");
                   7413: }
                   7414: 
1.121     albertel 7415: sub sethost {
                   7416:     my ($remotereq) = @_;
                   7417:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 7418:     # ignore sethost if we are already correct
                   7419:     if ($hostid eq $currenthostid) {
                   7420: 	return 'ok';
                   7421:     }
                   7422: 
1.121     albertel 7423:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 7424:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   7425: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  7426: 	$currenthostid  =$hostid;
1.369     albertel 7427: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.443     www      7428: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 7429:     } else {
                   7430: 	&logthis("Requested host id $hostid not an alias of ".
                   7431: 		 $perlvar{'lonHostID'}." refusing connection");
                   7432: 	return 'unable_to_set';
                   7433:     }
                   7434:     return 'ok';
                   7435: }
                   7436: 
                   7437: sub version {
                   7438:     my ($userinput)=@_;
                   7439:     $remoteVERSION=(split(/:/,$userinput))[1];
                   7440:     return "version:$VERSION";
1.127     albertel 7441: }
1.178     foxr     7442: 
1.447     raeburn  7443: sub get_usersession_config {
                   7444:     my ($dom,$name) = @_;
                   7445:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   7446:     if (defined($cached)) {
                   7447:         return $usersessionconf;
                   7448:     } else {
                   7449:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
                   7450:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   7451:             &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   7452:             return $domconfig{'usersessions'};
                   7453:         }
                   7454:     }
                   7455:     return;
                   7456: }
1.200     matthew  7457: 
1.450     raeburn  7458: 
1.471     raeburn  7459: sub distro_and_arch {
                   7460:     return $dist.':'.$arch;
                   7461: }
                   7462: 
1.61      harris41 7463: # ----------------------------------- POD (plain old documentation, CPAN style)
                   7464: 
                   7465: =head1 NAME
                   7466: 
                   7467: lond - "LON Daemon" Server (port "LOND" 5663)
                   7468: 
                   7469: =head1 SYNOPSIS
                   7470: 
1.74      harris41 7471: Usage: B<lond>
                   7472: 
                   7473: Should only be run as user=www.  This is a command-line script which
                   7474: is invoked by B<loncron>.  There is no expectation that a typical user
                   7475: will manually start B<lond> from the command-line.  (In other words,
                   7476: DO NOT START B<lond> YOURSELF.)
1.61      harris41 7477: 
                   7478: =head1 DESCRIPTION
                   7479: 
1.74      harris41 7480: There are two characteristics associated with the running of B<lond>,
                   7481: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   7482: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   7483: subscriptions, etc).  These are described in two large
                   7484: sections below.
                   7485: 
                   7486: B<PROCESS MANAGEMENT>
                   7487: 
1.61      harris41 7488: Preforker - server who forks first. Runs as a daemon. HUPs.
                   7489: Uses IDEA encryption
                   7490: 
1.74      harris41 7491: B<lond> forks off children processes that correspond to the other servers
                   7492: in the network.  Management of these processes can be done at the
                   7493: parent process level or the child process level.
                   7494: 
                   7495: B<logs/lond.log> is the location of log messages.
                   7496: 
                   7497: The process management is now explained in terms of linux shell commands,
                   7498: subroutines internal to this code, and signal assignments:
                   7499: 
                   7500: =over 4
                   7501: 
                   7502: =item *
                   7503: 
                   7504: PID is stored in B<logs/lond.pid>
                   7505: 
                   7506: This is the process id number of the parent B<lond> process.
                   7507: 
                   7508: =item *
                   7509: 
                   7510: SIGTERM and SIGINT
                   7511: 
                   7512: Parent signal assignment:
                   7513:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7514: 
                   7515: Child signal assignment:
                   7516:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   7517: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   7518:  to restart a new child.)
                   7519: 
                   7520: Command-line invocations:
                   7521:  B<kill> B<-s> SIGTERM I<PID>
                   7522:  B<kill> B<-s> SIGINT I<PID>
                   7523: 
                   7524: Subroutine B<HUNTSMAN>:
                   7525:  This is only invoked for the B<lond> parent I<PID>.
                   7526: This kills all the children, and then the parent.
                   7527: The B<lonc.pid> file is cleared.
                   7528: 
                   7529: =item *
                   7530: 
                   7531: SIGHUP
                   7532: 
                   7533: Current bug:
                   7534:  This signal can only be processed the first time
                   7535: on the parent process.  Subsequent SIGHUP signals
                   7536: have no effect.
                   7537: 
                   7538: Parent signal assignment:
                   7539:  $SIG{HUP}  = \&HUPSMAN;
                   7540: 
                   7541: Child signal assignment:
                   7542:  none (nothing happens)
                   7543: 
                   7544: Command-line invocations:
                   7545:  B<kill> B<-s> SIGHUP I<PID>
                   7546: 
                   7547: Subroutine B<HUPSMAN>:
                   7548:  This is only invoked for the B<lond> parent I<PID>,
                   7549: This kills all the children, and then the parent.
                   7550: The B<lond.pid> file is cleared.
                   7551: 
                   7552: =item *
                   7553: 
                   7554: SIGUSR1
                   7555: 
                   7556: Parent signal assignment:
                   7557:  $SIG{USR1} = \&USRMAN;
                   7558: 
                   7559: Child signal assignment:
                   7560:  $SIG{USR1}= \&logstatus;
                   7561: 
                   7562: Command-line invocations:
                   7563:  B<kill> B<-s> SIGUSR1 I<PID>
                   7564: 
                   7565: Subroutine B<USRMAN>:
                   7566:  When invoked for the B<lond> parent I<PID>,
                   7567: SIGUSR1 is sent to all the children, and the status of
                   7568: each connection is logged.
1.144     foxr     7569: 
                   7570: =item *
                   7571: 
                   7572: SIGUSR2
                   7573: 
                   7574: Parent Signal assignment:
                   7575:     $SIG{USR2} = \&UpdateHosts
                   7576: 
                   7577: Child signal assignment:
                   7578:     NONE
                   7579: 
1.74      harris41 7580: 
                   7581: =item *
                   7582: 
                   7583: SIGCHLD
                   7584: 
                   7585: Parent signal assignment:
                   7586:  $SIG{CHLD} = \&REAPER;
                   7587: 
                   7588: Child signal assignment:
                   7589:  none
                   7590: 
                   7591: Command-line invocations:
                   7592:  B<kill> B<-s> SIGCHLD I<PID>
                   7593: 
                   7594: Subroutine B<REAPER>:
                   7595:  This is only invoked for the B<lond> parent I<PID>.
                   7596: Information pertaining to the child is removed.
                   7597: The socket port is cleaned up.
                   7598: 
                   7599: =back
                   7600: 
                   7601: B<SERVER-SIDE ACTIVITIES>
                   7602: 
                   7603: Server-side information can be accepted in an encrypted or non-encrypted
                   7604: method.
                   7605: 
                   7606: =over 4
                   7607: 
                   7608: =item ping
                   7609: 
                   7610: Query a client in the hosts.tab table; "Are you there?"
                   7611: 
                   7612: =item pong
                   7613: 
                   7614: Respond to a ping query.
                   7615: 
                   7616: =item ekey
                   7617: 
                   7618: Read in encrypted key, make cipher.  Respond with a buildkey.
                   7619: 
                   7620: =item load
                   7621: 
                   7622: Respond with CPU load based on a computation upon /proc/loadavg.
                   7623: 
                   7624: =item currentauth
                   7625: 
                   7626: Reply with current authentication information (only over an
                   7627: encrypted channel).
                   7628: 
                   7629: =item auth
                   7630: 
                   7631: Only over an encrypted channel, reply as to whether a user's
                   7632: authentication information can be validated.
                   7633: 
                   7634: =item passwd
                   7635: 
                   7636: Allow for a password to be set.
                   7637: 
                   7638: =item makeuser
                   7639: 
                   7640: Make a user.
                   7641: 
                   7642: =item passwd
                   7643: 
                   7644: Allow for authentication mechanism and password to be changed.
                   7645: 
                   7646: =item home
1.61      harris41 7647: 
1.74      harris41 7648: Respond to a question "are you the home for a given user?"
                   7649: 
                   7650: =item update
                   7651: 
                   7652: Update contents of a subscribed resource.
                   7653: 
                   7654: =item unsubscribe
                   7655: 
                   7656: The server is unsubscribing from a resource.
                   7657: 
                   7658: =item subscribe
                   7659: 
                   7660: The server is subscribing to a resource.
                   7661: 
                   7662: =item log
                   7663: 
                   7664: Place in B<logs/lond.log>
                   7665: 
                   7666: =item put
                   7667: 
                   7668: stores hash in namespace
                   7669: 
1.489.2.2  raeburn  7670: =item rolesput
1.74      harris41 7671: 
                   7672: put a role into a user's environment
                   7673: 
                   7674: =item get
                   7675: 
                   7676: returns hash with keys from array
                   7677: reference filled in from namespace
                   7678: 
                   7679: =item eget
                   7680: 
                   7681: returns hash with keys from array
                   7682: reference filled in from namesp (encrypts the return communication)
                   7683: 
                   7684: =item rolesget
                   7685: 
                   7686: get a role from a user's environment
                   7687: 
                   7688: =item del
                   7689: 
                   7690: deletes keys out of array from namespace
                   7691: 
                   7692: =item keys
                   7693: 
                   7694: returns namespace keys
                   7695: 
                   7696: =item dump
                   7697: 
                   7698: dumps the complete (or key matching regexp) namespace into a hash
                   7699: 
                   7700: =item store
                   7701: 
                   7702: stores hash permanently
                   7703: for this url; hashref needs to be given and should be a \%hashname; the
                   7704: remaining args aren't required and if they aren't passed or are '' they will
                   7705: be derived from the ENV
                   7706: 
                   7707: =item restore
                   7708: 
                   7709: returns a hash for a given url
                   7710: 
                   7711: =item querysend
                   7712: 
                   7713: Tells client about the lonsql process that has been launched in response
                   7714: to a sent query.
                   7715: 
                   7716: =item queryreply
                   7717: 
                   7718: Accept information from lonsql and make appropriate storage in temporary
                   7719: file space.
                   7720: 
                   7721: =item idput
                   7722: 
                   7723: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   7724: for each student, defined perhaps by the institutional Registrar.)
                   7725: 
                   7726: =item idget
                   7727: 
                   7728: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   7729: for each student, defined perhaps by the institutional Registrar.)
                   7730: 
                   7731: =item tmpput
                   7732: 
                   7733: Accept and store information in temporary space.
                   7734: 
                   7735: =item tmpget
                   7736: 
                   7737: Send along temporarily stored information.
                   7738: 
                   7739: =item ls
                   7740: 
                   7741: List part of a user's directory.
                   7742: 
1.135     foxr     7743: =item pushtable
                   7744: 
                   7745: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   7746: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   7747: must be restored manually in case of a problem with the new table file.
                   7748: pushtable requires that the request be encrypted and validated via
                   7749: ValidateManager.  The form of the command is:
                   7750: enc:pushtable tablename <tablecontents> \n
                   7751: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   7752: cleartext newline.
                   7753: 
1.74      harris41 7754: =item Hanging up (exit or init)
                   7755: 
                   7756: What to do when a client tells the server that they (the client)
                   7757: are leaving the network.
                   7758: 
                   7759: =item unknown command
                   7760: 
                   7761: If B<lond> is sent an unknown command (not in the list above),
                   7762: it replys to the client "unknown_cmd".
1.135     foxr     7763: 
1.74      harris41 7764: 
                   7765: =item UNKNOWN CLIENT
                   7766: 
                   7767: If the anti-spoofing algorithm cannot verify the client,
                   7768: the client is rejected (with a "refused" message sent
                   7769: to the client, and the connection is closed.
                   7770: 
                   7771: =back
1.61      harris41 7772: 
                   7773: =head1 PREREQUISITES
                   7774: 
                   7775: IO::Socket
                   7776: IO::File
                   7777: Apache::File
                   7778: POSIX
                   7779: Crypt::IDEA
                   7780: LWP::UserAgent()
                   7781: GDBM_File
                   7782: Authen::Krb4
1.91      albertel 7783: Authen::Krb5
1.61      harris41 7784: 
                   7785: =head1 COREQUISITES
                   7786: 
                   7787: =head1 OSNAMES
                   7788: 
                   7789: linux
                   7790: 
                   7791: =head1 SCRIPT CATEGORIES
                   7792: 
                   7793: Server/Process
                   7794: 
                   7795: =cut
1.409     foxr     7796: 
                   7797: 
                   7798: =pod
                   7799: 
                   7800: =head1 LOG MESSAGES
                   7801: 
                   7802: The messages below can be emitted in the lond log.  This log is located
                   7803: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   7804: to provide coloring if examined from inside a web page. Some do not.
                   7805: Where color is used, the colors are; Red for sometihhng to get excited
                   7806: about and to follow up on. Yellow for something to keep an eye on to
                   7807: be sure it does not get worse, Green,and Blue for informational items.
                   7808: 
                   7809: In the discussions below, sometimes reference is made to ~httpd
                   7810: when describing file locations.  There isn't really an httpd 
                   7811: user, however there is an httpd directory that gets installed in the
                   7812: place that user home directories go.  On linux, this is usually
                   7813: (always?) /home/httpd.
                   7814: 
                   7815: 
                   7816: Some messages are colorless.  These are usually (not always)
                   7817: Green/Blue color level messages.
                   7818: 
                   7819: =over 2
                   7820: 
                   7821: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   7822: 
                   7823: A local connection negotiation was attempted by
                   7824: a host whose IP address was not 127.0.0.1.
                   7825: The socket is closed and the child will exit.
                   7826: lond has three ways to establish an encyrption
                   7827: key with a client:
                   7828: 
                   7829: =over 2
                   7830: 
                   7831: =item local 
                   7832: 
                   7833: The key is written and read from a file.
                   7834: This is only valid for connections from localhost.
                   7835: 
                   7836: =item insecure 
                   7837: 
                   7838: The key is generated by the server and
                   7839: transmitted to the client.
                   7840: 
                   7841: =item  ssl (secure)
                   7842: 
                   7843: An ssl connection is negotiated with the client,
                   7844: the key is generated by the server and sent to the 
                   7845: client across this ssl connection before the
                   7846: ssl connectionis terminated and clear text
                   7847: transmission resumes.
                   7848: 
                   7849: =back
                   7850: 
                   7851: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   7852: 
                   7853: The client is local but has not sent an initialization
                   7854: string that is the literal "init:local"  The connection
                   7855: is closed and the child exits.
                   7856: 
                   7857: =item Red CRITICAL Can't get key file <error>        
                   7858: 
                   7859: SSL key negotiation is being attempted but the call to
                   7860: lonssl::KeyFile  failed.  This usually means that the
                   7861: configuration file is not correctly defining or protecting
                   7862: the directories/files lonCertificateDirectory or
                   7863: lonnetPrivateKey
                   7864: <error> is a string that describes the reason that
                   7865: the key file could not be located.
                   7866: 
                   7867: =item (Red) CRITICAL  Can't get certificates <error>  
                   7868: 
                   7869: SSL key negotiation failed because we were not able to retrives our certificate
                   7870: or the CA's certificate in the call to lonssl::CertificateFile
                   7871: <error> is the textual reason this failed.  Usual reasons:
                   7872: 
                   7873: =over 2
                   7874:        
                   7875: =item Apache config file for loncapa  incorrect:
                   7876:  
                   7877: one of the variables 
                   7878: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   7879: undefined or incorrect
                   7880: 
                   7881: =item Permission error:
                   7882: 
                   7883: The directory pointed to by lonCertificateDirectory is not readable by lond
                   7884: 
                   7885: =item Permission error:
                   7886: 
                   7887: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   7888: 
                   7889: =item Installation error:                         
                   7890: 
                   7891: Either the certificate authority file or the certificate have not
                   7892: been installed in lonCertificateDirectory.
                   7893: 
                   7894: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   7895: 
                   7896: The promotion of the connection from plaintext to SSL failed
                   7897: <err> is the reason for the failure.  There are two
                   7898: system calls involved in the promotion (one of which failed), 
                   7899: a dup to produce
                   7900: a second fd on the raw socket over which the encrypted data
                   7901: will flow and IO::SOcket::SSL->new_from_fd which creates
                   7902: the SSL connection on the duped fd.
                   7903: 
                   7904: =item (Blue)   WARNING client did not respond to challenge 
                   7905: 
                   7906: This occurs on an insecure (non SSL) connection negotiation request.
                   7907: lond generates some number from the time, the PID and sends it to
                   7908: the client.  The client must respond by echoing this information back.
                   7909: If the client does not do so, that's a violation of the challenge
                   7910: protocols and the connection will be failed.
                   7911: 
                   7912: =item (Red) No manager table. Nobody can manage!!    
                   7913: 
                   7914: lond has the concept of privileged hosts that
                   7915: can perform remote management function such
                   7916: as update the hosts.tab.   The manager hosts
                   7917: are described in the 
                   7918: ~httpd/lonTabs/managers.tab file.
                   7919: this message is logged if this file is missing.
                   7920: 
                   7921: 
                   7922: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   7923: 
                   7924: Reports the successful parse and registration
                   7925: of a specific manager. 
                   7926: 
                   7927: =item Green existing host <clustername:dnsname>  
                   7928: 
                   7929: The manager host is already defined in the hosts.tab
                   7930: the information in that table, rather than the info in the
                   7931: manager table will be used to determine the manager's ip.
                   7932: 
                   7933: =item (Red) Unable to craete <filename>                 
                   7934: 
                   7935: lond has been asked to create new versions of an administrative
                   7936: file (by a manager).  When this is done, the new file is created
                   7937: in a temp file and then renamed into place so that there are always
                   7938: usable administrative files, even if the update fails.  This failure
                   7939: message means that the temp file could not be created.
                   7940: The update is abandoned, and the old file is available for use.
                   7941: 
                   7942: =item (Green) CopyFile from <oldname> to <newname> failed
                   7943: 
                   7944: In an update of administrative files, the copy of the existing file to a
                   7945: backup file failed.  The installation of the new file may still succeed,
                   7946: but there will not be a back up file to rever to (this should probably
                   7947: be yellow).
                   7948: 
                   7949: =item (Green) Pushfile: backed up <oldname> to <newname>
                   7950: 
                   7951: See above, the backup of the old administrative file succeeded.
                   7952: 
                   7953: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   7954: 
                   7955: The new administrative file could not be installed.  In this case,
                   7956: the old administrative file is still in use.
                   7957: 
                   7958: =item (Green) Installed new < filename>.                      
                   7959: 
                   7960: The new administrative file was successfullly installed.                                               
                   7961: 
                   7962: =item (Red) Reinitializing lond pid=<pid>                    
                   7963: 
                   7964: The lonc child process <pid> will be sent a USR2 
                   7965: signal.
                   7966: 
                   7967: =item (Red) Reinitializing self                                    
                   7968: 
                   7969: We've been asked to re-read our administrative files,and
                   7970: are doing so.
                   7971: 
                   7972: =item (Yellow) error:Invalid process identifier <ident>  
                   7973: 
                   7974: A reinit command was received, but the target part of the 
                   7975: command was not valid.  It must be either
                   7976: 'lond' or 'lonc' but was <ident>
                   7977: 
                   7978: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   7979: 
                   7980: Checking to see if lond has been handed a valid edit
                   7981: command.  It is possible the edit command is not valid
                   7982: in that case there are no log messages to indicate that.
                   7983: 
                   7984: =item Result of password change for  <username> pwchange_success
                   7985: 
                   7986: The password for <username> was
                   7987: successfully changed.
                   7988: 
                   7989: =item Unable to open <user> passwd to change password
                   7990: 
                   7991: Could not rewrite the 
                   7992: internal password file for a user
                   7993: 
                   7994: =item Result of password change for <user> : <result>
                   7995:                                                                      
                   7996: A unix password change for <user> was attempted 
                   7997: and the pipe returned <result>  
                   7998: 
                   7999: =item LWP GET: <message> for <fname> (<remoteurl>)
                   8000: 
                   8001: The lightweight process fetch for a resource failed
                   8002: with <message> the local filename that should
                   8003: have existed/been created was  <fname> the
                   8004: corresponding URI: <remoteurl>  This is emitted in several
                   8005: places.
                   8006: 
                   8007: =item Unable to move <transname> to <destname>     
                   8008: 
                   8009: From fetch_user_file_handler - the user file was replicated but could not
                   8010: be mv'd to its final location.
                   8011: 
                   8012: =item Looking for <domain> <username>              
                   8013: 
                   8014: From user_has_session_handler - This should be a Debug call instead
                   8015: it indicates lond is about to check whether the specified user has a 
                   8016: session active on the specified domain on the local host.
                   8017: 
                   8018: =item Client <ip> (<name>) hanging up: <input>     
                   8019: 
                   8020: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   8021: client systemand <input> is the full exit command sent to the server.
                   8022: 
                   8023: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
                   8024:                                                  
                   8025: A lond child terminated.  NOte that this termination can also occur when the
                   8026: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   8027: <hostname> the host lond is working for, and <message> the reason the child died
                   8028: to the best of our ability to get it (I would guess that any numeric value
                   8029: represents and errno value).  This is immediately followed by
                   8030: 
                   8031: =item  Famous last words: Catching exception - <log> 
                   8032: 
                   8033: Where log is some recent information about the state of the child.
                   8034: 
                   8035: =item Red CRITICAL: TIME OUT <pid>                     
                   8036: 
                   8037: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   8038: doing an HTTP::GET.
                   8039: 
                   8040: =item child <pid> died                              
                   8041: 
                   8042: The reaper caught a SIGCHILD for the lond child process <pid>
                   8043: This should be modified to also display the IP of the dying child
                   8044: $children{$pid}
                   8045: 
                   8046: =item Unknown child 0 died                           
                   8047: A child died but the wait for it returned a pid of zero which really should not
                   8048: ever happen. 
                   8049: 
                   8050: =item Child <which> - <pid> looks like we missed it's death 
                   8051: 
                   8052: When a sigchild is received, the reaper process checks all children to see if they are
                   8053: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   8054: that a signal hearalds the death of more than one child.  If so this message indicates
                   8055: which other one died. <which> is the ip of a dead child
                   8056: 
                   8057: =item Free socket: <shutdownretval>                
                   8058: 
                   8059: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   8060: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   8061: to return anything. This is followed by: 
                   8062: 
                   8063: =item Red CRITICAL: Shutting down                       
                   8064: 
                   8065: Just prior to exit.
                   8066: 
                   8067: =item Free socket: <shutdownretval>                 
                   8068: 
                   8069: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   8070: This is followed by:
                   8071: 
                   8072: =item (Red) CRITICAL: Restarting                         
                   8073: 
                   8074: lond is about to exec itself to restart.
                   8075: 
                   8076: =item (Blue) Updating connections                        
                   8077: 
                   8078: (In response to a USR2).  All the children (except the one for localhost)
                   8079: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   8080: 
                   8081: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   8082: 
                   8083: Due to USR2 as above.
                   8084: 
                   8085: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   8086: 
                   8087: In response to USR2 as above, the child indicated is not being restarted because
                   8088: it's assumed that we'll always need a child for the localhost.
                   8089: 
                   8090: 
                   8091: =item Going to check on the children                
                   8092: 
                   8093: Parent is about to check on the health of the child processes.
                   8094: Note that this is in response to a USR1 sent to the parent lond.
                   8095: there may be one or more of the next two messages:
                   8096: 
                   8097: =item <pid> is dead                                 
                   8098: 
                   8099: A child that we have in our child hash as alive has evidently died.
                   8100: 
                   8101: =item  Child <pid> did not respond                   
                   8102: 
                   8103: In the health check the child <pid> did not update/produce a pid_.txt
                   8104: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   8105: assumed to be hung in some un-fixable way.
                   8106: 
                   8107: =item Finished checking children                   
                   8108:  
                   8109: Master processs's USR1 processing is cojmplete.
                   8110: 
                   8111: =item (Red) CRITICAL: ------- Starting ------            
                   8112: 
                   8113: (There are more '-'s on either side).  Lond has forked itself off to 
                   8114: form a new session and is about to start actual initialization.
                   8115: 
                   8116: =item (Green) Attempting to start child (<client>)       
                   8117: 
                   8118: Started a new child process for <client>.  Client is IO::Socket object
                   8119: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   8120: 
                   8121: =item Unable to determine who caller was, getpeername returned nothing
                   8122:                                                   
                   8123: In child process initialization.  either getpeername returned undef or
                   8124: a zero sized object was returned.  Processing continues, but in my opinion,
                   8125: this should be cause for the child to exit.
                   8126: 
                   8127: =item Unable to determine clientip                  
                   8128: 
                   8129: In child process initialization.  The peer address from getpeername was not defined.
                   8130: The client address is stored as "Unavailable" and processing continues.
                   8131: 
                   8132: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
                   8133:                                                   
                   8134: In child initialization.  A good connectionw as received from <ip>.
                   8135: 
                   8136: =over 2
                   8137: 
                   8138: =item <name> 
                   8139: 
                   8140: is the name of the client from hosts.tab.
                   8141: 
                   8142: =item <type> 
                   8143: 
                   8144: Is the connection type which is either 
                   8145: 
                   8146: =over 2
                   8147: 
                   8148: =item manager 
                   8149: 
                   8150: The connection is from a manager node, not in hosts.tab
                   8151: 
                   8152: =item client  
                   8153: 
                   8154: the connection is from a non-manager in the hosts.tab
                   8155: 
                   8156: =item both
                   8157: 
                   8158: The connection is from a manager in the hosts.tab.
                   8159: 
                   8160: =back
                   8161: 
                   8162: =back
                   8163: 
                   8164: =item (Blue) Certificates not installed -- trying insecure auth
                   8165: 
                   8166: One of the certificate file, key file or
                   8167: certificate authority file could not be found for a client attempting
                   8168: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   8169: (this would be a system with an up to date lond that has not gotten a 
                   8170: certificate from us).
                   8171: 
                   8172: =item (Green)  Successful local authentication            
                   8173: 
                   8174: A local connection successfully negotiated the encryption key. 
                   8175: In this case the IDEA key is in a file (that is hopefully well protected).
                   8176: 
                   8177: =item (Green) Successful ssl authentication with <client>  
                   8178: 
                   8179: The client (<client> is the peer's name in hosts.tab), has successfully
                   8180: negotiated an SSL connection with this child process.
                   8181: 
                   8182: =item (Green) Successful insecure authentication with <client>
                   8183:                                                    
                   8184: 
                   8185: The client has successfully negotiated an  insecure connection withthe child process.
                   8186: 
                   8187: =item (Yellow) Attempted insecure connection disallowed    
                   8188: 
                   8189: The client attempted and failed to successfully negotiate a successful insecure
                   8190: connection.  This can happen either because the variable londAllowInsecure is false
                   8191: or undefined, or becuse the child did not successfully echo back the challenge
                   8192: string.
                   8193: 
                   8194: 
                   8195: =back
                   8196: 
1.441     raeburn  8197: =back
                   8198: 
1.409     foxr     8199: 
                   8200: =cut

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