Annotation of loncom/lond, revision 1.489.2.28.2.2

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

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