Annotation of loncom/lond, revision 1.512

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

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