Annotation of loncom/lond, revision 1.325

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.325   ! albertel    5: # $Id: lond,v 1.324 2006/03/29 19:56:10 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
                     18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     19: # GNU General Public License for more details.
                     20: #
                     21: # You should have received a copy of the GNU General Public License
                     22: # along with LON-CAPA; if not, write to the Free Software
1.178     foxr       23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
1.60      www        24: #
                     25: # /home/httpd/html/adm/gpl.txt
                     26: #
1.161     foxr       27: 
                     28: 
1.60      www        29: # http://www.lon-capa.org/
                     30: #
1.54      harris41   31: 
1.134     albertel   32: use strict;
1.80      harris41   33: use lib '/home/httpd/lib/perl/';
1.325   ! albertel   34: use LONCAPA;
1.80      harris41   35: use LONCAPA::Configuration;
                     36: 
1.1       albertel   37: use IO::Socket;
                     38: use IO::File;
1.126     albertel   39: #use Apache::File;
1.1       albertel   40: use Symbol;
                     41: use POSIX;
                     42: use Crypt::IDEA;
                     43: use LWP::UserAgent();
1.3       www        44: use GDBM_File;
                     45: use Authen::Krb4;
1.91      albertel   46: use Authen::Krb5;
1.49      albertel   47: use lib '/home/httpd/lib/perl/';
                     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.169     foxr       53: use LONCAPA::ConfigFileEdit;
1.200     matthew    54: use LONCAPA::lonlocal;
                     55: use LONCAPA::lonssl;
1.221     albertel   56: use Fcntl qw(:flock);
1.313     albertel   57: use Symbol;
1.1       albertel   58: 
1.239     foxr       59: my $DEBUG = 0;		       # Non zero to enable debug log entries.
1.77      foxr       60: 
1.57      www        61: my $status='';
                     62: my $lastlog='';
1.313     albertel   63: my $lond_max_wait_time = 13;
1.57      www        64: 
1.325   ! albertel   65: my $VERSION='$Revision: 1.324 $'; #' stupid emacs
1.121     albertel   66: my $remoteVERSION;
1.214     foxr       67: my $currenthostid="default";
1.115     albertel   68: my $currentdomainid;
1.134     albertel   69: 
                     70: my $client;
1.200     matthew    71: my $clientip;			# IP address of client.
                     72: my $clientname;			# LonCAPA name of client.
1.140     foxr       73: 
1.134     albertel   74: my $server;
1.200     matthew    75: my $thisserver;			# DNS of us.
                     76: 
                     77: my $keymode;
1.198     foxr       78: 
1.207     foxr       79: my $cipher;			# Cipher key negotiated with client
                     80: my $tmpsnum = 0;		# Id of tmpputs.
                     81: 
1.178     foxr       82: # 
                     83: #   Connection type is:
                     84: #      client                   - All client actions are allowed
                     85: #      manager                  - only management functions allowed.
                     86: #      both                     - Both management and client actions are allowed
                     87: #
1.161     foxr       88: 
1.178     foxr       89: my $ConnectionType;
1.161     foxr       90: 
1.200     matthew    91: my %hostid;			# ID's for hosts in cluster by ip.
                     92: my %hostdom;			# LonCAPA domain for hosts in cluster.
1.307     albertel   93: my %hostname;			# DNSname -> ID's mapping.
1.200     matthew    94: my %hostip;			# IPs for hosts in cluster.
                     95: my %hostdns;			# ID's of hosts looked up by DNS name.
1.161     foxr       96: 
1.178     foxr       97: my %managers;			# Ip -> manager names
1.161     foxr       98: 
1.178     foxr       99: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel  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.178     foxr      136: #  The array below are lcuseradd error strings.:
1.97      foxr      137: 
1.178     foxr      138: my $lastadderror = 13;
                    139: my @adderrors    = ("ok",
                    140: 		    "User ID mismatch, lcuseradd must run as user www",
                    141: 		    "lcuseradd Incorrect number of command line parameters must be 3",
                    142: 		    "lcuseradd Incorrect number of stdinput lines, must be 3",
                    143: 		    "lcuseradd Too many other simultaneous pwd changes in progress",
                    144: 		    "lcuseradd User does not exist",
                    145: 		    "lcuseradd Unable to make www member of users's group",
                    146: 		    "lcuseradd Unable to su to root",
                    147: 		    "lcuseradd Unable to set password",
                    148: 		    "lcuseradd Usrname has invalid characters",
                    149: 		    "lcuseradd Password has an invalid character",
                    150: 		    "lcuseradd User already exists",
                    151: 		    "lcuseradd Could not add user.",
                    152: 		    "lcuseradd Password mismatch");
1.97      foxr      153: 
1.96      foxr      154: 
1.207     foxr      155: 
                    156: #
                    157: #   Statistics that are maintained and dislayed in the status line.
                    158: #
1.212     foxr      159: my $Transactions = 0;		# Number of attempted transactions.
                    160: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      161: 
                    162: #   ResetStatistics: 
                    163: #      Resets the statistics counters:
                    164: #
                    165: sub ResetStatistics {
                    166:     $Transactions = 0;
                    167:     $Failures     = 0;
                    168: }
                    169: 
1.200     matthew   170: #------------------------------------------------------------------------
                    171: #
                    172: #   LocalConnection
                    173: #     Completes the formation of a locally authenticated connection.
                    174: #     This function will ensure that the 'remote' client is really the
                    175: #     local host.  If not, the connection is closed, and the function fails.
                    176: #     If so, initcmd is parsed for the name of a file containing the
                    177: #     IDEA session key.  The fie is opened, read, deleted and the session
                    178: #     key returned to the caller.
                    179: #
                    180: # Parameters:
                    181: #   $Socket      - Socket open on client.
                    182: #   $initcmd     - The full text of the init command.
                    183: #
                    184: # Implicit inputs:
                    185: #    $thisserver - Our DNS name.
                    186: #
                    187: # Returns:
                    188: #     IDEA session key on success.
                    189: #     undef on failure.
                    190: #
                    191: sub LocalConnection {
                    192:     my ($Socket, $initcmd) = @_;
1.277     albertel  193:     Debug("Attempting local connection: $initcmd client: $clientip me: $thisserver");
                    194:     if($clientip ne "127.0.0.1") {
1.200     matthew   195: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.277     albertel  196: 		 ."$clientip ne $thisserver </font>");
1.200     matthew   197: 	close $Socket;
                    198: 	return undef;
1.224     foxr      199:     }  else {
1.200     matthew   200: 	chomp($initcmd);	# Get rid of \n in filename.
                    201: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    202: 	Debug(" Init command: $init $type $name ");
                    203: 
                    204: 	# Require that $init = init, and $type = local:  Otherwise
                    205: 	# the caller is insane:
                    206: 
                    207: 	if(($init ne "init") && ($type ne "local")) {
                    208: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    209: 		     ."init = $init, and type = $type </font>");
                    210: 	    close($Socket);;
                    211: 	    return undef;
                    212: 		
                    213: 	}
                    214: 	#  Now get the key filename:
                    215: 
                    216: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    217: 	return $IDEAKey;
                    218:     }
                    219: }
                    220: #------------------------------------------------------------------------------
                    221: #
                    222: #  SSLConnection
                    223: #   Completes the formation of an ssh authenticated connection. The
                    224: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    225: #   certificate exchange are successful, the IDEA key is generated and sent
                    226: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    227: #   the caller after the SSL tunnel is torn down.
                    228: #
                    229: # Parameters:
                    230: #   Name              Type             Purpose
                    231: #   $Socket          IO::Socket::INET  Plaintext socket.
                    232: #
                    233: # Returns:
                    234: #    IDEA key on success.
                    235: #    undef on failure.
                    236: #
                    237: sub SSLConnection {
                    238:     my $Socket   = shift;
                    239: 
                    240:     Debug("SSLConnection: ");
                    241:     my $KeyFile         = lonssl::KeyFile();
                    242:     if(!$KeyFile) {
                    243: 	my $err = lonssl::LastError();
                    244: 	&logthis("<font color=\"red\"> CRITICAL"
                    245: 		 ."Can't get key file $err </font>");
                    246: 	return undef;
                    247:     }
                    248:     my ($CACertificate,
                    249: 	$Certificate) = lonssl::CertificateFile();
                    250: 
                    251: 
                    252:     # If any of the key, certificate or certificate authority 
                    253:     # certificate filenames are not defined, this can't work.
                    254: 
                    255:     if((!$Certificate) || (!$CACertificate)) {
                    256: 	my $err = lonssl::LastError();
                    257: 	&logthis("<font color=\"red\"> CRITICAL"
                    258: 		 ."Can't get certificates: $err </font>");
                    259: 
                    260: 	return undef;
                    261:     }
                    262:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    263: 
                    264:     # Indicate to our peer that we can procede with
                    265:     # a transition to ssl authentication:
                    266: 
                    267:     print $Socket "ok:ssl\n";
                    268: 
                    269:     Debug("Approving promotion -> ssl");
                    270:     #  And do so:
                    271: 
                    272:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    273: 						$CACertificate,
                    274: 						$Certificate,
                    275: 						$KeyFile);
                    276:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    277: 	my $err = lonssl::LastError();
                    278: 	&logthis("<font color=\"red\"> CRITICAL "
                    279: 		 ."SSL Socket promotion failed: $err </font>");
                    280: 	return undef;
                    281:     }
                    282:     Debug("SSL Promotion successful");
                    283: 
                    284:     # 
                    285:     #  The only thing we'll use the socket for is to send the IDEA key
                    286:     #  to the peer:
                    287: 
                    288:     my $Key = lonlocal::CreateCipherKey();
                    289:     print $SSLSocket "$Key\n";
                    290: 
                    291:     lonssl::Close($SSLSocket); 
                    292: 
                    293:     Debug("Key exchange complete: $Key");
                    294: 
                    295:     return $Key;
                    296: }
                    297: #
                    298: #     InsecureConnection: 
                    299: #        If insecure connections are allowd,
                    300: #        exchange a challenge with the client to 'validate' the
                    301: #        client (not really, but that's the protocol):
                    302: #        We produce a challenge string that's sent to the client.
                    303: #        The client must then echo the challenge verbatim to us.
                    304: #
                    305: #  Parameter:
                    306: #      Socket      - Socket open on the client.
                    307: #  Returns:
                    308: #      1           - success.
                    309: #      0           - failure (e.g.mismatch or insecure not allowed).
                    310: #
                    311: sub InsecureConnection {
                    312:     my $Socket  =  shift;
                    313: 
                    314:     #   Don't even start if insecure connections are not allowed.
                    315: 
                    316:     if(! $perlvar{londAllowInsecure}) {	# Insecure connections not allowed.
                    317: 	return 0;
                    318:     }
                    319: 
                    320:     #   Fabricate a challenge string and send it..
                    321: 
                    322:     my $challenge = "$$".time;	# pid + time.
                    323:     print $Socket "$challenge\n";
                    324:     &status("Waiting for challenge reply");
                    325: 
                    326:     my $answer = <$Socket>;
                    327:     $answer    =~s/\W//g;
                    328:     if($challenge eq $answer) {
                    329: 	return 1;
1.224     foxr      330:     } else {
1.200     matthew   331: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    332: 	&status("No challenge reqply");
                    333: 	return 0;
                    334:     }
                    335:     
                    336: 
                    337: }
1.251     foxr      338: #
                    339: #   Safely execute a command (as long as it's not a shel command and doesn
                    340: #   not require/rely on shell escapes.   The function operates by doing a
                    341: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    342: #
                    343: # Formal Parameters:
                    344: #     $line                    - A line of text to be executed as a command.
                    345: # Returns:
                    346: #     The output from that command.  If the output is multiline the caller
                    347: #     must know how to split up the output.
                    348: #
                    349: #
                    350: sub execute_command {
                    351:     my ($line)    = @_;
                    352:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    353:     my $output    = "";
                    354: 
                    355:     my $pid = open(CHILD, "-|");
                    356:     
                    357:     if($pid) {			# Parent process
                    358: 	Debug("In parent process for execute_command");
                    359: 	my @data = <CHILD>;	# Read the child's outupt...
                    360: 	close CHILD;
                    361: 	foreach my $output_line (@data) {
                    362: 	    Debug("Adding $output_line");
                    363: 	    $output .= $output_line; # Presumably has a \n on it.
                    364: 	}
                    365: 
                    366:     } else {			# Child process
                    367: 	close (STDERR);
                    368: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    369: 	exec(@words);		# won't return.
                    370:     }
                    371:     return $output;
                    372: }
                    373: 
1.200     matthew   374: 
1.140     foxr      375: #   GetCertificate: Given a transaction that requires a certificate,
                    376: #   this function will extract the certificate from the transaction
                    377: #   request.  Note that at this point, the only concept of a certificate
                    378: #   is the hostname to which we are connected.
                    379: #
                    380: #   Parameter:
                    381: #      request   - The request sent by our client (this parameterization may
                    382: #                  need to change when we really use a certificate granting
                    383: #                  authority.
                    384: #
                    385: sub GetCertificate {
                    386:     my $request = shift;
                    387: 
                    388:     return $clientip;
                    389: }
1.161     foxr      390: 
1.178     foxr      391: #
                    392: #   Return true if client is a manager.
                    393: #
                    394: sub isManager {
                    395:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    396: }
                    397: #
                    398: #   Return tru if client can do client functions
                    399: #
                    400: sub isClient {
                    401:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    402: }
1.161     foxr      403: 
                    404: 
1.156     foxr      405: #
                    406: #   ReadManagerTable: Reads in the current manager table. For now this is
                    407: #                     done on each manager authentication because:
                    408: #                     - These authentications are not frequent
                    409: #                     - This allows dynamic changes to the manager table
                    410: #                       without the need to signal to the lond.
                    411: #
                    412: sub ReadManagerTable {
                    413: 
                    414:     #   Clean out the old table first..
                    415: 
1.166     foxr      416:    foreach my $key (keys %managers) {
                    417:       delete $managers{$key};
                    418:    }
                    419: 
                    420:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    421:    if (!open (MANAGERS, $tablename)) {
                    422:       logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    423:       return;
                    424:    }
                    425:    while(my $host = <MANAGERS>) {
                    426:       chomp($host);
                    427:       if ($host =~ "^#") {                  # Comment line.
                    428:          next;
                    429:       }
                    430:       if (!defined $hostip{$host}) { # This is a non cluster member
1.161     foxr      431: 	    #  The entry is of the form:
                    432: 	    #    cluname:hostname
                    433: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    434: 	    #            the host key.
                    435: 	    #  hostname- The dns name of the host.
                    436: 	    #
1.166     foxr      437:           my($cluname, $dnsname) = split(/:/, $host);
                    438:           
                    439:           my $ip = gethostbyname($dnsname);
                    440:           if(defined($ip)) {                 # bad names don't deserve entry.
                    441:             my $hostip = inet_ntoa($ip);
                    442:             $managers{$hostip} = $cluname;
                    443:             logthis('<font color="green"> registering manager '.
                    444:                     "$dnsname as $cluname with $hostip </font>\n");
                    445:          }
                    446:       } else {
                    447:          logthis('<font color="green"> existing host'." $host</font>\n");
                    448:          $managers{$hostip{$host}} = $host;  # Use info from cluster tab if clumemeber
                    449:       }
                    450:    }
1.156     foxr      451: }
1.140     foxr      452: 
                    453: #
                    454: #  ValidManager: Determines if a given certificate represents a valid manager.
                    455: #                in this primitive implementation, the 'certificate' is
                    456: #                just the connecting loncapa client name.  This is checked
                    457: #                against a valid client list in the configuration.
                    458: #
                    459: #                  
                    460: sub ValidManager {
                    461:     my $certificate = shift; 
                    462: 
1.163     foxr      463:     return isManager;
1.140     foxr      464: }
                    465: #
1.143     foxr      466: #  CopyFile:  Called as part of the process of installing a 
                    467: #             new configuration file.  This function copies an existing
                    468: #             file to a backup file.
                    469: # Parameters:
                    470: #     oldfile  - Name of the file to backup.
                    471: #     newfile  - Name of the backup file.
                    472: # Return:
                    473: #     0   - Failure (errno has failure reason).
                    474: #     1   - Success.
                    475: #
                    476: sub CopyFile {
1.192     foxr      477: 
                    478:     my ($oldfile, $newfile) = @_;
1.143     foxr      479: 
1.281     matthew   480:     if (! copy($oldfile,$newfile)) {
                    481:         return 0;
1.143     foxr      482:     }
1.281     matthew   483:     chmod(0660, $newfile);
                    484:     return 1;
1.143     foxr      485: }
1.157     foxr      486: #
                    487: #  Host files are passed out with externally visible host IPs.
                    488: #  If, for example, we are behind a fire-wall or NAT host, our 
                    489: #  internally visible IP may be different than the externally
                    490: #  visible IP.  Therefore, we always adjust the contents of the
                    491: #  host file so that the entry for ME is the IP that we believe
                    492: #  we have.  At present, this is defined as the entry that
                    493: #  DNS has for us.  If by some chance we are not able to get a
                    494: #  DNS translation for us, then we assume that the host.tab file
                    495: #  is correct.  
                    496: #    BUGBUGBUG - in the future, we really should see if we can
                    497: #       easily query the interface(s) instead.
                    498: # Parameter(s):
                    499: #     contents    - The contents of the host.tab to check.
                    500: # Returns:
                    501: #     newcontents - The adjusted contents.
                    502: #
                    503: #
                    504: sub AdjustHostContents {
                    505:     my $contents  = shift;
                    506:     my $adjusted;
                    507:     my $me        = $perlvar{'lonHostID'};
                    508: 
1.166     foxr      509:  foreach my $line (split(/\n/,$contents)) {
1.157     foxr      510: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
                    511: 	    chomp($line);
                    512: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    513: 	    if ($id eq $me) {
1.166     foxr      514:           my $ip = gethostbyname($name);
                    515:           my $ipnew = inet_ntoa($ip);
                    516:          $ip = $ipnew;
1.157     foxr      517: 		#  Reconstruct the host line and append to adjusted:
                    518: 		
1.166     foxr      519: 		   my $newline = "$id:$domain:$role:$name:$ip";
                    520: 		   if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    521: 		     $newline .= ":$maxcon:$idleto:$mincon";
                    522: 		   }
                    523: 		   $adjusted .= $newline."\n";
1.157     foxr      524: 		
1.166     foxr      525:       } else {		# Not me, pass unmodified.
                    526: 		   $adjusted .= $line."\n";
                    527:       }
1.157     foxr      528: 	} else {                  # Blank or comment never re-written.
                    529: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    530: 	}
1.166     foxr      531:  }
                    532:  return $adjusted;
1.157     foxr      533: }
1.143     foxr      534: #
                    535: #   InstallFile: Called to install an administrative file:
                    536: #       - The file is created with <name>.tmp
                    537: #       - The <name>.tmp file is then mv'd to <name>
                    538: #   This lugubrious procedure is done to ensure that we are never without
                    539: #   a valid, even if dated, version of the file regardless of who crashes
                    540: #   and when the crash occurs.
                    541: #
                    542: #  Parameters:
                    543: #       Name of the file
                    544: #       File Contents.
                    545: #  Return:
                    546: #      nonzero - success.
                    547: #      0       - failure and $! has an errno.
                    548: #
                    549: sub InstallFile {
1.192     foxr      550: 
                    551:     my ($Filename, $Contents) = @_;
1.143     foxr      552:     my $TempFile = $Filename.".tmp";
                    553: 
                    554:     #  Open the file for write:
                    555: 
                    556:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    557:     if(!(defined $fh)) {
                    558: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    559: 	return 0;
                    560:     }
                    561:     #  write the contents of the file:
                    562: 
                    563:     print $fh ($Contents); 
                    564:     $fh->close;			# In case we ever have a filesystem w. locking
                    565: 
                    566:     chmod(0660, $TempFile);
                    567: 
                    568:     # Now we can move install the file in position.
                    569:     
                    570:     move($TempFile, $Filename);
                    571: 
                    572:     return 1;
                    573: }
1.200     matthew   574: 
                    575: 
1.169     foxr      576: #
                    577: #   ConfigFileFromSelector: converts a configuration file selector
                    578: #                 (one of host or domain at this point) into a 
                    579: #                 configuration file pathname.
                    580: #
                    581: #  Parameters:
                    582: #      selector  - Configuration file selector.
                    583: #  Returns:
                    584: #      Full path to the file or undef if the selector is invalid.
                    585: #
                    586: sub ConfigFileFromSelector {
                    587:     my $selector   = shift;
                    588:     my $tablefile;
                    589: 
                    590:     my $tabledir = $perlvar{'lonTabDir'}.'/';
                    591:     if ($selector eq "hosts") {
                    592: 	$tablefile = $tabledir."hosts.tab";
                    593:     } elsif ($selector eq "domain") {
                    594: 	$tablefile = $tabledir."domain.tab";
                    595:     } else {
                    596: 	return undef;
                    597:     }
                    598:     return $tablefile;
1.143     foxr      599: 
1.169     foxr      600: }
1.143     foxr      601: #
1.141     foxr      602: #   PushFile:  Called to do an administrative push of a file.
                    603: #              - Ensure the file being pushed is one we support.
                    604: #              - Backup the old file to <filename.saved>
                    605: #              - Separate the contents of the new file out from the
                    606: #                rest of the request.
                    607: #              - Write the new file.
                    608: #  Parameter:
                    609: #     Request - The entire user request.  This consists of a : separated
                    610: #               string pushfile:tablename:contents.
                    611: #     NOTE:  The contents may have :'s in it as well making things a bit
                    612: #            more interesting... but not much.
                    613: #  Returns:
                    614: #     String to send to client ("ok" or "refused" if bad file).
                    615: #
                    616: sub PushFile {
                    617:     my $request = shift;    
                    618:     my ($command, $filename, $contents) = split(":", $request, 3);
                    619:     
                    620:     #  At this point in time, pushes for only the following tables are
                    621:     #  supported:
                    622:     #   hosts.tab  ($filename eq host).
                    623:     #   domain.tab ($filename eq domain).
                    624:     # Construct the destination filename or reject the request.
                    625:     #
                    626:     # lonManage is supposed to ensure this, however this session could be
                    627:     # part of some elaborate spoof that managed somehow to authenticate.
                    628:     #
                    629: 
1.169     foxr      630: 
                    631:     my $tablefile = ConfigFileFromSelector($filename);
                    632:     if(! (defined $tablefile)) {
1.141     foxr      633: 	return "refused";
                    634:     }
                    635:     #
                    636:     # >copy< the old table to the backup table
                    637:     #        don't rename in case system crashes/reboots etc. in the time
                    638:     #        window between a rename and write.
                    639:     #
                    640:     my $backupfile = $tablefile;
                    641:     $backupfile    =~ s/\.tab$/.old/;
1.143     foxr      642:     if(!CopyFile($tablefile, $backupfile)) {
                    643: 	&logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
                    644: 	return "error:$!";
                    645:     }
1.141     foxr      646:     &logthis('<font color="green"> Pushfile: backed up '
                    647: 	    .$tablefile." to $backupfile</font>");
                    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);
                    657:     }
                    658: 
1.141     foxr      659:     #  Install the new file:
                    660: 
1.143     foxr      661:     if(!InstallFile($tablefile, $contents)) {
                    662: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      663: 	 .$tablefile." $! </font>");
1.143     foxr      664: 	return "error:$!";
1.224     foxr      665:     } else {
1.143     foxr      666: 	&logthis('<font color="green"> Installed new '.$tablefile
                    667: 		 ."</font>");
                    668: 
                    669:     }
                    670: 
1.141     foxr      671: 
                    672:     #  Indicate success:
                    673:  
                    674:     return "ok";
                    675: 
                    676: }
1.145     foxr      677: 
                    678: #
                    679: #  Called to re-init either lonc or lond.
                    680: #
                    681: #  Parameters:
                    682: #    request   - The full request by the client.  This is of the form
                    683: #                reinit:<process>  
                    684: #                where <process> is allowed to be either of 
                    685: #                lonc or lond
                    686: #
                    687: #  Returns:
                    688: #     The string to be sent back to the client either:
                    689: #   ok         - Everything worked just fine.
                    690: #   error:why  - There was a failure and why describes the reason.
                    691: #
                    692: #
                    693: sub ReinitProcess {
                    694:     my $request = shift;
                    695: 
1.146     foxr      696: 
                    697:     # separate the request (reinit) from the process identifier and
                    698:     # validate it producing the name of the .pid file for the process.
                    699:     #
                    700:     #
                    701:     my ($junk, $process) = split(":", $request);
1.147     foxr      702:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      703:     if($process eq 'lonc') {
                    704: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      705: 	if (!open(PIDFILE, "< $processpidfile")) {
                    706: 	    return "error:Open failed for $processpidfile";
                    707: 	}
                    708: 	my $loncpid = <PIDFILE>;
                    709: 	close(PIDFILE);
                    710: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    711: 		."</font>");
                    712: 	kill("USR2", $loncpid);
1.146     foxr      713:     } elsif ($process eq 'lond') {
1.147     foxr      714: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    715: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      716:     } else {
                    717: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    718: 		 ."</font>");
                    719: 	return "error:Invalid process identifier $process";
                    720:     }
1.145     foxr      721:     return 'ok';
                    722: }
1.168     foxr      723: #   Validate a line in a configuration file edit script:
                    724: #   Validation includes:
                    725: #     - Ensuring the command is valid.
                    726: #     - Ensuring the command has sufficient parameters
                    727: #   Parameters:
                    728: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      729: #
1.168     foxr      730: #   Return:
                    731: #      0     - Invalid scriptline.
                    732: #      1     - Valid scriptline
                    733: #  NOTE:
                    734: #     Only the command syntax is checked, not the executability of the
                    735: #     command.
                    736: #
                    737: sub isValidEditCommand {
                    738:     my $scriptline = shift;
                    739: 
                    740:     #   Line elements are pipe separated:
                    741: 
                    742:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                    743:     &logthis('<font color="green"> isValideditCommand checking: '.
                    744: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                    745:     
                    746:     if ($command eq "delete") {
                    747: 	#
                    748: 	#   key with no newline.
                    749: 	#
                    750: 	if( ($key eq "") || ($newline ne "")) {
                    751: 	    return 0;		# Must have key but no newline.
                    752: 	} else {
                    753: 	    return 1;		# Valid syntax.
                    754: 	}
1.169     foxr      755:     } elsif ($command eq "replace") {
1.168     foxr      756: 	#
                    757: 	#   key and newline:
                    758: 	#
                    759: 	if (($key eq "") || ($newline eq "")) {
                    760: 	    return 0;
                    761: 	} else {
                    762: 	    return 1;
                    763: 	}
1.169     foxr      764:     } elsif ($command eq "append") {
                    765: 	if (($key ne "") && ($newline eq "")) {
                    766: 	    return 1;
                    767: 	} else {
                    768: 	    return 0;
                    769: 	}
1.168     foxr      770:     } else {
                    771: 	return 0;		# Invalid command.
                    772:     }
                    773:     return 0;			# Should not get here!!!
                    774: }
1.169     foxr      775: #
                    776: #   ApplyEdit - Applies an edit command to a line in a configuration 
                    777: #               file.  It is the caller's responsiblity to validate the
                    778: #               edit line.
                    779: #   Parameters:
                    780: #      $directive - A single edit directive to apply.  
                    781: #                   Edit directives are of the form:
                    782: #                  append|newline      - Appends a new line to the file.
                    783: #                  replace|key|newline - Replaces the line with key value 'key'
                    784: #                  delete|key          - Deletes the line with key value 'key'.
                    785: #      $editor   - A config file editor object that contains the
                    786: #                  file being edited.
                    787: #
                    788: sub ApplyEdit {
1.192     foxr      789: 
                    790:     my ($directive, $editor) = @_;
1.169     foxr      791: 
                    792:     # Break the directive down into its command and its parameters
                    793:     # (at most two at this point.  The meaning of the parameters, if in fact
                    794:     #  they exist depends on the command).
                    795: 
                    796:     my ($command, $p1, $p2) = split(/\|/, $directive);
                    797: 
                    798:     if($command eq "append") {
                    799: 	$editor->Append($p1);	          # p1 - key p2 null.
                    800:     } elsif ($command eq "replace") {
                    801: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                    802:     } elsif ($command eq "delete") {
                    803: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                    804:     } else {			          # Should not get here!!!
                    805: 	die "Invalid command given to ApplyEdit $command"
                    806:     }
                    807: }
                    808: #
                    809: # AdjustOurHost:
                    810: #           Adjusts a host file stored in a configuration file editor object
                    811: #           for the true IP address of this host. This is necessary for hosts
                    812: #           that live behind a firewall.
                    813: #           Those hosts have a publicly distributed IP of the firewall, but
                    814: #           internally must use their actual IP.  We assume that a given
                    815: #           host only has a single IP interface for now.
                    816: # Formal Parameters:
                    817: #     editor   - The configuration file editor to adjust.  This
                    818: #                editor is assumed to contain a hosts.tab file.
                    819: # Strategy:
                    820: #    - Figure out our hostname.
                    821: #    - Lookup the entry for this host.
                    822: #    - Modify the line to contain our IP
                    823: #    - Do a replace for this host.
                    824: sub AdjustOurHost {
                    825:     my $editor        = shift;
                    826: 
                    827:     # figure out who I am.
                    828: 
                    829:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                    830: 
                    831:     #  Get my host file entry.
                    832: 
                    833:     my $ConfigLine    = $editor->Find($myHostName);
                    834:     if(! (defined $ConfigLine)) {
                    835: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                    836:     }
                    837:     # figure out my IP:
                    838:     #   Use the config line to get my hostname.
                    839:     #   Use gethostbyname to translate that into an IP address.
                    840:     #
                    841:     my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
                    842:     my $BinaryIp = gethostbyname($name);
                    843:     my $ip       = inet_ntoa($ip);
                    844:     #
                    845:     #  Reassemble the config line from the elements in the list.
                    846:     #  Note that if the loncnew items were not present before, they will
                    847:     #  be now even if they would be empty
                    848:     #
                    849:     my $newConfigLine = $id;
                    850:     foreach my $item ($domain, $role, $name, $ip, $maxcon, $idleto, $mincon) {
                    851: 	$newConfigLine .= ":".$item;
                    852:     }
                    853:     #  Replace the line:
                    854: 
                    855:     $editor->ReplaceLine($id, $newConfigLine);
                    856:     
                    857: }
                    858: #
                    859: #   ReplaceConfigFile:
                    860: #              Replaces a configuration file with the contents of a
                    861: #              configuration file editor object.
                    862: #              This is done by:
                    863: #              - Copying the target file to <filename>.old
                    864: #              - Writing the new file to <filename>.tmp
                    865: #              - Moving <filename.tmp>  -> <filename>
                    866: #              This laborious process ensures that the system is never without
                    867: #              a configuration file that's at least valid (even if the contents
                    868: #              may be dated).
                    869: #   Parameters:
                    870: #        filename   - Name of the file to modify... this is a full path.
                    871: #        editor     - Editor containing the file.
                    872: #
                    873: sub ReplaceConfigFile {
1.192     foxr      874:     
                    875:     my ($filename, $editor) = @_;
1.168     foxr      876: 
1.169     foxr      877:     CopyFile ($filename, $filename.".old");
                    878: 
                    879:     my $contents  = $editor->Get(); # Get the contents of the file.
                    880: 
                    881:     InstallFile($filename, $contents);
                    882: }
1.168     foxr      883: #   
                    884: #
                    885: #   Called to edit a configuration table  file
1.167     foxr      886: #   Parameters:
                    887: #      request           - The entire command/request sent by lonc or lonManage
                    888: #   Return:
                    889: #      The reply to send to the client.
1.168     foxr      890: #
1.167     foxr      891: sub EditFile {
                    892:     my $request = shift;
                    893: 
                    894:     #  Split the command into it's pieces:  edit:filetype:script
                    895: 
1.168     foxr      896:     my ($request, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr      897: 
                    898:     #  Check the pre-coditions for success:
                    899: 
                    900:     if($request != "edit") {	# Something is amiss afoot alack.
                    901: 	return "error:edit request detected, but request != 'edit'\n";
                    902:     }
                    903:     if( ($filetype ne "hosts")  &&
                    904: 	($filetype ne "domain")) {
                    905: 	return "error:edit requested with invalid file specifier: $filetype \n";
                    906:     }
                    907: 
                    908:     #   Split the edit script and check it's validity.
1.168     foxr      909: 
                    910:     my @scriptlines = split(/\n/, $script);  # one line per element.
                    911:     my $linecount   = scalar(@scriptlines);
                    912:     for(my $i = 0; $i < $linecount; $i++) {
                    913: 	chomp($scriptlines[$i]);
                    914: 	if(!isValidEditCommand($scriptlines[$i])) {
                    915: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                    916: 	}
                    917:     }
1.145     foxr      918: 
1.167     foxr      919:     #   Execute the edit operation.
1.169     foxr      920:     #   - Create a config file editor for the appropriate file and 
                    921:     #   - execute each command in the script:
                    922:     #
                    923:     my $configfile = ConfigFileFromSelector($filetype);
                    924:     if (!(defined $configfile)) {
                    925: 	return "refused\n";
                    926:     }
                    927:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr      928: 
1.169     foxr      929:     for (my $i = 0; $i < $linecount; $i++) {
                    930: 	ApplyEdit($scriptlines[$i], $editor);
                    931:     }
                    932:     # If the file is the host file, ensure that our host is
                    933:     # adjusted to have our ip:
                    934:     #
                    935:     if($filetype eq "host") {
                    936: 	AdjustOurHost($editor);
                    937:     }
                    938:     #  Finally replace the current file with our file.
                    939:     #
                    940:     ReplaceConfigFile($configfile, $editor);
1.167     foxr      941: 
                    942:     return "ok\n";
                    943: }
1.207     foxr      944: 
                    945: #---------------------------------------------------------------
                    946: #
                    947: # Manipulation of hash based databases (factoring out common code
                    948: # for later use as we refactor.
                    949: #
                    950: #  Ties a domain level resource file to a hash.
                    951: #  If requested a history entry is created in the associated hist file.
                    952: #
                    953: #  Parameters:
                    954: #     domain    - Name of the domain in which the resource file lives.
                    955: #     namespace - Name of the hash within that domain.
                    956: #     how       - How to tie the hash (e.g. GDBM_WRCREAT()).
                    957: #     loghead   - Optional parameter, if present a log entry is created
                    958: #                 in the associated history file and this is the first part
                    959: #                  of that entry.
                    960: #     logtail   - Goes along with loghead,  The actual logentry is of the
                    961: #                 form $loghead:<timestamp>:logtail.
                    962: # Returns:
                    963: #    Reference to a hash bound to the db file or alternatively undef
                    964: #    if the tie failed.
                    965: #
1.209     albertel  966: sub tie_domain_hash {
1.210     albertel  967:     my ($domain,$namespace,$how,$loghead,$logtail) = @_;
1.207     foxr      968:     
                    969:     # Filter out any whitespace in the domain name:
                    970:     
                    971:     $domain =~ s/\W//g;
                    972:     
                    973:     # We have enough to go on to tie the hash:
                    974:     
                    975:     my $user_top_dir   = $perlvar{'lonUsersDir'};
                    976:     my $domain_dir     = $user_top_dir."/$domain";
1.312     albertel  977:     my $resource_file  = $domain_dir."/$namespace";
1.313     albertel  978:     return &_locking_hash_tie($resource_file,$namespace,$how,$loghead,$logtail);
1.207     foxr      979: }
                    980: 
1.311     albertel  981: sub untie_domain_hash {
1.313     albertel  982:     return &_locking_hash_untie(@_);
1.311     albertel  983: }
1.207     foxr      984: #
                    985: #   Ties a user's resource file to a hash.  
                    986: #   If necessary, an appropriate history
                    987: #   log file entry is made as well.
                    988: #   This sub factors out common code from the subs that manipulate
                    989: #   the various gdbm files that keep keyword value pairs.
                    990: # Parameters:
                    991: #   domain       - Name of the domain the user is in.
                    992: #   user         - Name of the 'current user'.
                    993: #   namespace    - Namespace representing the file to tie.
                    994: #   how          - What the tie is done to (e.g. GDBM_WRCREAT().
                    995: #   loghead      - Optional first part of log entry if there may be a
                    996: #                  history file.
                    997: #   what         - Optional tail of log entry if there may be a history
                    998: #                  file.
                    999: # Returns:
                   1000: #   hash to which the database is tied.  It's up to the caller to untie.
                   1001: #   undef if the has could not be tied.
                   1002: #
1.210     albertel 1003: sub tie_user_hash {
                   1004:     my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
1.207     foxr     1005: 
                   1006:     $namespace=~s/\//\_/g;	# / -> _
                   1007:     $namespace=~s/\W//g;		# whitespace eliminated.
                   1008:     my $proname     = propath($domain, $user);
1.312     albertel 1009: 
                   1010:     my $file_prefix="$proname/$namespace";
1.313     albertel 1011:     return &_locking_hash_tie($file_prefix,$namespace,$how,$loghead,$what);
1.312     albertel 1012: }
                   1013: 
                   1014: sub untie_user_hash {
1.313     albertel 1015:     return &_locking_hash_untie(@_);
1.312     albertel 1016: }
                   1017: 
                   1018: # internal routines that handle the actual tieing and untieing process
                   1019: 
                   1020: sub _do_hash_tie {
                   1021:     my ($file_prefix,$namespace,$how,$loghead,$what) = @_;
1.207     foxr     1022:     my %hash;
1.312     albertel 1023:     if(tie(%hash, 'GDBM_File', "$file_prefix.db", $how, 0640)) {
1.209     albertel 1024: 	# If this is a namespace for which a history is kept,
                   1025: 	# make the history log entry:    
1.252     albertel 1026: 	if (($namespace !~/^nohist\_/) && (defined($loghead))) {
1.209     albertel 1027: 	    my $args = scalar @_;
1.312     albertel 1028: 	    Debug(" Opening history: $file_prefix $args");
                   1029: 	    my $hfh = IO::File->new(">>$file_prefix.hist"); 
1.209     albertel 1030: 	    if($hfh) {
                   1031: 		my $now = time;
                   1032: 		print $hfh "$loghead:$now:$what\n";
                   1033: 	    }
1.210     albertel 1034: 	    $hfh->close;
1.209     albertel 1035: 	}
1.207     foxr     1036: 	return \%hash;
1.209     albertel 1037:     } else {
1.207     foxr     1038: 	return undef;
                   1039:     }
                   1040: }
1.214     foxr     1041: 
1.312     albertel 1042: sub _do_hash_untie {
1.311     albertel 1043:     my ($hashref) = @_;
                   1044:     my $result = untie(%$hashref);
                   1045:     return $result;
                   1046: }
1.313     albertel 1047: 
                   1048: {
                   1049:     my $sym;
                   1050: 
                   1051:     sub _locking_hash_tie {
                   1052: 	my ($file_prefix,$namespace,$how,$loghead,$what) = @_;
                   1053: 
                   1054: 	my ($lock);
                   1055:     
                   1056: 	if ($how eq &GDBM_READER()) {
                   1057: 	    $lock=LOCK_SH;
                   1058: 	    $how=$how|&GDBM_NOLOCK();
                   1059: 	    #if the db doesn't exist we can't read from it
                   1060: 	    if (! -e "$file_prefix.db") {
                   1061: 		$! = 2;
                   1062: 		return undef;
                   1063: 	    }
                   1064: 	} elsif ($how eq &GDBM_WRCREAT()) {
                   1065: 	    $lock=LOCK_EX;
                   1066: 	    $how=$how|&GDBM_NOLOCK();
                   1067: 	    if (! -e "$file_prefix.db") {
                   1068: 		# doesn't exist but we need it to in order to successfully
                   1069:                 # lock it so bring it into existance
                   1070: 		open(TOUCH,">>$file_prefix.db");
                   1071: 		close(TOUCH);
                   1072: 	    }
                   1073: 	} else {
                   1074: 	    &logthis("Unknown method $how for $file_prefix");
                   1075: 	    die();
                   1076: 	}
                   1077:     
                   1078: 	$sym=&Symbol::gensym();
                   1079: 	open($sym,"$file_prefix.db");
                   1080: 	my $failed=0;
                   1081: 	eval {
                   1082: 	    local $SIG{__DIE__}='DEFAULT';
                   1083: 	    local $SIG{ALRM}=sub { 
                   1084: 		$failed=1;
                   1085: 		die("failed lock");
                   1086: 	    };
                   1087: 	    alarm($lond_max_wait_time);
                   1088: 	    flock($sym,$lock);
                   1089: 	    alarm(0);
                   1090: 	};
                   1091: 	if ($failed) {
                   1092: 	    $! = 100; # throwing error # 100
                   1093: 	    return undef;
                   1094: 	}
                   1095: 	return &_do_hash_tie($file_prefix,$namespace,$how,$loghead,$what);
                   1096:     }
                   1097: 
                   1098:     sub _locking_hash_untie {
                   1099: 	my ($hashref) = @_;
                   1100: 	my $result = untie(%$hashref);
                   1101: 	flock($sym,LOCK_UN);
                   1102: 	close($sym);
                   1103: 	undef($sym);
                   1104: 	return $result;
                   1105:     }
                   1106: }
                   1107: 
1.255     foxr     1108: #   read_profile
                   1109: #
                   1110: #   Returns a set of specific entries from a user's profile file.
                   1111: #   this is a utility function that is used by both get_profile_entry and
                   1112: #   get_profile_entry_encrypted.
                   1113: #
                   1114: # Parameters:
                   1115: #    udom       - Domain in which the user exists.
                   1116: #    uname      - User's account name (loncapa account)
                   1117: #    namespace  - The profile namespace to open.
                   1118: #    what       - A set of & separated queries.
                   1119: # Returns:
                   1120: #    If all ok: - The string that needs to be shipped back to the user.
                   1121: #    If failure - A string that starts with error: followed by the failure
                   1122: #                 reason.. note that this probabyl gets shipped back to the
                   1123: #                 user as well.
                   1124: #
                   1125: sub read_profile {
                   1126:     my ($udom, $uname, $namespace, $what) = @_;
                   1127:     
                   1128:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1129: 				 &GDBM_READER());
                   1130:     if ($hashref) {
                   1131:         my @queries=split(/\&/,$what);
                   1132:         my $qresult='';
                   1133: 	
                   1134: 	for (my $i=0;$i<=$#queries;$i++) {
                   1135: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1136: 	}
                   1137: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1138: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1139: 	    return $qresult;
                   1140: 	} else {
                   1141: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1142: 	}
                   1143:     } else {
                   1144: 	if ($!+0 == 2) {
                   1145: 	    return "error:No such file or GDBM reported bad block error";
                   1146: 	} else {
                   1147: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1148: 	}
                   1149:     }
                   1150: 
                   1151: }
1.214     foxr     1152: #--------------------- Request Handlers --------------------------------------------
                   1153: #
1.215     foxr     1154: #   By convention each request handler registers itself prior to the sub 
                   1155: #   declaration:
1.214     foxr     1156: #
                   1157: 
1.216     foxr     1158: #++
                   1159: #
1.214     foxr     1160: #  Handles ping requests.
                   1161: #  Parameters:
                   1162: #      $cmd    - the actual keyword that invoked us.
                   1163: #      $tail   - the tail of the request that invoked us.
                   1164: #      $replyfd- File descriptor connected to the client
                   1165: #  Implicit Inputs:
                   1166: #      $currenthostid - Global variable that carries the name of the host we are
                   1167: #                       known as.
                   1168: #  Returns:
                   1169: #      1       - Ok to continue processing.
                   1170: #      0       - Program should exit.
                   1171: #  Side effects:
                   1172: #      Reply information is sent to the client.
                   1173: sub ping_handler {
                   1174:     my ($cmd, $tail, $client) = @_;
                   1175:     Debug("$cmd $tail $client .. $currenthostid:");
                   1176:    
                   1177:     Reply( $client,"$currenthostid\n","$cmd:$tail");
                   1178:    
                   1179:     return 1;
                   1180: }
                   1181: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1182: 
1.216     foxr     1183: #++
1.215     foxr     1184: #
                   1185: # Handles pong requests.  Pong replies with our current host id, and
                   1186: #                         the results of a ping sent to us via our lonc.
                   1187: #
                   1188: # Parameters:
                   1189: #      $cmd    - the actual keyword that invoked us.
                   1190: #      $tail   - the tail of the request that invoked us.
                   1191: #      $replyfd- File descriptor connected to the client
                   1192: #  Implicit Inputs:
                   1193: #      $currenthostid - Global variable that carries the name of the host we are
                   1194: #                       connected to.
                   1195: #  Returns:
                   1196: #      1       - Ok to continue processing.
                   1197: #      0       - Program should exit.
                   1198: #  Side effects:
                   1199: #      Reply information is sent to the client.
                   1200: sub pong_handler {
                   1201:     my ($cmd, $tail, $replyfd) = @_;
                   1202: 
                   1203:     my $reply=&reply("ping",$clientname);
                   1204:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1205:     return 1;
                   1206: }
                   1207: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1208: 
1.216     foxr     1209: #++
                   1210: #      Called to establish an encrypted session key with the remote client.
                   1211: #      Note that with secure lond, in most cases this function is never
                   1212: #      invoked.  Instead, the secure session key is established either
                   1213: #      via a local file that's locked down tight and only lives for a short
                   1214: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1215: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1216: #      by this sub.  This sub is only used in the old-style insecure
                   1217: #      key negotiation.
                   1218: # Parameters:
                   1219: #      $cmd    - the actual keyword that invoked us.
                   1220: #      $tail   - the tail of the request that invoked us.
                   1221: #      $replyfd- File descriptor connected to the client
                   1222: #  Implicit Inputs:
                   1223: #      $currenthostid - Global variable that carries the name of the host
                   1224: #                       known as.
                   1225: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
                   1226: #  Returns:
                   1227: #      1       - Ok to continue processing.
                   1228: #      0       - Program should exit.
                   1229: #  Implicit Outputs:
                   1230: #      Reply information is sent to the client.
                   1231: #      $cipher is set with a reference to a new IDEA encryption object.
                   1232: #
                   1233: sub establish_key_handler {
                   1234:     my ($cmd, $tail, $replyfd) = @_;
                   1235: 
                   1236:     my $buildkey=time.$$.int(rand 100000);
                   1237:     $buildkey=~tr/1-6/A-F/;
                   1238:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1239:     my $key=$currenthostid.$clientname;
                   1240:     $key=~tr/a-z/A-Z/;
                   1241:     $key=~tr/G-P/0-9/;
                   1242:     $key=~tr/Q-Z/0-9/;
                   1243:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1244:     $key=substr($key,0,32);
                   1245:     my $cipherkey=pack("H32",$key);
                   1246:     $cipher=new IDEA $cipherkey;
                   1247:     &Reply($replyfd, "$buildkey\n", "$cmd:$tail"); 
                   1248:    
                   1249:     return 1;
                   1250: 
                   1251: }
                   1252: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1253: 
1.217     foxr     1254: #     Handler for the load command.  Returns the current system load average
                   1255: #     to the requestor.
                   1256: #
                   1257: # Parameters:
                   1258: #      $cmd    - the actual keyword that invoked us.
                   1259: #      $tail   - the tail of the request that invoked us.
                   1260: #      $replyfd- File descriptor connected to the client
                   1261: #  Implicit Inputs:
                   1262: #      $currenthostid - Global variable that carries the name of the host
                   1263: #                       known as.
                   1264: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
                   1265: #  Returns:
                   1266: #      1       - Ok to continue processing.
                   1267: #      0       - Program should exit.
                   1268: #  Side effects:
                   1269: #      Reply information is sent to the client.
                   1270: sub load_handler {
                   1271:     my ($cmd, $tail, $replyfd) = @_;
                   1272: 
                   1273:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1274:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1275: 
                   1276:     my $loadavg;
                   1277:     my $loadfile=IO::File->new('/proc/loadavg');
                   1278:    
                   1279:     $loadavg=<$loadfile>;
                   1280:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1281:    
                   1282:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1283: 
                   1284:     &Reply( $replyfd, "$loadpercent\n", "$cmd:$tail");
                   1285:    
                   1286:     return 1;
                   1287: }
1.263     albertel 1288: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1289: 
                   1290: #
                   1291: #   Process the userload request.  This sub returns to the client the current
                   1292: #  user load average.  It can be invoked either by clients or managers.
                   1293: #
                   1294: # Parameters:
                   1295: #      $cmd    - the actual keyword that invoked us.
                   1296: #      $tail   - the tail of the request that invoked us.
                   1297: #      $replyfd- File descriptor connected to the client
                   1298: #  Implicit Inputs:
                   1299: #      $currenthostid - Global variable that carries the name of the host
                   1300: #                       known as.
                   1301: #      $clientname    - Global variable that carries the name of the hsot we're connected to.
                   1302: #  Returns:
                   1303: #      1       - Ok to continue processing.
                   1304: #      0       - Program should exit
                   1305: # Implicit inputs:
                   1306: #     whatever the userload() function requires.
                   1307: #  Implicit outputs:
                   1308: #     the reply is written to the client.
                   1309: #
                   1310: sub user_load_handler {
                   1311:     my ($cmd, $tail, $replyfd) = @_;
                   1312: 
                   1313:     my $userloadpercent=&userload();
                   1314:     &Reply($replyfd, "$userloadpercent\n", "$cmd:$tail");
                   1315:     
                   1316:     return 1;
                   1317: }
1.263     albertel 1318: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1319: 
1.218     foxr     1320: #   Process a request for the authorization type of a user:
                   1321: #   (userauth).
                   1322: #
                   1323: # Parameters:
                   1324: #      $cmd    - the actual keyword that invoked us.
                   1325: #      $tail   - the tail of the request that invoked us.
                   1326: #      $replyfd- File descriptor connected to the client
                   1327: #  Returns:
                   1328: #      1       - Ok to continue processing.
                   1329: #      0       - Program should exit
                   1330: # Implicit outputs:
                   1331: #    The user authorization type is written to the client.
                   1332: #
                   1333: sub user_authorization_type {
                   1334:     my ($cmd, $tail, $replyfd) = @_;
                   1335:    
                   1336:     my $userinput = "$cmd:$tail";
                   1337:    
                   1338:     #  Pull the domain and username out of the command tail.
1.222     foxr     1339:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1340:    
                   1341:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1342:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1343:     if($result eq "nouser") {
                   1344: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1345:     } else {
                   1346: 	#
1.222     foxr     1347: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1348: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1349: 	# password for internals e.g.
                   1350: 	#
                   1351: 	my ($type,$otherinfo) = split(/:/,$result);
                   1352: 	if($type =~ /^krb/) {
                   1353: 	    $type = $result;
1.269     raeburn  1354: 	} else {
                   1355:             $type .= ':';
                   1356:         }
                   1357: 	&Reply( $replyfd, "$type\n", $userinput);
1.218     foxr     1358:     }
                   1359:   
                   1360:     return 1;
                   1361: }
                   1362: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1363: 
                   1364: #   Process a request by a manager to push a hosts or domain table 
                   1365: #   to us.  We pick apart the command and pass it on to the subs
                   1366: #   that already exist to do this.
                   1367: #
                   1368: # Parameters:
                   1369: #      $cmd    - the actual keyword that invoked us.
                   1370: #      $tail   - the tail of the request that invoked us.
                   1371: #      $client - File descriptor connected to the client
                   1372: #  Returns:
                   1373: #      1       - Ok to continue processing.
                   1374: #      0       - Program should exit
                   1375: # Implicit Output:
                   1376: #    a reply is written to the client.
                   1377: sub push_file_handler {
                   1378:     my ($cmd, $tail, $client) = @_;
                   1379: 
                   1380:     my $userinput = "$cmd:$tail";
                   1381: 
                   1382:     # At this time we only know that the IP of our partner is a valid manager
                   1383:     # the code below is a hook to do further authentication (e.g. to resolve
                   1384:     # spoofing).
                   1385: 
                   1386:     my $cert = &GetCertificate($userinput);
                   1387:     if(&ValidManager($cert)) { 
                   1388: 
                   1389: 	# Now presumably we have the bona fides of both the peer host and the
                   1390: 	# process making the request.
                   1391:       
                   1392: 	my $reply = &PushFile($userinput);
                   1393: 	&Reply($client, "$reply\n", $userinput);
                   1394: 
                   1395:     } else {
                   1396: 	&Failure( $client, "refused\n", $userinput);
                   1397:     } 
1.219     foxr     1398:     return 1;
1.218     foxr     1399: }
                   1400: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1401: 
1.243     banghart 1402: #
                   1403: #   du  - list the disk usuage of a directory recursively. 
                   1404: #    
                   1405: #   note: stolen code from the ls file handler
                   1406: #   under construction by Rick Banghart 
                   1407: #    .
                   1408: # Parameters:
                   1409: #    $cmd        - The command that dispatched us (du).
                   1410: #    $ududir     - The directory path to list... I'm not sure what this
                   1411: #                  is relative as things like ls:. return e.g.
                   1412: #                  no_such_dir.
                   1413: #    $client     - Socket open on the client.
                   1414: # Returns:
                   1415: #     1 - indicating that the daemon should not disconnect.
                   1416: # Side Effects:
                   1417: #   The reply is written to  $client.
                   1418: #
                   1419: sub du_handler {
                   1420:     my ($cmd, $ududir, $client) = @_;
1.251     foxr     1421:     my ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
                   1422:     my $userinput = "$cmd:$ududir";
                   1423: 
1.245     albertel 1424:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1425: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1426: 	return 1;
                   1427:     }
1.249     foxr     1428:     #  Since $ududir could have some nasties in it,
                   1429:     #  we will require that ududir is a valid
                   1430:     #  directory.  Just in case someone tries to
                   1431:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1432:     #  etc.
                   1433:     #
                   1434:     if (-d $ududir) {
1.292     albertel 1435: 	my $total_size=0;
                   1436: 	my $code=sub { 
                   1437: 	    if ($_=~/\.\d+\./) { return;} 
                   1438: 	    if ($_=~/\.meta$/) { return;}
                   1439: 	    $total_size+=(stat($_))[7];
                   1440: 	};
1.295     raeburn  1441: 	chdir($ududir);
1.292     albertel 1442: 	find($code,$ududir);
                   1443: 	$total_size=int($total_size/1024);
                   1444: 	&Reply($client,"$total_size\n","$cmd:$ududir");
1.249     foxr     1445:     } else {
1.251     foxr     1446: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1447:     }
1.243     banghart 1448:     return 1;
                   1449: }
                   1450: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1451: 
1.239     foxr     1452: #
1.280     matthew  1453: # The ls_handler routine should be considered obosolete and is retained
                   1454: # for communication with legacy servers.  Please see the ls2_handler.
                   1455: #
1.239     foxr     1456: #   ls  - list the contents of a directory.  For each file in the
                   1457: #    selected directory the filename followed by the full output of
                   1458: #    the stat function is returned.  The returned info for each
                   1459: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1460: # Parameters:
                   1461: #    $cmd        - The command that dispatched us (ls).
                   1462: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1463: #                  is relative as things like ls:. return e.g.
                   1464: #                  no_such_dir.
                   1465: #    $client     - Socket open on the client.
                   1466: # Returns:
                   1467: #     1 - indicating that the daemon should not disconnect.
                   1468: # Side Effects:
                   1469: #   The reply is written to  $client.
                   1470: #
                   1471: sub ls_handler {
1.280     matthew  1472:     # obsoleted by ls2_handler
1.239     foxr     1473:     my ($cmd, $ulsdir, $client) = @_;
                   1474: 
                   1475:     my $userinput = "$cmd:$ulsdir";
                   1476: 
                   1477:     my $obs;
                   1478:     my $rights;
                   1479:     my $ulsout='';
                   1480:     my $ulsfn;
                   1481:     if (-e $ulsdir) {
                   1482: 	if(-d $ulsdir) {
                   1483: 	    if (opendir(LSDIR,$ulsdir)) {
                   1484: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1485: 		    undef($obs);
                   1486: 		    undef($rights); 
1.239     foxr     1487: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1488: 		    #We do some obsolete checking here
                   1489: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1490: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1491: 			my @obsolete=<FILE>;
                   1492: 			foreach my $obsolete (@obsolete) {
1.301     www      1493: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1494: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1495: 			}
                   1496: 		    }
                   1497: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1498: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1499: 		    else { $ulsout.="&0"; }
                   1500: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1501: 		    else { $ulsout.="&0:"; }
                   1502: 		}
                   1503: 		closedir(LSDIR);
                   1504: 	    }
                   1505: 	} else {
                   1506: 	    my @ulsstats=stat($ulsdir);
                   1507: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1508: 	}
                   1509:     } else {
                   1510: 	$ulsout='no_such_dir';
                   1511:     }
                   1512:     if ($ulsout eq '') { $ulsout='empty'; }
1.249     foxr     1513:     &Reply($client, "$ulsout\n", $userinput); # This supports debug logging.
1.239     foxr     1514:     
                   1515:     return 1;
                   1516: 
                   1517: }
                   1518: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1519: 
1.280     matthew  1520: #
                   1521: # Please also see the ls_handler, which this routine obosolets.
                   1522: # ls2_handler differs from ls_handler in that it escapes its return 
                   1523: # values before concatenating them together with ':'s.
                   1524: #
                   1525: #   ls2  - list the contents of a directory.  For each file in the
                   1526: #    selected directory the filename followed by the full output of
                   1527: #    the stat function is returned.  The returned info for each
                   1528: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1529: # Parameters:
                   1530: #    $cmd        - The command that dispatched us (ls).
                   1531: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1532: #                  is relative as things like ls:. return e.g.
                   1533: #                  no_such_dir.
                   1534: #    $client     - Socket open on the client.
                   1535: # Returns:
                   1536: #     1 - indicating that the daemon should not disconnect.
                   1537: # Side Effects:
                   1538: #   The reply is written to  $client.
                   1539: #
                   1540: sub ls2_handler {
                   1541:     my ($cmd, $ulsdir, $client) = @_;
                   1542: 
                   1543:     my $userinput = "$cmd:$ulsdir";
                   1544: 
                   1545:     my $obs;
                   1546:     my $rights;
                   1547:     my $ulsout='';
                   1548:     my $ulsfn;
                   1549:     if (-e $ulsdir) {
                   1550:         if(-d $ulsdir) {
                   1551:             if (opendir(LSDIR,$ulsdir)) {
                   1552:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1553:                     undef($obs);
                   1554: 		    undef($rights); 
1.280     matthew  1555:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1556:                     #We do some obsolete checking here
                   1557:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1558:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1559:                         my @obsolete=<FILE>;
                   1560:                         foreach my $obsolete (@obsolete) {
1.301     www      1561:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1562:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1563:                                 $rights = 1;
                   1564:                             }
                   1565:                         }
                   1566:                     }
                   1567:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1568:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1569:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1570:                     $ulsout.= &escape($tmp).':';
                   1571:                 }
                   1572:                 closedir(LSDIR);
                   1573:             }
                   1574:         } else {
                   1575:             my @ulsstats=stat($ulsdir);
                   1576:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1577:         }
                   1578:     } else {
                   1579:         $ulsout='no_such_dir';
                   1580:    }
                   1581:    if ($ulsout eq '') { $ulsout='empty'; }
                   1582:    &Reply($client, "$ulsout\n", $userinput); # This supports debug logging.
                   1583:    return 1;
                   1584: }
                   1585: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
                   1586: 
1.218     foxr     1587: #   Process a reinit request.  Reinit requests that either
                   1588: #   lonc or lond be reinitialized so that an updated 
                   1589: #   host.tab or domain.tab can be processed.
                   1590: #
                   1591: # Parameters:
                   1592: #      $cmd    - the actual keyword that invoked us.
                   1593: #      $tail   - the tail of the request that invoked us.
                   1594: #      $client - File descriptor connected to the client
                   1595: #  Returns:
                   1596: #      1       - Ok to continue processing.
                   1597: #      0       - Program should exit
                   1598: #  Implicit output:
                   1599: #     a reply is sent to the client.
                   1600: #
                   1601: sub reinit_process_handler {
                   1602:     my ($cmd, $tail, $client) = @_;
                   1603:    
                   1604:     my $userinput = "$cmd:$tail";
                   1605:    
                   1606:     my $cert = &GetCertificate($userinput);
                   1607:     if(&ValidManager($cert)) {
                   1608: 	chomp($userinput);
                   1609: 	my $reply = &ReinitProcess($userinput);
                   1610: 	&Reply( $client,  "$reply\n", $userinput);
                   1611:     } else {
                   1612: 	&Failure( $client, "refused\n", $userinput);
                   1613:     }
                   1614:     return 1;
                   1615: }
                   1616: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   1617: 
                   1618: #  Process the editing script for a table edit operation.
                   1619: #  the editing operation must be encrypted and requested by
                   1620: #  a manager host.
                   1621: #
                   1622: # Parameters:
                   1623: #      $cmd    - the actual keyword that invoked us.
                   1624: #      $tail   - the tail of the request that invoked us.
                   1625: #      $client - File descriptor connected to the client
                   1626: #  Returns:
                   1627: #      1       - Ok to continue processing.
                   1628: #      0       - Program should exit
                   1629: #  Implicit output:
                   1630: #     a reply is sent to the client.
                   1631: #
                   1632: sub edit_table_handler {
                   1633:     my ($command, $tail, $client) = @_;
                   1634:    
                   1635:     my $userinput = "$command:$tail";
                   1636: 
                   1637:     my $cert = &GetCertificate($userinput);
                   1638:     if(&ValidManager($cert)) {
                   1639: 	my($filetype, $script) = split(/:/, $tail);
                   1640: 	if (($filetype eq "hosts") || 
                   1641: 	    ($filetype eq "domain")) {
                   1642: 	    if($script ne "") {
                   1643: 		&Reply($client,              # BUGBUG - EditFile
                   1644: 		      &EditFile($userinput), #   could fail.
                   1645: 		      $userinput);
                   1646: 	    } else {
                   1647: 		&Failure($client,"refused\n",$userinput);
                   1648: 	    }
                   1649: 	} else {
                   1650: 	    &Failure($client,"refused\n",$userinput);
                   1651: 	}
                   1652:     } else {
                   1653: 	&Failure($client,"refused\n",$userinput);
                   1654:     }
                   1655:     return 1;
                   1656: }
1.263     albertel 1657: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     1658: 
1.220     foxr     1659: #
                   1660: #   Authenticate a user against the LonCAPA authentication
                   1661: #   database.  Note that there are several authentication
                   1662: #   possibilities:
                   1663: #   - unix     - The user can be authenticated against the unix
                   1664: #                password file.
                   1665: #   - internal - The user can be authenticated against a purely 
                   1666: #                internal per user password file.
                   1667: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   1668: #                ticket granting authority.
                   1669: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   1670: #                mechanism that is per system.
                   1671: #
                   1672: # Parameters:
                   1673: #    $cmd      - The command that got us here.
                   1674: #    $tail     - Tail of the command (remaining parameters).
                   1675: #    $client   - File descriptor connected to client.
                   1676: # Returns
                   1677: #     0        - Requested to exit, caller should shut down.
                   1678: #     1        - Continue processing.
                   1679: # Implicit inputs:
                   1680: #    The authentication systems describe above have their own forms of implicit
                   1681: #    input into the authentication process that are described above.
                   1682: #
                   1683: sub authenticate_handler {
                   1684:     my ($cmd, $tail, $client) = @_;
                   1685: 
                   1686:     
                   1687:     #  Regenerate the full input line 
                   1688:     
                   1689:     my $userinput  = $cmd.":".$tail;
                   1690:     
                   1691:     #  udom    - User's domain.
                   1692:     #  uname   - Username.
                   1693:     #  upass   - User's password.
                   1694:     
                   1695:     my ($udom,$uname,$upass)=split(/:/,$tail);
                   1696:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass");
                   1697:     chomp($upass);
                   1698:     $upass=&unescape($upass);
                   1699: 
                   1700:     my $pwdcorrect = &validate_user($udom, $uname, $upass);
                   1701:     if($pwdcorrect) {
                   1702: 	&Reply( $client, "authorized\n", $userinput);
                   1703: 	#
                   1704: 	#  Bad credentials: Failed to authorize
                   1705: 	#
                   1706:     } else {
                   1707: 	&Failure( $client, "non_authorized\n", $userinput);
                   1708:     }
                   1709: 
                   1710:     return 1;
                   1711: }
1.263     albertel 1712: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     1713: 
1.222     foxr     1714: #
                   1715: #   Change a user's password.  Note that this function is complicated by
                   1716: #   the fact that a user may be authenticated in more than one way:
                   1717: #   At present, we are not able to change the password for all types of
                   1718: #   authentication methods.  Only for:
                   1719: #      unix    - unix password or shadow passoword style authentication.
                   1720: #      local   - Locally written authentication mechanism.
                   1721: #   For now, kerb4 and kerb5 password changes are not supported and result
                   1722: #   in an error.
                   1723: # FUTURE WORK:
                   1724: #    Support kerberos passwd changes?
                   1725: # Parameters:
                   1726: #    $cmd      - The command that got us here.
                   1727: #    $tail     - Tail of the command (remaining parameters).
                   1728: #    $client   - File descriptor connected to client.
                   1729: # Returns
                   1730: #     0        - Requested to exit, caller should shut down.
                   1731: #     1        - Continue processing.
                   1732: # Implicit inputs:
                   1733: #    The authentication systems describe above have their own forms of implicit
                   1734: #    input into the authentication process that are described above.
                   1735: sub change_password_handler {
                   1736:     my ($cmd, $tail, $client) = @_;
                   1737: 
                   1738:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   1739: 
                   1740:     #
                   1741:     #  udom  - user's domain.
                   1742:     #  uname - Username.
                   1743:     #  upass - Current password.
                   1744:     #  npass - New password.
                   1745:    
                   1746:     my ($udom,$uname,$upass,$npass)=split(/:/,$tail);
                   1747: 
                   1748:     $upass=&unescape($upass);
                   1749:     $npass=&unescape($npass);
                   1750:     &Debug("Trying to change password for $uname");
                   1751: 
                   1752:     # First require that the user can be authenticated with their
                   1753:     # old password:
                   1754: 
                   1755:     my $validated = &validate_user($udom, $uname, $upass);
                   1756:     if($validated) {
                   1757: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   1758: 	
                   1759: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   1760: 	if ($howpwd eq 'internal') {
                   1761: 	    &Debug("internal auth");
                   1762: 	    my $salt=time;
                   1763: 	    $salt=substr($salt,6,2);
                   1764: 	    my $ncpass=crypt($npass,$salt);
                   1765: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
                   1766: 		&logthis("Result of password change for "
                   1767: 			 ."$uname: pwchange_success");
                   1768: 		&Reply($client, "ok\n", $userinput);
                   1769: 	    } else {
                   1770: 		&logthis("Unable to open $uname passwd "               
                   1771: 			 ."to change password");
                   1772: 		&Failure( $client, "non_authorized\n",$userinput);
                   1773: 	    }
                   1774: 	} elsif ($howpwd eq 'unix') {
1.287     foxr     1775: 	    my $result = &change_unix_password($uname, $npass);
1.222     foxr     1776: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     1777: 		     $result);
1.222     foxr     1778: 	    &Reply($client, "$result\n", $userinput);
                   1779: 	} else {
                   1780: 	    # this just means that the current password mode is not
                   1781: 	    # one we know how to change (e.g the kerberos auth modes or
                   1782: 	    # locally written auth handler).
                   1783: 	    #
                   1784: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   1785: 	}  
                   1786: 	
1.224     foxr     1787:     } else {
1.222     foxr     1788: 	&Failure( $client, "non_authorized\n", $userinput);
                   1789:     }
                   1790: 
                   1791:     return 1;
                   1792: }
1.263     albertel 1793: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     1794: 
1.225     foxr     1795: #
                   1796: #   Create a new user.  User in this case means a lon-capa user.
                   1797: #   The user must either already exist in some authentication realm
                   1798: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   1799: #   this loncapa system is created.
                   1800: #
                   1801: # Parameters:
                   1802: #    $cmd      - The command that got us here.
                   1803: #    $tail     - Tail of the command (remaining parameters).
                   1804: #    $client   - File descriptor connected to client.
                   1805: # Returns
                   1806: #     0        - Requested to exit, caller should shut down.
                   1807: #     1        - Continue processing.
                   1808: # Implicit inputs:
                   1809: #    The authentication systems describe above have their own forms of implicit
                   1810: #    input into the authentication process that are described above.
                   1811: sub add_user_handler {
                   1812: 
                   1813:     my ($cmd, $tail, $client) = @_;
                   1814: 
                   1815: 
                   1816:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   1817:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   1818: 
                   1819:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   1820: 
                   1821: 
                   1822:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   1823: 	
                   1824: 	my $oldumask=umask(0077);
                   1825: 	chomp($npass);
                   1826: 	$npass=&unescape($npass);
                   1827: 	my $passfilename  = &password_path($udom, $uname);
                   1828: 	&Debug("Password file created will be:".$passfilename);
                   1829: 	if (-e $passfilename) {
                   1830: 	    &Failure( $client, "already_exists\n", $userinput);
                   1831: 	} else {
                   1832: 	    my $fperror='';
1.264     albertel 1833: 	    if (!&mkpath($passfilename)) {
                   1834: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   1835: 		    ."makeuser";
1.225     foxr     1836: 	    }
                   1837: 	    unless ($fperror) {
                   1838: 		my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
                   1839: 		&Reply($client, $result, $userinput);     #BUGBUG - could be fail
                   1840: 	    } else {
                   1841: 		&Failure($client, "$fperror\n", $userinput);
                   1842: 	    }
                   1843: 	}
                   1844: 	umask($oldumask);
                   1845:     }  else {
                   1846: 	&Failure($client, "not_right_domain\n",
                   1847: 		$userinput);	# Even if we are multihomed.
                   1848:     
                   1849:     }
                   1850:     return 1;
                   1851: 
                   1852: }
                   1853: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   1854: 
                   1855: #
                   1856: #   Change the authentication method of a user.  Note that this may
                   1857: #   also implicitly change the user's password if, for example, the user is
                   1858: #   joining an existing authentication realm.  Known authentication realms at
                   1859: #   this time are:
                   1860: #    internal   - Purely internal password file (only loncapa knows this user)
                   1861: #    local      - Institutionally written authentication module.
                   1862: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   1863: #    kerb4      - kerberos version 4
                   1864: #    kerb5      - kerberos version 5
                   1865: #
                   1866: # Parameters:
                   1867: #    $cmd      - The command that got us here.
                   1868: #    $tail     - Tail of the command (remaining parameters).
                   1869: #    $client   - File descriptor connected to client.
                   1870: # Returns
                   1871: #     0        - Requested to exit, caller should shut down.
                   1872: #     1        - Continue processing.
                   1873: # Implicit inputs:
                   1874: #    The authentication systems describe above have their own forms of implicit
                   1875: #    input into the authentication process that are described above.
1.287     foxr     1876: # NOTE:
                   1877: #   This is also used to change the authentication credential values (e.g. passwd).
                   1878: #   
1.225     foxr     1879: #
                   1880: sub change_authentication_handler {
                   1881: 
                   1882:     my ($cmd, $tail, $client) = @_;
                   1883:    
                   1884:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   1885: 
                   1886:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   1887:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   1888:     if ($udom ne $currentdomainid) {
                   1889: 	&Failure( $client, "not_right_domain\n", $client);
                   1890:     } else {
                   1891: 	
                   1892: 	chomp($npass);
                   1893: 	
                   1894: 	$npass=&unescape($npass);
1.261     foxr     1895: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     1896: 	my $passfilename = &password_path($udom, $uname);
                   1897: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     1898: 	    # If just changing the unix passwd. need to arrange to run
                   1899: 	    # passwd since otherwise make_passwd_file will run
                   1900: 	    # lcuseradd which fails if an account already exists
                   1901: 	    # (to prevent an unscrupulous LONCAPA admin from stealing
                   1902: 	    # an existing account by overwriting it as a LonCAPA account).
                   1903: 
                   1904: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   1905: 		my $result = &change_unix_password($uname, $npass);
                   1906: 		&logthis("Result of password change for $uname: ".$result);
                   1907: 		if ($result eq "ok") {
                   1908: 		    &Reply($client, "$result\n")
1.288     albertel 1909: 		} else {
1.287     foxr     1910: 		    &Failure($client, "$result\n");
                   1911: 		}
1.288     albertel 1912: 	    } else {
1.287     foxr     1913: 		my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
                   1914: 		#
                   1915: 		#  If the current auth mode is internal, and the old auth mode was
                   1916: 		#  unix, or krb*,  and the user is an author for this domain,
                   1917: 		#  re-run manage_permissions for that role in order to be able
                   1918: 		#  to take ownership of the construction space back to www:www
                   1919: 		#
                   1920: 		
                   1921: 		
                   1922: 		if( (($oldauth =~ /^unix/) && ($umode eq "internal")) ||
                   1923: 		    (($oldauth =~ /^internal/) && ($umode eq "unix")) ) { 
                   1924: 		    if(&is_author($udom, $uname)) {
                   1925: 			&Debug(" Need to manage author permissions...");
                   1926: 			&manage_permissions("/$udom/_au", $udom, $uname, "$umode:");
                   1927: 		    }
1.261     foxr     1928: 		}
1.287     foxr     1929: 		&Reply($client, $result, $userinput);
1.261     foxr     1930: 	    }
                   1931: 	       
                   1932: 
1.225     foxr     1933: 	} else {	       
1.251     foxr     1934: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     1935: 	}
                   1936:     }
                   1937:     return 1;
                   1938: }
                   1939: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   1940: 
                   1941: #
                   1942: #   Determines if this is the home server for a user.  The home server
                   1943: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   1944: #   to do is determine if this file exists.
                   1945: #
                   1946: # Parameters:
                   1947: #    $cmd      - The command that got us here.
                   1948: #    $tail     - Tail of the command (remaining parameters).
                   1949: #    $client   - File descriptor connected to client.
                   1950: # Returns
                   1951: #     0        - Requested to exit, caller should shut down.
                   1952: #     1        - Continue processing.
                   1953: # Implicit inputs:
                   1954: #    The authentication systems describe above have their own forms of implicit
                   1955: #    input into the authentication process that are described above.
                   1956: #
                   1957: sub is_home_handler {
                   1958:     my ($cmd, $tail, $client) = @_;
                   1959:    
                   1960:     my $userinput  = "$cmd:$tail";
                   1961:    
                   1962:     my ($udom,$uname)=split(/:/,$tail);
                   1963:     chomp($uname);
                   1964:     my $passfile = &password_filename($udom, $uname);
                   1965:     if($passfile) {
                   1966: 	&Reply( $client, "found\n", $userinput);
                   1967:     } else {
                   1968: 	&Failure($client, "not_found\n", $userinput);
                   1969:     }
                   1970:     return 1;
                   1971: }
                   1972: &register_handler("home", \&is_home_handler, 0,1,0);
                   1973: 
                   1974: #
                   1975: #   Process an update request for a resource?? I think what's going on here is
                   1976: #   that a resource has been modified that we hold a subscription to.
                   1977: #   If the resource is not local, then we must update, or at least invalidate our
                   1978: #   cached copy of the resource. 
                   1979: #   FUTURE WORK:
                   1980: #      I need to look at this logic carefully.  My druthers would be to follow
                   1981: #      typical caching logic, and simple invalidate the cache, drop any subscription
                   1982: #      an let the next fetch start the ball rolling again... however that may
                   1983: #      actually be more difficult than it looks given the complex web of
                   1984: #      proxy servers.
                   1985: # Parameters:
                   1986: #    $cmd      - The command that got us here.
                   1987: #    $tail     - Tail of the command (remaining parameters).
                   1988: #    $client   - File descriptor connected to client.
                   1989: # Returns
                   1990: #     0        - Requested to exit, caller should shut down.
                   1991: #     1        - Continue processing.
                   1992: # Implicit inputs:
                   1993: #    The authentication systems describe above have their own forms of implicit
                   1994: #    input into the authentication process that are described above.
                   1995: #
                   1996: sub update_resource_handler {
                   1997: 
                   1998:     my ($cmd, $tail, $client) = @_;
                   1999:    
                   2000:     my $userinput = "$cmd:$tail";
                   2001:    
                   2002:     my $fname= $tail;		# This allows interactive testing
                   2003: 
                   2004: 
                   2005:     my $ownership=ishome($fname);
                   2006:     if ($ownership eq 'not_owner') {
                   2007: 	if (-e $fname) {
                   2008: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2009: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2010: 	    my $now=time;
                   2011: 	    my $since=$now-$atime;
                   2012: 	    if ($since>$perlvar{'lonExpire'}) {
                   2013: 		my $reply=&reply("unsub:$fname","$clientname");
1.308     albertel 2014: 		&devalidate_meta_cache($fname);
1.225     foxr     2015: 		unlink("$fname");
                   2016: 	    } else {
                   2017: 		my $transname="$fname.in.transfer";
                   2018: 		my $remoteurl=&reply("sub:$fname","$clientname");
                   2019: 		my $response;
                   2020: 		alarm(120);
                   2021: 		{
                   2022: 		    my $ua=new LWP::UserAgent;
                   2023: 		    my $request=new HTTP::Request('GET',"$remoteurl");
                   2024: 		    $response=$ua->request($request,$transname);
                   2025: 		}
                   2026: 		alarm(0);
                   2027: 		if ($response->is_error()) {
                   2028: 		    unlink($transname);
                   2029: 		    my $message=$response->status_line;
                   2030: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2031: 		} else {
                   2032: 		    if ($remoteurl!~/\.meta$/) {
                   2033: 			alarm(120);
                   2034: 			{
                   2035: 			    my $ua=new LWP::UserAgent;
                   2036: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2037: 			    my $mresponse=$ua->request($mrequest,$fname.'.meta');
                   2038: 			    if ($mresponse->is_error()) {
                   2039: 				unlink($fname.'.meta');
                   2040: 			    }
                   2041: 			}
                   2042: 			alarm(0);
                   2043: 		    }
                   2044: 		    rename($transname,$fname);
1.308     albertel 2045: 		    &devalidate_meta_cache($fname);
1.225     foxr     2046: 		}
                   2047: 	    }
                   2048: 	    &Reply( $client, "ok\n", $userinput);
                   2049: 	} else {
                   2050: 	    &Failure($client, "not_found\n", $userinput);
                   2051: 	}
                   2052:     } else {
                   2053: 	&Failure($client, "rejected\n", $userinput);
                   2054:     }
                   2055:     return 1;
                   2056: }
                   2057: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2058: 
1.308     albertel 2059: sub devalidate_meta_cache {
                   2060:     my ($url) = @_;
                   2061:     use Cache::Memcached;
                   2062:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
                   2063:     $url = &declutter($url);
                   2064:     $url =~ s-\.meta$--;
                   2065:     my $id = &escape('meta:'.$url);
                   2066:     $memcache->delete($id);
                   2067: }
                   2068: 
                   2069: sub declutter {
                   2070:     my $thisfn=shift;
                   2071:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   2072:     $thisfn=~s/^\///;
                   2073:     $thisfn=~s|^adm/wrapper/||;
                   2074:     $thisfn=~s|^adm/coursedocs/showdoc/||;
                   2075:     $thisfn=~s/^res\///;
                   2076:     $thisfn=~s/\?.+$//;
                   2077:     return $thisfn;
                   2078: }
1.225     foxr     2079: #
1.226     foxr     2080: #   Fetch a user file from a remote server to the user's home directory
                   2081: #   userfiles subdir.
1.225     foxr     2082: # Parameters:
                   2083: #    $cmd      - The command that got us here.
                   2084: #    $tail     - Tail of the command (remaining parameters).
                   2085: #    $client   - File descriptor connected to client.
                   2086: # Returns
                   2087: #     0        - Requested to exit, caller should shut down.
                   2088: #     1        - Continue processing.
                   2089: #
                   2090: sub fetch_user_file_handler {
                   2091: 
                   2092:     my ($cmd, $tail, $client) = @_;
                   2093: 
                   2094:     my $userinput = "$cmd:$tail";
                   2095:     my $fname           = $tail;
1.232     foxr     2096:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2097:     my $udir=&propath($udom,$uname).'/userfiles';
                   2098:     unless (-e $udir) {
                   2099: 	mkdir($udir,0770); 
                   2100:     }
1.232     foxr     2101:     Debug("fetch user file for $fname");
1.225     foxr     2102:     if (-e $udir) {
                   2103: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2104: 
                   2105: 	# IF necessary, create the path right down to the file.
                   2106: 	# Note that any regular files in the way of this path are
                   2107: 	# wiped out to deal with some earlier folly of mine.
                   2108: 
1.267     raeburn  2109: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2110: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2111: 	}
                   2112: 
1.225     foxr     2113: 	my $destname=$udir.'/'.$ufile;
                   2114: 	my $transname=$udir.'/'.$ufile.'.in.transit';
                   2115: 	my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
                   2116: 	my $response;
1.232     foxr     2117: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.225     foxr     2118: 	alarm(120);
                   2119: 	{
                   2120: 	    my $ua=new LWP::UserAgent;
                   2121: 	    my $request=new HTTP::Request('GET',"$remoteurl");
                   2122: 	    $response=$ua->request($request,$transname);
                   2123: 	}
                   2124: 	alarm(0);
                   2125: 	if ($response->is_error()) {
                   2126: 	    unlink($transname);
                   2127: 	    my $message=$response->status_line;
                   2128: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2129: 	    &Failure($client, "failed\n", $userinput);
                   2130: 	} else {
1.232     foxr     2131: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2132: 	    if (!rename($transname,$destname)) {
                   2133: 		&logthis("Unable to move $transname to $destname");
                   2134: 		unlink($transname);
                   2135: 		&Failure($client, "failed\n", $userinput);
                   2136: 	    } else {
                   2137: 		&Reply($client, "ok\n", $userinput);
                   2138: 	    }
                   2139: 	}   
                   2140:     } else {
                   2141: 	&Failure($client, "not_home\n", $userinput);
                   2142:     }
                   2143:     return 1;
                   2144: }
                   2145: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2146: 
1.226     foxr     2147: #
                   2148: #   Remove a file from a user's home directory userfiles subdirectory.
                   2149: # Parameters:
                   2150: #    cmd   - the Lond request keyword that got us here.
                   2151: #    tail  - the part of the command past the keyword.
                   2152: #    client- File descriptor connected with the client.
                   2153: #
                   2154: # Returns:
                   2155: #    1    - Continue processing.
                   2156: sub remove_user_file_handler {
                   2157:     my ($cmd, $tail, $client) = @_;
                   2158: 
                   2159:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2160: 
                   2161:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2162:     if ($ufile =~m|/\.\./|) {
                   2163: 	# any files paths with /../ in them refuse 
                   2164: 	# to deal with
                   2165: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2166:     } else {
                   2167: 	my $udir = &propath($udom,$uname);
                   2168: 	if (-e $udir) {
                   2169: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2170: 	    if (-e $file) {
1.253     foxr     2171: 		#
                   2172: 		#   If the file is a regular file unlink is fine...
                   2173: 		#   However it's possible the client wants a dir.
                   2174: 		#   removed, in which case rmdir is more approprate:
                   2175: 		#
1.240     banghart 2176: 	        if (-f $file){
1.241     albertel 2177: 		    unlink($file);
                   2178: 		} elsif(-d $file) {
                   2179: 		    rmdir($file);
1.240     banghart 2180: 		}
1.226     foxr     2181: 		if (-e $file) {
1.253     foxr     2182: 		    #  File is still there after we deleted it ?!?
                   2183: 
1.226     foxr     2184: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2185: 		} else {
                   2186: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2187: 		}
                   2188: 	    } else {
                   2189: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2190: 	    }
                   2191: 	} else {
                   2192: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2193: 	}
                   2194:     }
                   2195:     return 1;
                   2196: }
                   2197: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2198: 
1.236     albertel 2199: #
                   2200: #   make a directory in a user's home directory userfiles subdirectory.
                   2201: # Parameters:
                   2202: #    cmd   - the Lond request keyword that got us here.
                   2203: #    tail  - the part of the command past the keyword.
                   2204: #    client- File descriptor connected with the client.
                   2205: #
                   2206: # Returns:
                   2207: #    1    - Continue processing.
                   2208: sub mkdir_user_file_handler {
                   2209:     my ($cmd, $tail, $client) = @_;
                   2210: 
                   2211:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2212:     $dir=&unescape($dir);
                   2213:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2214:     if ($ufile =~m|/\.\./|) {
                   2215: 	# any files paths with /../ in them refuse 
                   2216: 	# to deal with
                   2217: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2218:     } else {
                   2219: 	my $udir = &propath($udom,$uname);
                   2220: 	if (-e $udir) {
1.264     albertel 2221: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2222: 	    if (!&mkpath($newdir)) {
                   2223: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2224: 	    }
1.264     albertel 2225: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2226: 	} else {
                   2227: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2228: 	}
                   2229:     }
                   2230:     return 1;
                   2231: }
                   2232: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2233: 
1.237     albertel 2234: #
                   2235: #   rename a file in a user's home directory userfiles subdirectory.
                   2236: # Parameters:
                   2237: #    cmd   - the Lond request keyword that got us here.
                   2238: #    tail  - the part of the command past the keyword.
                   2239: #    client- File descriptor connected with the client.
                   2240: #
                   2241: # Returns:
                   2242: #    1    - Continue processing.
                   2243: sub rename_user_file_handler {
                   2244:     my ($cmd, $tail, $client) = @_;
                   2245: 
                   2246:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2247:     $old=&unescape($old);
                   2248:     $new=&unescape($new);
                   2249:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2250: 	# any files paths with /../ in them refuse to deal with
                   2251: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2252:     } else {
                   2253: 	my $udir = &propath($udom,$uname);
                   2254: 	if (-e $udir) {
                   2255: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2256: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2257: 	    if (-e $newfile) {
                   2258: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2259: 	    } elsif (! -e $oldfile) {
                   2260: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2261: 	    } else {
                   2262: 		if (!rename($oldfile,$newfile)) {
                   2263: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2264: 		} else {
                   2265: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2266: 		}
                   2267: 	    }
                   2268: 	} else {
                   2269: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2270: 	}
                   2271:     }
                   2272:     return 1;
                   2273: }
                   2274: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2275: 
1.227     foxr     2276: #
1.263     albertel 2277: #  Authenticate access to a user file by checking that the token the user's 
                   2278: #  passed also exists in their session file
1.227     foxr     2279: #
                   2280: # Parameters:
                   2281: #   cmd      - The request keyword that dispatched to tus.
                   2282: #   tail     - The tail of the request (colon separated parameters).
                   2283: #   client   - Filehandle open on the client.
                   2284: # Return:
                   2285: #    1.
                   2286: sub token_auth_user_file_handler {
                   2287:     my ($cmd, $tail, $client) = @_;
                   2288: 
                   2289:     my ($fname, $session) = split(/:/, $tail);
                   2290:     
                   2291:     chomp($session);
1.251     foxr     2292:     my $reply="non_auth\n";
1.227     foxr     2293:     if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
                   2294: 	     $session.'.id')) {
                   2295: 	while (my $line=<ENVIN>) {
1.251     foxr     2296: 	    if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply="ok\n"; }
1.227     foxr     2297: 	}
                   2298: 	close(ENVIN);
1.251     foxr     2299: 	&Reply($client, $reply, "$cmd:$tail");
1.227     foxr     2300:     } else {
                   2301: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2302:     }
                   2303:     return 1;
                   2304: 
                   2305: }
                   2306: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2307: 
                   2308: #
                   2309: #   Unsubscribe from a resource.
                   2310: #
                   2311: # Parameters:
                   2312: #    $cmd      - The command that got us here.
                   2313: #    $tail     - Tail of the command (remaining parameters).
                   2314: #    $client   - File descriptor connected to client.
                   2315: # Returns
                   2316: #     0        - Requested to exit, caller should shut down.
                   2317: #     1        - Continue processing.
                   2318: #
                   2319: sub unsubscribe_handler {
                   2320:     my ($cmd, $tail, $client) = @_;
                   2321: 
                   2322:     my $userinput= "$cmd:$tail";
                   2323:     
                   2324:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   2325: 
                   2326:     &Debug("Unsubscribing $fname");
                   2327:     if (-e $fname) {
                   2328: 	&Debug("Exists");
                   2329: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   2330:     } else {
                   2331: 	&Failure($client, "not_found\n", $userinput);
                   2332:     }
                   2333:     return 1;
                   2334: }
                   2335: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 2336: 
1.230     foxr     2337: #   Subscribe to a resource
                   2338: #
                   2339: # Parameters:
                   2340: #    $cmd      - The command that got us here.
                   2341: #    $tail     - Tail of the command (remaining parameters).
                   2342: #    $client   - File descriptor connected to client.
                   2343: # Returns
                   2344: #     0        - Requested to exit, caller should shut down.
                   2345: #     1        - Continue processing.
                   2346: #
                   2347: sub subscribe_handler {
                   2348:     my ($cmd, $tail, $client)= @_;
                   2349: 
                   2350:     my $userinput  = "$cmd:$tail";
                   2351: 
                   2352:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   2353: 
                   2354:     return 1;
                   2355: }
                   2356: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   2357: 
                   2358: #
                   2359: #   Determine the version of a resource (?) Or is it return
                   2360: #   the top version of the resource?  Not yet clear from the
                   2361: #   code in currentversion.
                   2362: #
                   2363: # Parameters:
                   2364: #    $cmd      - The command that got us here.
                   2365: #    $tail     - Tail of the command (remaining parameters).
                   2366: #    $client   - File descriptor connected to client.
                   2367: # Returns
                   2368: #     0        - Requested to exit, caller should shut down.
                   2369: #     1        - Continue processing.
                   2370: #
                   2371: sub current_version_handler {
                   2372:     my ($cmd, $tail, $client) = @_;
                   2373: 
                   2374:     my $userinput= "$cmd:$tail";
                   2375:    
                   2376:     my $fname   = $tail;
                   2377:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   2378:     return 1;
                   2379: 
                   2380: }
                   2381: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   2382: 
                   2383: #  Make an entry in a user's activity log.
                   2384: #
                   2385: # Parameters:
                   2386: #    $cmd      - The command that got us here.
                   2387: #    $tail     - Tail of the command (remaining parameters).
                   2388: #    $client   - File descriptor connected to client.
                   2389: # Returns
                   2390: #     0        - Requested to exit, caller should shut down.
                   2391: #     1        - Continue processing.
                   2392: #
                   2393: sub activity_log_handler {
                   2394:     my ($cmd, $tail, $client) = @_;
                   2395: 
                   2396: 
                   2397:     my $userinput= "$cmd:$tail";
                   2398: 
                   2399:     my ($udom,$uname,$what)=split(/:/,$tail);
                   2400:     chomp($what);
                   2401:     my $proname=&propath($udom,$uname);
                   2402:     my $now=time;
                   2403:     my $hfh;
                   2404:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   2405: 	print $hfh "$now:$clientname:$what\n";
                   2406: 	&Reply( $client, "ok\n", $userinput); 
                   2407:     } else {
                   2408: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   2409: 		 ."while attempting log\n", 
                   2410: 		 $userinput);
                   2411:     }
                   2412: 
                   2413:     return 1;
                   2414: }
1.263     albertel 2415: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     2416: 
                   2417: #
                   2418: #   Put a namespace entry in a user profile hash.
                   2419: #   My druthers would be for this to be an encrypted interaction too.
                   2420: #   anything that might be an inadvertent covert channel about either
                   2421: #   user authentication or user personal information....
                   2422: #
                   2423: # Parameters:
                   2424: #    $cmd      - The command that got us here.
                   2425: #    $tail     - Tail of the command (remaining parameters).
                   2426: #    $client   - File descriptor connected to client.
                   2427: # Returns
                   2428: #     0        - Requested to exit, caller should shut down.
                   2429: #     1        - Continue processing.
                   2430: #
                   2431: sub put_user_profile_entry {
                   2432:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     2433: 
1.230     foxr     2434:     my $userinput = "$cmd:$tail";
                   2435:     
1.242     raeburn  2436:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     2437:     if ($namespace ne 'roles') {
                   2438: 	chomp($what);
                   2439: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2440: 				  &GDBM_WRCREAT(),"P",$what);
                   2441: 	if($hashref) {
                   2442: 	    my @pairs=split(/\&/,$what);
                   2443: 	    foreach my $pair (@pairs) {
                   2444: 		my ($key,$value)=split(/=/,$pair);
                   2445: 		$hashref->{$key}=$value;
                   2446: 	    }
1.311     albertel 2447: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     2448: 		&Reply( $client, "ok\n", $userinput);
                   2449: 	    } else {
                   2450: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2451: 			"while attempting put\n", 
                   2452: 			$userinput);
                   2453: 	    }
                   2454: 	} else {
1.316     albertel 2455: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     2456: 		     "while attempting put\n", $userinput);
                   2457: 	}
                   2458:     } else {
                   2459:         &Failure( $client, "refused\n", $userinput);
                   2460:     }
                   2461:     
                   2462:     return 1;
                   2463: }
                   2464: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   2465: 
1.283     albertel 2466: #   Put a piece of new data in hash, returns error if entry already exists
                   2467: # Parameters:
                   2468: #    $cmd      - The command that got us here.
                   2469: #    $tail     - Tail of the command (remaining parameters).
                   2470: #    $client   - File descriptor connected to client.
                   2471: # Returns
                   2472: #     0        - Requested to exit, caller should shut down.
                   2473: #     1        - Continue processing.
                   2474: #
                   2475: sub newput_user_profile_entry {
                   2476:     my ($cmd, $tail, $client)  = @_;
                   2477: 
                   2478:     my $userinput = "$cmd:$tail";
                   2479: 
                   2480:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   2481:     if ($namespace eq 'roles') {
                   2482:         &Failure( $client, "refused\n", $userinput);
                   2483: 	return 1;
                   2484:     }
                   2485: 
                   2486:     chomp($what);
                   2487: 
                   2488:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2489: 				 &GDBM_WRCREAT(),"N",$what);
                   2490:     if(!$hashref) {
1.316     albertel 2491: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 2492: 		  "while attempting put\n", $userinput);
                   2493: 	return 1;
                   2494:     }
                   2495: 
                   2496:     my @pairs=split(/\&/,$what);
                   2497:     foreach my $pair (@pairs) {
                   2498: 	my ($key,$value)=split(/=/,$pair);
                   2499: 	if (exists($hashref->{$key})) {
                   2500: 	    &Failure($client, "key_exists: ".$key."\n",$userinput);
                   2501: 	    return 1;
                   2502: 	}
                   2503:     }
                   2504: 
                   2505:     foreach my $pair (@pairs) {
                   2506: 	my ($key,$value)=split(/=/,$pair);
                   2507: 	$hashref->{$key}=$value;
                   2508:     }
                   2509: 
1.311     albertel 2510:     if (&untie_user_hash($hashref)) {
1.283     albertel 2511: 	&Reply( $client, "ok\n", $userinput);
                   2512:     } else {
                   2513: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2514: 		 "while attempting put\n", 
                   2515: 		 $userinput);
                   2516:     }
                   2517:     return 1;
                   2518: }
                   2519: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   2520: 
1.230     foxr     2521: # 
                   2522: #   Increment a profile entry in the user history file.
                   2523: #   The history contains keyword value pairs.  In this case,
                   2524: #   The value itself is a pair of numbers.  The first, the current value
                   2525: #   the second an increment that this function applies to the current
                   2526: #   value.
                   2527: #
                   2528: # Parameters:
                   2529: #    $cmd      - The command that got us here.
                   2530: #    $tail     - Tail of the command (remaining parameters).
                   2531: #    $client   - File descriptor connected to client.
                   2532: # Returns
                   2533: #     0        - Requested to exit, caller should shut down.
                   2534: #     1        - Continue processing.
                   2535: #
                   2536: sub increment_user_value_handler {
                   2537:     my ($cmd, $tail, $client) = @_;
                   2538:     
                   2539:     my $userinput   = "$cmd:$tail";
                   2540:     
                   2541:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   2542:     if ($namespace ne 'roles') {
                   2543:         chomp($what);
                   2544: 	my $hashref = &tie_user_hash($udom, $uname,
                   2545: 				     $namespace, &GDBM_WRCREAT(),
                   2546: 				     "P",$what);
                   2547: 	if ($hashref) {
                   2548: 	    my @pairs=split(/\&/,$what);
                   2549: 	    foreach my $pair (@pairs) {
                   2550: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  2551:                 $value = &unescape($value);
1.230     foxr     2552: 		# We could check that we have a number...
                   2553: 		if (! defined($value) || $value eq '') {
                   2554: 		    $value = 1;
                   2555: 		}
                   2556: 		$hashref->{$key}+=$value;
1.284     raeburn  2557:                 if ($namespace eq 'nohist_resourcetracker') {
                   2558:                     if ($hashref->{$key} < 0) {
                   2559:                         $hashref->{$key} = 0;
                   2560:                     }
                   2561:                 }
1.230     foxr     2562: 	    }
1.311     albertel 2563: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     2564: 		&Reply( $client, "ok\n", $userinput);
                   2565: 	    } else {
                   2566: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2567: 			 "while attempting inc\n", $userinput);
                   2568: 	    }
                   2569: 	} else {
                   2570: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2571: 		     "while attempting inc\n", $userinput);
                   2572: 	}
                   2573:     } else {
                   2574: 	&Failure($client, "refused\n", $userinput);
                   2575:     }
                   2576:     
                   2577:     return 1;
                   2578: }
                   2579: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   2580: 
                   2581: #
                   2582: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   2583: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   2584: #   for a person grants the permissions packaged with that role
                   2585: #   to that user when the role is selected.
                   2586: #
                   2587: # Parameters:
                   2588: #    $cmd       - The command string (rolesput).
                   2589: #    $tail      - The remainder of the request line.  For rolesput this
                   2590: #                 consists of a colon separated list that contains:
                   2591: #                 The domain and user that is granting the role (logged).
                   2592: #                 The domain and user that is getting the role.
                   2593: #                 The roles being granted as a set of & separated pairs.
                   2594: #                 each pair a key value pair.
                   2595: #    $client    - File descriptor connected to the client.
                   2596: # Returns:
                   2597: #     0         - If the daemon should exit
                   2598: #     1         - To continue processing.
                   2599: #
                   2600: #
                   2601: sub roles_put_handler {
                   2602:     my ($cmd, $tail, $client) = @_;
                   2603: 
                   2604:     my $userinput  = "$cmd:$tail";
                   2605: 
                   2606:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   2607:     
                   2608: 
                   2609:     my $namespace='roles';
                   2610:     chomp($what);
                   2611:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2612: 				 &GDBM_WRCREAT(), "P",
                   2613: 				 "$exedom:$exeuser:$what");
                   2614:     #
                   2615:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   2616:     #  handle is open for the minimal amount of time.  Since the flush
                   2617:     #  is done on close this improves the chances the log will be an un-
                   2618:     #  corrupted ordered thing.
                   2619:     if ($hashref) {
1.261     foxr     2620: 	my $pass_entry = &get_auth_type($udom, $uname);
                   2621: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   2622: 	$auth_type = $auth_type.":";
1.230     foxr     2623: 	my @pairs=split(/\&/,$what);
                   2624: 	foreach my $pair (@pairs) {
                   2625: 	    my ($key,$value)=split(/=/,$pair);
                   2626: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     2627: 			       $auth_type);
1.230     foxr     2628: 	    $hashref->{$key}=$value;
                   2629: 	}
1.311     albertel 2630: 	if (&untie_user_hash($hashref)) {
1.230     foxr     2631: 	    &Reply($client, "ok\n", $userinput);
                   2632: 	} else {
                   2633: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2634: 		     "while attempting rolesput\n", $userinput);
                   2635: 	}
                   2636:     } else {
                   2637: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2638: 		 "while attempting rolesput\n", $userinput);
                   2639:     }
                   2640:     return 1;
                   2641: }
                   2642: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   2643: 
                   2644: #
1.231     foxr     2645: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   2646: #  a permissions package associated with the role from the user's profile.
                   2647: #
                   2648: # Parameters:
                   2649: #     $cmd                 - The command (rolesdel)
                   2650: #     $tail                - The remainder of the request line. This consists
                   2651: #                             of:
                   2652: #                             The domain and user requesting the change (logged)
                   2653: #                             The domain and user being changed.
                   2654: #                             The roles being revoked.  These are shipped to us
                   2655: #                             as a bunch of & separated role name keywords.
                   2656: #     $client              - The file handle open on the client.
                   2657: # Returns:
                   2658: #     1                    - Continue processing
                   2659: #     0                    - Exit.
                   2660: #
                   2661: sub roles_delete_handler {
                   2662:     my ($cmd, $tail, $client)  = @_;
                   2663: 
                   2664:     my $userinput    = "$cmd:$tail";
                   2665:    
                   2666:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   2667:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   2668: 	   "what = ".$what);
                   2669:     my $namespace='roles';
                   2670:     chomp($what);
                   2671:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2672: 				 &GDBM_WRCREAT(), "D",
                   2673: 				 "$exedom:$exeuser:$what");
                   2674:     
                   2675:     if ($hashref) {
                   2676: 	my @rolekeys=split(/\&/,$what);
                   2677: 	
                   2678: 	foreach my $key (@rolekeys) {
                   2679: 	    delete $hashref->{$key};
                   2680: 	}
1.315     albertel 2681: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2682: 	    &Reply($client, "ok\n", $userinput);
                   2683: 	} else {
                   2684: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2685: 		     "while attempting rolesdel\n", $userinput);
                   2686: 	}
                   2687:     } else {
                   2688:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2689: 		 "while attempting rolesdel\n", $userinput);
                   2690:     }
                   2691:     
                   2692:     return 1;
                   2693: }
                   2694: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   2695: 
                   2696: # Unencrypted get from a user's profile database.  See 
                   2697: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   2698: # This function retrieves a keyed item from a specific named database in the
                   2699: # user's directory.
                   2700: #
                   2701: # Parameters:
                   2702: #   $cmd             - Command request keyword (get).
                   2703: #   $tail            - Tail of the command.  This is a colon separated list
                   2704: #                      consisting of the domain and username that uniquely
                   2705: #                      identifies the profile,
                   2706: #                      The 'namespace' which selects the gdbm file to 
                   2707: #                      do the lookup in, 
                   2708: #                      & separated list of keys to lookup.  Note that
                   2709: #                      the values are returned as an & separated list too.
                   2710: #   $client          - File descriptor open on the client.
                   2711: # Returns:
                   2712: #   1       - Continue processing.
                   2713: #   0       - Exit.
                   2714: #
                   2715: sub get_profile_entry {
                   2716:     my ($cmd, $tail, $client) = @_;
                   2717: 
                   2718:     my $userinput= "$cmd:$tail";
                   2719:    
                   2720:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2721:     chomp($what);
1.255     foxr     2722: 
                   2723:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   2724:     my ($first) = split(/:/,$replystring);
                   2725:     if($first ne "error") {
                   2726: 	&Reply($client, "$replystring\n", $userinput);
1.231     foxr     2727:     } else {
1.255     foxr     2728: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     2729:     }
                   2730:     return 1;
1.255     foxr     2731: 
                   2732: 
1.231     foxr     2733: }
                   2734: &register_handler("get", \&get_profile_entry, 0,1,0);
                   2735: 
                   2736: #
                   2737: #  Process the encrypted get request.  Note that the request is sent
                   2738: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   2739: #  information about the sensitive keys is given to the snooper.  Just not
                   2740: #  information about the values of the sensitive key.  Hmm if I wanted to
                   2741: #  know these I'd snoop for the egets. Get the profile item names from them
                   2742: #  and then issue a get for them since there's no enforcement of the
                   2743: #  requirement of an encrypted get for particular profile items.  If I
                   2744: #  were re-doing this, I'd force the request to be encrypted as well as the
                   2745: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   2746: #  that would prevent any covert channel snooping.
                   2747: #
                   2748: #  Parameters:
                   2749: #     $cmd               - Command keyword of request (eget).
                   2750: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
                   2751: #     $client            - File open on the client.
                   2752: #  Returns:
                   2753: #     1      - Continue processing
                   2754: #     0      - server should exit.
                   2755: sub get_profile_entry_encrypted {
                   2756:     my ($cmd, $tail, $client) = @_;
                   2757: 
                   2758:     my $userinput = "$cmd:$tail";
                   2759:    
                   2760:     my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
                   2761:     chomp($what);
1.255     foxr     2762:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   2763:     my ($first) = split(/:/, $qresult);
                   2764:     if($first ne "error") {
                   2765: 	
                   2766: 	if ($cipher) {
                   2767: 	    my $cmdlength=length($qresult);
                   2768: 	    $qresult.="         ";
                   2769: 	    my $encqresult='';
                   2770: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   2771: 		$encqresult.= unpack("H16", 
                   2772: 				     $cipher->encrypt(substr($qresult,
                   2773: 							     $encidx,
                   2774: 							     8)));
                   2775: 	    }
                   2776: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   2777: 	} else {
1.231     foxr     2778: 		&Failure( $client, "error:no_key\n", $userinput);
                   2779: 	    }
                   2780:     } else {
1.255     foxr     2781: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   2782: 
1.231     foxr     2783:     }
                   2784:     
                   2785:     return 1;
                   2786: }
1.255     foxr     2787: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 2788: 
1.231     foxr     2789: #
                   2790: #   Deletes a key in a user profile database.
                   2791: #   
                   2792: #   Parameters:
                   2793: #       $cmd                  - Command keyword (del).
                   2794: #       $tail                 - Command tail.  IN this case a colon
                   2795: #                               separated list containing:
                   2796: #                               The domain and user that identifies uniquely
                   2797: #                               the identity of the user.
                   2798: #                               The profile namespace (name of the profile
                   2799: #                               database file).
                   2800: #                               & separated list of keywords to delete.
                   2801: #       $client              - File open on client socket.
                   2802: # Returns:
                   2803: #     1   - Continue processing
                   2804: #     0   - Exit server.
                   2805: #
                   2806: #
                   2807: sub delete_profile_entry {
                   2808:     my ($cmd, $tail, $client) = @_;
                   2809: 
                   2810:     my $userinput = "cmd:$tail";
                   2811: 
                   2812:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2813:     chomp($what);
                   2814:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2815: 				 &GDBM_WRCREAT(),
                   2816: 				 "D",$what);
                   2817:     if ($hashref) {
                   2818:         my @keys=split(/\&/,$what);
                   2819: 	foreach my $key (@keys) {
                   2820: 	    delete($hashref->{$key});
                   2821: 	}
1.315     albertel 2822: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2823: 	    &Reply($client, "ok\n", $userinput);
                   2824: 	} else {
                   2825: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2826: 		    "while attempting del\n", $userinput);
                   2827: 	}
                   2828:     } else {
                   2829: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2830: 		 "while attempting del\n", $userinput);
                   2831:     }
                   2832:     return 1;
                   2833: }
                   2834: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 2835: 
1.231     foxr     2836: #
                   2837: #  List the set of keys that are defined in a profile database file.
                   2838: #  A successful reply from this will contain an & separated list of
                   2839: #  the keys. 
                   2840: # Parameters:
                   2841: #     $cmd              - Command request (keys).
                   2842: #     $tail             - Remainder of the request, a colon separated
                   2843: #                         list containing domain/user that identifies the
                   2844: #                         user being queried, and the database namespace
                   2845: #                         (database filename essentially).
                   2846: #     $client           - File open on the client.
                   2847: #  Returns:
                   2848: #    1    - Continue processing.
                   2849: #    0    - Exit the server.
                   2850: #
                   2851: sub get_profile_keys {
                   2852:     my ($cmd, $tail, $client) = @_;
                   2853: 
                   2854:     my $userinput = "$cmd:$tail";
                   2855: 
                   2856:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   2857:     my $qresult='';
                   2858:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2859: 				  &GDBM_READER());
                   2860:     if ($hashref) {
                   2861: 	foreach my $key (keys %$hashref) {
                   2862: 	    $qresult.="$key&";
                   2863: 	}
1.315     albertel 2864: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2865: 	    $qresult=~s/\&$//;
                   2866: 	    &Reply($client, "$qresult\n", $userinput);
                   2867: 	} else {
                   2868: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2869: 		    "while attempting keys\n", $userinput);
                   2870: 	}
                   2871:     } else {
                   2872: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2873: 		 "while attempting keys\n", $userinput);
                   2874:     }
                   2875:    
                   2876:     return 1;
                   2877: }
                   2878: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   2879: 
                   2880: #
                   2881: #   Dump the contents of a user profile database.
                   2882: #   Note that this constitutes a very large covert channel too since
                   2883: #   the dump will return sensitive information that is not encrypted.
                   2884: #   The naive security assumption is that the session negotiation ensures
                   2885: #   our client is trusted and I don't believe that's assured at present.
                   2886: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   2887: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   2888: # 
                   2889: #  Parameters:
                   2890: #     $cmd           - The command request keyword (currentdump).
                   2891: #     $tail          - Remainder of the request, consisting of a colon
                   2892: #                      separated list that has the domain/username and
                   2893: #                      the namespace to dump (database file).
                   2894: #     $client        - file open on the remote client.
                   2895: # Returns:
                   2896: #     1    - Continue processing.
                   2897: #     0    - Exit the server.
                   2898: #
                   2899: sub dump_profile_database {
                   2900:     my ($cmd, $tail, $client) = @_;
                   2901: 
                   2902:     my $userinput = "$cmd:$tail";
                   2903:    
                   2904:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   2905:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2906: 				 &GDBM_READER());
                   2907:     if ($hashref) {
                   2908: 	# Structure of %data:
                   2909: 	# $data{$symb}->{$parameter}=$value;
                   2910: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   2911: 	# since $parameter will be unescaped, we do not
                   2912:  	# have to worry about silly parameter names...
                   2913: 	
                   2914:         my $qresult='';
                   2915: 	my %data = ();                     # A hash of anonymous hashes..
                   2916: 	while (my ($key,$value) = each(%$hashref)) {
                   2917: 	    my ($v,$symb,$param) = split(/:/,$key);
                   2918: 	    next if ($v eq 'version' || $symb eq 'keys');
                   2919: 	    next if (exists($data{$symb}) && 
                   2920: 		     exists($data{$symb}->{$param}) &&
                   2921: 		     $data{$symb}->{'v.'.$param} > $v);
                   2922: 	    $data{$symb}->{$param}=$value;
                   2923: 	    $data{$symb}->{'v.'.$param}=$v;
                   2924: 	}
1.311     albertel 2925: 	if (&untie_user_hash($hashref)) {
1.231     foxr     2926: 	    while (my ($symb,$param_hash) = each(%data)) {
                   2927: 		while(my ($param,$value) = each (%$param_hash)){
                   2928: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   2929: 		    #
                   2930: 		    #   Just dump the symb=value pairs separated by &
                   2931: 		    #
                   2932: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   2933: 		}
                   2934: 	    }
                   2935: 	    chop($qresult);
                   2936: 	    &Reply($client , "$qresult\n", $userinput);
                   2937: 	} else {
                   2938: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2939: 		     "while attempting currentdump\n", $userinput);
                   2940: 	}
                   2941:     } else {
                   2942: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2943: 		"while attempting currentdump\n", $userinput);
                   2944:     }
                   2945: 
                   2946:     return 1;
                   2947: }
                   2948: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   2949: 
                   2950: #
                   2951: #   Dump a profile database with an optional regular expression
                   2952: #   to match against the keys.  In this dump, no effort is made
                   2953: #   to separate symb from version information. Presumably the
                   2954: #   databases that are dumped by this command are of a different
                   2955: #   structure.  Need to look at this and improve the documentation of
                   2956: #   both this and the currentdump handler.
                   2957: # Parameters:
                   2958: #    $cmd                     - The command keyword.
                   2959: #    $tail                    - All of the characters after the $cmd:
                   2960: #                               These are expected to be a colon
                   2961: #                               separated list containing:
                   2962: #                               domain/user - identifying the user.
                   2963: #                               namespace   - identifying the database.
                   2964: #                               regexp      - optional regular expression
                   2965: #                                             that is matched against
                   2966: #                                             database keywords to do
                   2967: #                                             selective dumps.
                   2968: #   $client                   - Channel open on the client.
                   2969: # Returns:
                   2970: #    1    - Continue processing.
                   2971: # Side effects:
                   2972: #    response is written to $client.
                   2973: #
                   2974: sub dump_with_regexp {
                   2975:     my ($cmd, $tail, $client) = @_;
                   2976: 
                   2977: 
                   2978:     my $userinput = "$cmd:$tail";
                   2979: 
1.306     albertel 2980:     my ($udom,$uname,$namespace,$regexp,$range)=split(/:/,$tail);
1.231     foxr     2981:     if (defined($regexp)) {
                   2982: 	$regexp=&unescape($regexp);
                   2983:     } else {
                   2984: 	$regexp='.';
                   2985:     }
1.306     albertel 2986:     my ($start,$end);
                   2987:     if (defined($range)) {
                   2988: 	if ($range =~/^(\d+)\-(\d+)$/) {
                   2989: 	    ($start,$end) = ($1,$2);
                   2990: 	} elsif ($range =~/^(\d+)$/) {
                   2991: 	    ($start,$end) = (0,$1);
                   2992: 	} else {
                   2993: 	    undef($range);
                   2994: 	}
                   2995:     }
1.231     foxr     2996:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2997: 				 &GDBM_READER());
                   2998:     if ($hashref) {
                   2999:         my $qresult='';
1.306     albertel 3000: 	my $count=0;
1.231     foxr     3001: 	while (my ($key,$value) = each(%$hashref)) {
                   3002: 	    if ($regexp eq '.') {
1.306     albertel 3003: 		$count++;
                   3004: 		if (defined($range) && $count >= $end)   { last; }
                   3005: 		if (defined($range) && $count <  $start) { next; }
1.231     foxr     3006: 		$qresult.=$key.'='.$value.'&';
                   3007: 	    } else {
                   3008: 		my $unescapeKey = &unescape($key);
                   3009: 		if (eval('$unescapeKey=~/$regexp/')) {
1.306     albertel 3010: 		    $count++;
                   3011: 		    if (defined($range) && $count >= $end)   { last; }
                   3012: 		    if (defined($range) && $count <  $start) { next; }
1.231     foxr     3013: 		    $qresult.="$key=$value&";
                   3014: 		}
                   3015: 	    }
                   3016: 	}
1.311     albertel 3017: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3018: 	    chop($qresult);
                   3019: 	    &Reply($client, "$qresult\n", $userinput);
                   3020: 	} else {
                   3021: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3022: 		     "while attempting dump\n", $userinput);
                   3023: 	}
                   3024:     } else {
                   3025: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3026: 		"while attempting dump\n", $userinput);
                   3027:     }
                   3028: 
                   3029:     return 1;
                   3030: }
                   3031: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3032: 
                   3033: #  Store a set of key=value pairs associated with a versioned name.
                   3034: #
                   3035: #  Parameters:
                   3036: #    $cmd                - Request command keyword.
                   3037: #    $tail               - Tail of the request.  This is a colon
                   3038: #                          separated list containing:
                   3039: #                          domain/user - User and authentication domain.
                   3040: #                          namespace   - Name of the database being modified
                   3041: #                          rid         - Resource keyword to modify.
                   3042: #                          what        - new value associated with rid.
                   3043: #
                   3044: #    $client             - Socket open on the client.
                   3045: #
                   3046: #
                   3047: #  Returns:
                   3048: #      1 (keep on processing).
                   3049: #  Side-Effects:
                   3050: #    Writes to the client
                   3051: sub store_handler {
                   3052:     my ($cmd, $tail, $client) = @_;
                   3053:  
                   3054:     my $userinput = "$cmd:$tail";
                   3055: 
                   3056:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
                   3057:     if ($namespace ne 'roles') {
                   3058: 
                   3059: 	chomp($what);
                   3060: 	my @pairs=split(/\&/,$what);
                   3061: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3062: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3063: 				       "$rid:$what");
                   3064: 	if ($hashref) {
                   3065: 	    my $now = time;
                   3066: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
                   3067: 	    my $key;
                   3068: 	    $hashref->{"version:$rid"}++;
                   3069: 	    my $version=$hashref->{"version:$rid"};
                   3070: 	    my $allkeys=''; 
                   3071: 	    foreach my $pair (@pairs) {
                   3072: 		my ($key,$value)=split(/=/,$pair);
                   3073: 		$allkeys.=$key.':';
                   3074: 		$hashref->{"$version:$rid:$key"}=$value;
                   3075: 	    }
                   3076: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3077: 	    $allkeys.='timestamp';
                   3078: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3079: 	    if (&untie_user_hash($hashref)) {
1.231     foxr     3080: 		&Reply($client, "ok\n", $userinput);
                   3081: 	    } else {
                   3082: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3083: 			"while attempting store\n", $userinput);
                   3084: 	    }
                   3085: 	} else {
                   3086: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3087: 		     "while attempting store\n", $userinput);
                   3088: 	}
                   3089:     } else {
                   3090: 	&Failure($client, "refused\n", $userinput);
                   3091:     }
                   3092: 
                   3093:     return 1;
                   3094: }
                   3095: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3096: 
1.323     albertel 3097: #  Modify a set of key=value pairs associated with a versioned name.
                   3098: #
                   3099: #  Parameters:
                   3100: #    $cmd                - Request command keyword.
                   3101: #    $tail               - Tail of the request.  This is a colon
                   3102: #                          separated list containing:
                   3103: #                          domain/user - User and authentication domain.
                   3104: #                          namespace   - Name of the database being modified
                   3105: #                          rid         - Resource keyword to modify.
                   3106: #                          v           - Version item to modify
                   3107: #                          what        - new value associated with rid.
                   3108: #
                   3109: #    $client             - Socket open on the client.
                   3110: #
                   3111: #
                   3112: #  Returns:
                   3113: #      1 (keep on processing).
                   3114: #  Side-Effects:
                   3115: #    Writes to the client
                   3116: sub putstore_handler {
                   3117:     my ($cmd, $tail, $client) = @_;
                   3118:  
                   3119:     my $userinput = "$cmd:$tail";
                   3120: 
                   3121:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3122:     if ($namespace ne 'roles') {
                   3123: 
                   3124: 	chomp($what);
                   3125: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3126: 				       &GDBM_WRCREAT(), "M",
                   3127: 				       "$rid:$v:$what");
                   3128: 	if ($hashref) {
                   3129: 	    my $now = time;
                   3130: 	    my %data = &hash_extract($what);
                   3131: 	    my @allkeys;
                   3132: 	    while (my($key,$value) = each(%data)) {
                   3133: 		push(@allkeys,$key);
                   3134: 		$hashref->{"$v:$rid:$key"} = $value;
                   3135: 	    }
                   3136: 	    my $allkeys = join(':',@allkeys);
                   3137: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3138: 
                   3139: 	    if (&untie_user_hash($hashref)) {
                   3140: 		&Reply($client, "ok\n", $userinput);
                   3141: 	    } else {
                   3142: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3143: 			"while attempting store\n", $userinput);
                   3144: 	    }
                   3145: 	} else {
                   3146: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3147: 		     "while attempting store\n", $userinput);
                   3148: 	}
                   3149:     } else {
                   3150: 	&Failure($client, "refused\n", $userinput);
                   3151:     }
                   3152: 
                   3153:     return 1;
                   3154: }
                   3155: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3156: 
                   3157: sub hash_extract {
                   3158:     my ($str)=@_;
                   3159:     my %hash;
                   3160:     foreach my $pair (split(/\&/,$str)) {
                   3161: 	my ($key,$value)=split(/=/,$pair);
                   3162: 	$hash{$key}=$value;
                   3163:     }
                   3164:     return (%hash);
                   3165: }
                   3166: sub hash_to_str {
                   3167:     my ($hash_ref)=@_;
                   3168:     my $str;
                   3169:     foreach my $key (keys(%$hash_ref)) {
                   3170: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3171:     }
                   3172:     $str=~s/\&$//;
                   3173:     return $str;
                   3174: }
                   3175: 
1.231     foxr     3176: #
                   3177: #  Dump out all versions of a resource that has key=value pairs associated
                   3178: # with it for each version.  These resources are built up via the store
                   3179: # command.
                   3180: #
                   3181: #  Parameters:
                   3182: #     $cmd               - Command keyword.
                   3183: #     $tail              - Remainder of the request which consists of:
                   3184: #                          domain/user   - User and auth. domain.
                   3185: #                          namespace     - name of resource database.
                   3186: #                          rid           - Resource id.
                   3187: #    $client             - socket open on the client.
                   3188: #
                   3189: # Returns:
                   3190: #      1  indicating the caller should not yet exit.
                   3191: # Side-effects:
                   3192: #   Writes a reply to the client.
                   3193: #   The reply is a string of the following shape:
                   3194: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3195: #    Where the 1 above represents version 1.
                   3196: #    this continues for all pairs of keys in all versions.
                   3197: #
                   3198: #
                   3199: #    
                   3200: #
                   3201: sub restore_handler {
                   3202:     my ($cmd, $tail, $client) = @_;
                   3203: 
                   3204:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
                   3205: 
                   3206:     my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
                   3207:     $namespace=~s/\//\_/g;
                   3208:     $namespace=~s/\W//g;
                   3209:     chomp($rid);
                   3210:     my $qresult='';
1.309     albertel 3211:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3212:     if ($hashref) {
                   3213: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3214: 	$qresult.="version=$version&";
                   3215: 	my $scope;
                   3216: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3217: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3218: 	    my @keys=split(/:/,$vkeys);
                   3219: 	    my $key;
                   3220: 	    $qresult.="$scope:keys=$vkeys&";
                   3221: 	    foreach $key (@keys) {
1.309     albertel 3222: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3223: 	    }                                  
                   3224: 	}
1.311     albertel 3225: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3226: 	    $qresult=~s/\&$//;
                   3227: 	    &Reply( $client, "$qresult\n", $userinput);
                   3228: 	} else {
                   3229: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3230: 		    "while attempting restore\n", $userinput);
                   3231: 	}
                   3232:     } else {
                   3233: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3234: 		"while attempting restore\n", $userinput);
                   3235:     }
                   3236:   
                   3237:     return 1;
                   3238: 
                   3239: 
                   3240: }
                   3241: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3242: 
                   3243: #
1.324     raeburn  3244: #   Add a chat message to a synchronous discussion board.
1.234     foxr     3245: #
                   3246: # Parameters:
                   3247: #    $cmd                - Request keyword.
                   3248: #    $tail               - Tail of the command. A colon separated list
                   3249: #                          containing:
                   3250: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  3251: #                          cnum    - Course containing the chat board.
                   3252: #                          newpost - Body of the posting.
                   3253: #                          group   - Optional group, if chat board is only 
                   3254: #                                    accessible in a group within the course 
1.234     foxr     3255: #   $client              - Socket open on the client.
                   3256: # Returns:
                   3257: #   1    - Indicating caller should keep on processing.
                   3258: #
                   3259: # Side-effects:
                   3260: #   writes a reply to the client.
                   3261: #
                   3262: #
                   3263: sub send_chat_handler {
                   3264:     my ($cmd, $tail, $client) = @_;
                   3265: 
                   3266:     
                   3267:     my $userinput = "$cmd:$tail";
                   3268: 
1.324     raeburn  3269:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   3270:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     3271:     &Reply($client, "ok\n", $userinput);
                   3272: 
                   3273:     return 1;
                   3274: }
                   3275: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3276: 
1.234     foxr     3277: #
1.324     raeburn  3278: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     3279: #
                   3280: #  Parameters:
                   3281: #    $cmd             - Command keyword that initiated the request.
                   3282: #    $tail            - Remainder of the request after the command
                   3283: #                       keyword.  In this case a colon separated list of
                   3284: #                       chat domain    - Which discussion board.
                   3285: #                       chat id        - Discussion thread(?)
                   3286: #                       domain/user    - Authentication domain and username
                   3287: #                                        of the requesting person.
1.324     raeburn  3288: #                       group          - Optional course group containing
                   3289: #                                        the board.      
1.234     foxr     3290: #   $client           - Socket open on the client program.
                   3291: # Returns:
                   3292: #    1     - continue processing
                   3293: # Side effects:
                   3294: #    Response is written to the client.
                   3295: #
                   3296: sub retrieve_chat_handler {
                   3297:     my ($cmd, $tail, $client) = @_;
                   3298: 
                   3299: 
                   3300:     my $userinput = "$cmd:$tail";
                   3301: 
1.324     raeburn  3302:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     3303:     my $reply='';
1.324     raeburn  3304:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     3305: 	$reply.=&escape($_).':';
                   3306:     }
                   3307:     $reply=~s/\:$//;
                   3308:     &Reply($client, $reply."\n", $userinput);
                   3309: 
                   3310: 
                   3311:     return 1;
                   3312: }
                   3313: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3314: 
                   3315: #
                   3316: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3317: #  a file for later retrieval.  This prevents sql query results from
                   3318: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3319: #  less of an issue since multiple outstanding requests can be concurrently
                   3320: #  serviced.
                   3321: #
                   3322: #  Parameters:
                   3323: #     $cmd       - COmmand keyword that initiated the request.
                   3324: #     $tail      - Remainder of the command after the keyword.
                   3325: #                  For this function, this consists of a query and
                   3326: #                  3 arguments that are self-documentingly labelled
                   3327: #                  in the original arg1, arg2, arg3.
                   3328: #     $client    - Socket open on the client.
                   3329: # Return:
                   3330: #    1   - Indicating processing should continue.
                   3331: # Side-effects:
                   3332: #    a reply is written to $client.
                   3333: #
                   3334: sub send_query_handler {
                   3335:     my ($cmd, $tail, $client) = @_;
                   3336: 
                   3337: 
                   3338:     my $userinput = "$cmd:$tail";
                   3339: 
                   3340:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3341:     $query=~s/\n*$//g;
                   3342:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   3343: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   3344: 	  $userinput);
                   3345:     
                   3346:     return 1;
                   3347: }
                   3348: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   3349: 
                   3350: #
                   3351: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   3352: #   The query is submitted via a "querysend" transaction.
                   3353: #   There it is passed on to the lonsql daemon, queued and issued to
                   3354: #   mysql.
                   3355: #     This transaction is invoked when the sql transaction is complete
                   3356: #   it stores the query results in flie and indicates query completion.
                   3357: #   presumably local software then fetches this response... I'm guessing
                   3358: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   3359: #   lonsql on completion of the query interacts with the lond of our
                   3360: #   client to do a query reply storing two files:
                   3361: #    - id     - The results of the query.
                   3362: #    - id.end - Indicating the transaction completed. 
                   3363: #    NOTE: id is a unique id assigned to the query and querysend time.
                   3364: # Parameters:
                   3365: #    $cmd        - Command keyword that initiated this request.
                   3366: #    $tail       - Remainder of the tail.  In this case that's a colon
                   3367: #                  separated list containing the query Id and the 
                   3368: #                  results of the query.
                   3369: #    $client     - Socket open on the client.
                   3370: # Return:
                   3371: #    1           - Indicating that we should continue processing.
                   3372: # Side effects:
                   3373: #    ok written to the client.
                   3374: #
                   3375: sub reply_query_handler {
                   3376:     my ($cmd, $tail, $client) = @_;
                   3377: 
                   3378: 
                   3379:     my $userinput = "$cmd:$tail";
                   3380: 
                   3381:     my ($cmd,$id,$reply)=split(/:/,$userinput); 
                   3382:     my $store;
                   3383:     my $execdir=$perlvar{'lonDaemons'};
                   3384:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   3385: 	$reply=~s/\&/\n/g;
                   3386: 	print $store $reply;
                   3387: 	close $store;
                   3388: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   3389: 	print $store2 "done\n";
                   3390: 	close $store2;
                   3391: 	&Reply($client, "ok\n", $userinput);
                   3392:     } else {
                   3393: 	&Failure($client, "error: ".($!+0)
                   3394: 		." IO::File->new Failed ".
                   3395: 		"while attempting queryreply\n", $userinput);
                   3396:     }
                   3397:  
                   3398: 
                   3399:     return 1;
                   3400: }
                   3401: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   3402: 
                   3403: #
                   3404: #  Process the courseidput request.  Not quite sure what this means
                   3405: #  at the system level sense.  It appears a gdbm file in the 
                   3406: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   3407: #  a set of entries made in that database.
                   3408: #
                   3409: # Parameters:
                   3410: #   $cmd      - The command keyword that initiated this request.
                   3411: #   $tail     - Tail of the command.  In this case consists of a colon
                   3412: #               separated list contaning the domain to apply this to and
                   3413: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  3414: #               Each value is a colon separated list that includes:  
                   3415: #               description, institutional code and course owner.
                   3416: #               For backward compatibility with versions included
                   3417: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   3418: #               code and/or course owner are preserved from the existing 
                   3419: #               record when writing a new record in response to 1.1 or 
                   3420: #               1.2 implementations of lonnet::flushcourselogs().   
                   3421: #                      
1.234     foxr     3422: #   $client   - Socket open on the client.
                   3423: # Returns:
                   3424: #   1    - indicating that processing should continue
                   3425: #
                   3426: # Side effects:
                   3427: #   reply is written to the client.
                   3428: #
                   3429: sub put_course_id_handler {
                   3430:     my ($cmd, $tail, $client) = @_;
                   3431: 
                   3432: 
                   3433:     my $userinput = "$cmd:$tail";
                   3434: 
1.266     raeburn  3435:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     3436:     chomp($what);
                   3437:     my $now=time;
                   3438:     my @pairs=split(/\&/,$what);
                   3439: 
                   3440:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3441:     if ($hashref) {
                   3442: 	foreach my $pair (@pairs) {
1.271     raeburn  3443:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   3444:             $courseinfo =~ s/=/:/g;
1.272     raeburn  3445: 
1.273     albertel 3446:             my @current_items = split(/:/,$hashref->{$key});
                   3447:             shift(@current_items); # remove description
                   3448:             pop(@current_items);   # remove last access
1.272     raeburn  3449:             my $numcurrent = scalar(@current_items);
                   3450: 
1.273     albertel 3451:             my @new_items = split(/:/,$courseinfo);
1.272     raeburn  3452:             my $numnew = scalar(@new_items);
                   3453:             if ($numcurrent > 0) {
                   3454:                 if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
                   3455:                     $courseinfo .= ':'.join(':',@current_items);
                   3456:                 } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
                   3457:                     $courseinfo .= ':'.$current_items[$numcurrent-1];
                   3458:                 }
                   3459:             }
1.266     raeburn  3460: 	    $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     3461: 	}
1.311     albertel 3462: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     3463: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     3464: 	} else {
1.253     foxr     3465: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     3466: 		     ." untie(GDBM) Failed ".
                   3467: 		     "while attempting courseidput\n", $userinput);
                   3468: 	}
                   3469:     } else {
1.253     foxr     3470: 	&Failure($client, "error: ".($!+0)
1.234     foxr     3471: 		 ." tie(GDBM) Failed ".
                   3472: 		 "while attempting courseidput\n", $userinput);
                   3473:     }
1.253     foxr     3474:     
1.234     foxr     3475: 
                   3476:     return 1;
                   3477: }
                   3478: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   3479: 
                   3480: #  Retrieves the value of a course id resource keyword pattern
                   3481: #  defined since a starting date.  Both the starting date and the
                   3482: #  keyword pattern are optional.  If the starting date is not supplied it
                   3483: #  is treated as the beginning of time.  If the pattern is not found,
                   3484: #  it is treatred as "." matching everything.
                   3485: #
                   3486: #  Parameters:
                   3487: #     $cmd     - Command keyword that resulted in us being dispatched.
                   3488: #     $tail    - The remainder of the command that, in this case, consists
                   3489: #                of a colon separated list of:
                   3490: #                 domain   - The domain in which the course database is 
                   3491: #                            defined.
                   3492: #                 since    - Optional parameter describing the minimum
                   3493: #                            time of definition(?) of the resources that
                   3494: #                            will match the dump.
                   3495: #                 description - regular expression that is used to filter
                   3496: #                            the dump.  Only keywords matching this regexp
                   3497: #                            will be used.
1.272     raeburn  3498: #                 institutional code - optional supplied code to filter 
                   3499: #                            the dump. Only courses with an institutional code 
                   3500: #                            that match the supplied code will be returned.
                   3501: #                 owner    - optional supplied username of owner to filter
                   3502: #                            the dump.  Only courses for which the course 
                   3503: #                            owner matches the supplied username will be
1.274     albertel 3504: #                            returned. Implicit assumption that owner
                   3505: #                            is a user in the domain in which the
                   3506: #                            course database is defined.
1.234     foxr     3507: #     $client  - The socket open on the client.
                   3508: # Returns:
                   3509: #    1     - Continue processing.
                   3510: # Side Effects:
                   3511: #   a reply is written to $client.
                   3512: sub dump_course_id_handler {
                   3513:     my ($cmd, $tail, $client) = @_;
                   3514: 
                   3515:     my $userinput = "$cmd:$tail";
                   3516: 
1.282     raeburn  3517:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter) =split(/:/,$tail);
1.234     foxr     3518:     if (defined($description)) {
                   3519: 	$description=&unescape($description);
                   3520:     } else {
                   3521: 	$description='.';
                   3522:     }
1.266     raeburn  3523:     if (defined($instcodefilter)) {
                   3524:         $instcodefilter=&unescape($instcodefilter);
                   3525:     } else {
                   3526:         $instcodefilter='.';
                   3527:     }
                   3528:     if (defined($ownerfilter)) {
                   3529:         $ownerfilter=&unescape($ownerfilter);
                   3530:     } else {
                   3531:         $ownerfilter='.';
                   3532:     }
1.282     raeburn  3533:     if (defined($coursefilter)) {
                   3534:         $coursefilter=&unescape($coursefilter);
                   3535:     } else {
                   3536:         $coursefilter='.';
                   3537:     }
1.266     raeburn  3538: 
1.234     foxr     3539:     unless (defined($since)) { $since=0; }
                   3540:     my $qresult='';
                   3541:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3542:     if ($hashref) {
                   3543: 	while (my ($key,$value) = each(%$hashref)) {
1.266     raeburn  3544: 	    my ($descr,$lasttime,$inst_code,$owner);
1.274     albertel 3545:             my @courseitems = split(/:/,$value);
                   3546:             $lasttime = pop(@courseitems);
                   3547: 	    ($descr,$inst_code,$owner)=@courseitems;
1.234     foxr     3548: 	    if ($lasttime<$since) { next; }
1.266     raeburn  3549:             my $match = 1;
                   3550: 	    unless ($description eq '.') {
                   3551: 		my $unescapeDescr = &unescape($descr);
                   3552: 		unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
                   3553:                     $match = 0;
1.234     foxr     3554: 		}
1.266     raeburn  3555:             }
                   3556:             unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
                   3557:                 my $unescapeInstcode = &unescape($inst_code);
                   3558:                 unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
                   3559:                     $match = 0;
                   3560:                 }
1.234     foxr     3561: 	    }
1.266     raeburn  3562:             unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
                   3563:                 my $unescapeOwner = &unescape($owner);
                   3564:                 unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
                   3565:                     $match = 0;
                   3566:                 }
                   3567:             }
1.282     raeburn  3568:             unless ($coursefilter eq '.' || !defined($coursefilter)) {
                   3569:                 my $unescapeCourse = &unescape($key);
                   3570:                 unless (eval('$unescapeCourse=~/^$udom(_)\Q$coursefilter\E$/')) {
                   3571:                     $match = 0;
                   3572:                 }
                   3573:             }
1.266     raeburn  3574:             if ($match == 1) {
                   3575:                 $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
                   3576:             }
1.234     foxr     3577: 	}
1.311     albertel 3578: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     3579: 	    chop($qresult);
                   3580: 	    &Reply($client, "$qresult\n", $userinput);
                   3581: 	} else {
                   3582: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3583: 		    "while attempting courseiddump\n", $userinput);
                   3584: 	}
                   3585:     } else {
                   3586: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3587: 		"while attempting courseiddump\n", $userinput);
                   3588:     }
                   3589: 
                   3590: 
                   3591:     return 1;
                   3592: }
                   3593: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     3594: 
                   3595: #
                   3596: #  Puts an id to a domains id database. 
                   3597: #
                   3598: #  Parameters:
                   3599: #   $cmd     - The command that triggered us.
                   3600: #   $tail    - Remainder of the request other than the command. This is a 
                   3601: #              colon separated list containing:
                   3602: #              $domain  - The domain for which we are writing the id.
                   3603: #              $pairs  - The id info to write... this is and & separated list
                   3604: #                        of keyword=value.
                   3605: #   $client  - Socket open on the client.
                   3606: #  Returns:
                   3607: #    1   - Continue processing.
                   3608: #  Side effects:
                   3609: #     reply is written to $client.
                   3610: #
                   3611: sub put_id_handler {
                   3612:     my ($cmd,$tail,$client) = @_;
                   3613: 
                   3614: 
                   3615:     my $userinput = "$cmd:$tail";
                   3616: 
                   3617:     my ($udom,$what)=split(/:/,$tail);
                   3618:     chomp($what);
                   3619:     my @pairs=split(/\&/,$what);
                   3620:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   3621: 				   "P", $what);
                   3622:     if ($hashref) {
                   3623: 	foreach my $pair (@pairs) {
                   3624: 	    my ($key,$value)=split(/=/,$pair);
                   3625: 	    $hashref->{$key}=$value;
                   3626: 	}
1.311     albertel 3627: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     3628: 	    &Reply($client, "ok\n", $userinput);
                   3629: 	} else {
                   3630: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3631: 		     "while attempting idput\n", $userinput);
                   3632: 	}
                   3633:     } else {
                   3634: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3635: 		  "while attempting idput\n", $userinput);
                   3636:     }
                   3637: 
                   3638:     return 1;
                   3639: }
1.263     albertel 3640: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     3641: 
                   3642: #
                   3643: #  Retrieves a set of id values from the id database.
                   3644: #  Returns an & separated list of results, one for each requested id to the
                   3645: #  client.
                   3646: #
                   3647: # Parameters:
                   3648: #   $cmd       - Command keyword that caused us to be dispatched.
                   3649: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3650: #               domain - the domain whose id table we dump
                   3651: #               ids      Consists of an & separated list of
                   3652: #                        id keywords whose values will be fetched.
                   3653: #                        nonexisting keywords will have an empty value.
                   3654: #   $client    - Socket open on the client.
                   3655: #
                   3656: # Returns:
                   3657: #    1 - indicating processing should continue.
                   3658: # Side effects:
                   3659: #   An & separated list of results is written to $client.
                   3660: #
                   3661: sub get_id_handler {
                   3662:     my ($cmd, $tail, $client) = @_;
                   3663: 
                   3664:     
                   3665:     my $userinput = "$client:$tail";
                   3666:     
                   3667:     my ($udom,$what)=split(/:/,$tail);
                   3668:     chomp($what);
                   3669:     my @queries=split(/\&/,$what);
                   3670:     my $qresult='';
                   3671:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   3672:     if ($hashref) {
                   3673: 	for (my $i=0;$i<=$#queries;$i++) {
                   3674: 	    $qresult.="$hashref->{$queries[$i]}&";
                   3675: 	}
1.311     albertel 3676: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     3677: 	    $qresult=~s/\&$//;
                   3678: 	    &Reply($client, "$qresult\n", $userinput);
                   3679: 	} else {
                   3680: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3681: 		      "while attempting idget\n",$userinput);
                   3682: 	}
                   3683:     } else {
                   3684: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3685: 		 "while attempting idget\n",$userinput);
                   3686:     }
                   3687:     
                   3688:     return 1;
                   3689: }
1.263     albertel 3690: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     3691: 
                   3692: #
1.299     raeburn  3693: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   3694: #
                   3695: # Parameters
                   3696: #   $cmd       - Command keyword that caused us to be dispatched.
                   3697: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3698: #               domain - the domain whose dcmail we are recording
                   3699: #               email    Consists of key=value pair 
                   3700: #                        where key is unique msgid
                   3701: #                        and value is message (in XML)
                   3702: #   $client    - Socket open on the client.
                   3703: #
                   3704: # Returns:
                   3705: #    1 - indicating processing should continue.
                   3706: # Side effects
                   3707: #     reply is written to $client.
                   3708: #
                   3709: sub put_dcmail_handler {
                   3710:     my ($cmd,$tail,$client) = @_;
                   3711:     my $userinput = "$cmd:$tail";
                   3712:                                                                                 
                   3713:     my ($udom,$what)=split(/:/,$tail);
                   3714:     chomp($what);
                   3715:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   3716:     if ($hashref) {
                   3717:         my ($key,$value)=split(/=/,$what);
                   3718:         $hashref->{$key}=$value;
                   3719:     }
1.311     albertel 3720:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  3721:         &Reply($client, "ok\n", $userinput);
                   3722:     } else {
                   3723:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3724:                  "while attempting dcmailput\n", $userinput);
                   3725:     }
                   3726:     return 1;
                   3727: }
                   3728: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   3729: 
                   3730: #
                   3731: # Retrieves broadcast e-mail from nohist_dcmail database
                   3732: # Returns to client an & separated list of key=value pairs,
                   3733: # where key is msgid and value is message information.
                   3734: #
                   3735: # Parameters
                   3736: #   $cmd       - Command keyword that caused us to be dispatched.
                   3737: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3738: #               domain - the domain whose dcmail table we dump
                   3739: #               startfilter - beginning of time window 
                   3740: #               endfilter - end of time window
                   3741: #               sendersfilter - & separated list of username:domain 
                   3742: #                 for senders to search for.
                   3743: #   $client    - Socket open on the client.
                   3744: #
                   3745: # Returns:
                   3746: #    1 - indicating processing should continue.
                   3747: # Side effects
                   3748: #     reply (& separated list of msgid=messageinfo pairs) is 
                   3749: #     written to $client.
                   3750: #
                   3751: sub dump_dcmail_handler {
                   3752:     my ($cmd, $tail, $client) = @_;
                   3753:                                                                                 
                   3754:     my $userinput = "$cmd:$tail";
                   3755:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   3756:     chomp($sendersfilter);
                   3757:     my @senders = ();
                   3758:     if (defined($startfilter)) {
                   3759:         $startfilter=&unescape($startfilter);
                   3760:     } else {
                   3761:         $startfilter='.';
                   3762:     }
                   3763:     if (defined($endfilter)) {
                   3764:         $endfilter=&unescape($endfilter);
                   3765:     } else {
                   3766:         $endfilter='.';
                   3767:     }
                   3768:     if (defined($sendersfilter)) {
                   3769:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 3770: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  3771:     }
                   3772: 
                   3773:     my $qresult='';
                   3774:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   3775:     if ($hashref) {
                   3776:         while (my ($key,$value) = each(%$hashref)) {
                   3777:             my $match = 1;
1.303     albertel 3778:             my ($timestamp,$subj,$uname,$udom) = 
                   3779: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  3780:             $subj = &unescape($subj);
                   3781:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   3782:                 if ($timestamp < $startfilter) {
                   3783:                     $match = 0;
                   3784:                 }
                   3785:             }
                   3786:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   3787:                 if ($timestamp > $endfilter) {
                   3788:                     $match = 0;
                   3789:                 }
                   3790:             }
                   3791:             unless (@senders < 1) {
                   3792:                 unless (grep/^$uname:$udom$/,@senders) {
                   3793:                     $match = 0;
                   3794:                 }
                   3795:             }
                   3796:             if ($match == 1) {
                   3797:                 $qresult.=$key.'='.$value.'&';
                   3798:             }
                   3799:         }
1.311     albertel 3800:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  3801:             chop($qresult);
                   3802:             &Reply($client, "$qresult\n", $userinput);
                   3803:         } else {
                   3804:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3805:                     "while attempting dcmaildump\n", $userinput);
                   3806:         }
                   3807:     } else {
                   3808:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3809:                 "while attempting dcmaildump\n", $userinput);
                   3810:     }
                   3811:     return 1;
                   3812: }
                   3813: 
                   3814: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   3815: 
                   3816: #
                   3817: # Puts domain roles in nohist_domainroles database
                   3818: #
                   3819: # Parameters
                   3820: #   $cmd       - Command keyword that caused us to be dispatched.
                   3821: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3822: #               domain - the domain whose roles we are recording  
                   3823: #               role -   Consists of key=value pair
                   3824: #                        where key is unique role
                   3825: #                        and value is start/end date information
                   3826: #   $client    - Socket open on the client.
                   3827: #
                   3828: # Returns:
                   3829: #    1 - indicating processing should continue.
                   3830: # Side effects
                   3831: #     reply is written to $client.
                   3832: #
                   3833: 
                   3834: sub put_domainroles_handler {
                   3835:     my ($cmd,$tail,$client) = @_;
                   3836: 
                   3837:     my $userinput = "$cmd:$tail";
                   3838:     my ($udom,$what)=split(/:/,$tail);
                   3839:     chomp($what);
                   3840:     my @pairs=split(/\&/,$what);
                   3841:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   3842:     if ($hashref) {
                   3843:         foreach my $pair (@pairs) {
                   3844:             my ($key,$value)=split(/=/,$pair);
                   3845:             $hashref->{$key}=$value;
                   3846:         }
1.311     albertel 3847:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  3848:             &Reply($client, "ok\n", $userinput);
                   3849:         } else {
                   3850:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3851:                      "while attempting domroleput\n", $userinput);
                   3852:         }
                   3853:     } else {
                   3854:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3855:                   "while attempting domroleput\n", $userinput);
                   3856:     }
                   3857:                                                                                   
                   3858:     return 1;
                   3859: }
                   3860: 
                   3861: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   3862: 
                   3863: #
                   3864: # Retrieves domain roles from nohist_domainroles database
                   3865: # Returns to client an & separated list of key=value pairs,
                   3866: # where key is role and value is start and end date information.
                   3867: #
                   3868: # Parameters
                   3869: #   $cmd       - Command keyword that caused us to be dispatched.
                   3870: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3871: #               domain - the domain whose domain roles table we dump
                   3872: #   $client    - Socket open on the client.
                   3873: #
                   3874: # Returns:
                   3875: #    1 - indicating processing should continue.
                   3876: # Side effects
                   3877: #     reply (& separated list of role=start/end info pairs) is
                   3878: #     written to $client.
                   3879: #
                   3880: sub dump_domainroles_handler {
                   3881:     my ($cmd, $tail, $client) = @_;
                   3882:                                                                                            
                   3883:     my $userinput = "$cmd:$tail";
                   3884:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   3885:     chomp($rolesfilter);
                   3886:     my @roles = ();
                   3887:     if (defined($startfilter)) {
                   3888:         $startfilter=&unescape($startfilter);
                   3889:     } else {
                   3890:         $startfilter='.';
                   3891:     }
                   3892:     if (defined($endfilter)) {
                   3893:         $endfilter=&unescape($endfilter);
                   3894:     } else {
                   3895:         $endfilter='.';
                   3896:     }
                   3897:     if (defined($rolesfilter)) {
                   3898:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 3899: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  3900:     }
                   3901:                                                                                            
                   3902:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   3903:     if ($hashref) {
                   3904:         my $qresult = '';
                   3905:         while (my ($key,$value) = each(%$hashref)) {
                   3906:             my $match = 1;
                   3907:             my ($start,$end) = split(/:/,&unescape($value));
                   3908:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
                   3909:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   3910:                 if ($start >= $startfilter) {
                   3911:                     $match = 0;
                   3912:                 }
                   3913:             }
                   3914:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   3915:                 if ($end <= $endfilter) {
                   3916:                     $match = 0;
                   3917:                 }
                   3918:             }
                   3919:             unless (@roles < 1) {
                   3920:                 unless (grep/^$trole$/,@roles) {
                   3921:                     $match = 0;
                   3922:                 }
                   3923:             }
                   3924:             if ($match == 1) {
                   3925:                 $qresult.=$key.'='.$value.'&';
                   3926:             }
                   3927:         }
1.311     albertel 3928:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  3929:             chop($qresult);
                   3930:             &Reply($client, "$qresult\n", $userinput);
                   3931:         } else {
                   3932:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3933:                     "while attempting domrolesdump\n", $userinput);
                   3934:         }
                   3935:     } else {
                   3936:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3937:                 "while attempting domrolesdump\n", $userinput);
                   3938:     }
                   3939:     return 1;
                   3940: }
                   3941: 
                   3942: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   3943: 
                   3944: 
1.238     foxr     3945: #  Process the tmpput command I'm not sure what this does.. Seems to
                   3946: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   3947: # where Id is the client's ip concatenated with a sequence number.
                   3948: # The file will contain some value that is passed in.  Is this e.g.
                   3949: # a login token?
                   3950: #
                   3951: # Parameters:
                   3952: #    $cmd     - The command that got us dispatched.
                   3953: #    $tail    - The remainder of the request following $cmd:
                   3954: #               In this case this will be the contents of the file.
                   3955: #    $client  - Socket connected to the client.
                   3956: # Returns:
                   3957: #    1 indicating processing can continue.
                   3958: # Side effects:
                   3959: #   A file is created in the local filesystem.
                   3960: #   A reply is sent to the client.
                   3961: sub tmp_put_handler {
                   3962:     my ($cmd, $what, $client) = @_;
                   3963: 
                   3964:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   3965: 
                   3966: 
                   3967:     my $store;
                   3968:     $tmpsnum++;
                   3969:     my $id=$$.'_'.$clientip.'_'.$tmpsnum;
                   3970:     $id=~s/\W/\_/g;
                   3971:     $what=~s/\n//g;
                   3972:     my $execdir=$perlvar{'lonDaemons'};
                   3973:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
                   3974: 	print $store $what;
                   3975: 	close $store;
                   3976: 	&Reply($client, "$id\n", $userinput);
                   3977:     } else {
                   3978: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   3979: 		  "while attempting tmpput\n", $userinput);
                   3980:     }
                   3981:     return 1;
                   3982:   
                   3983: }
                   3984: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 3985: 
1.238     foxr     3986: #   Processes the tmpget command.  This command returns the contents
                   3987: #  of a temporary resource file(?) created via tmpput.
                   3988: #
                   3989: # Paramters:
                   3990: #    $cmd      - Command that got us dispatched.
                   3991: #    $id       - Tail of the command, contain the id of the resource
                   3992: #                we want to fetch.
                   3993: #    $client   - socket open on the client.
                   3994: # Return:
                   3995: #    1         - Inidcating processing can continue.
                   3996: # Side effects:
                   3997: #   A reply is sent to the client.
                   3998: #
                   3999: sub tmp_get_handler {
                   4000:     my ($cmd, $id, $client) = @_;
                   4001: 
                   4002:     my $userinput = "$cmd:$id"; 
                   4003:     
                   4004: 
                   4005:     $id=~s/\W/\_/g;
                   4006:     my $store;
                   4007:     my $execdir=$perlvar{'lonDaemons'};
                   4008:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   4009: 	my $reply=<$store>;
                   4010: 	&Reply( $client, "$reply\n", $userinput);
                   4011: 	close $store;
                   4012:     } else {
                   4013: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   4014: 		  "while attempting tmpget\n", $userinput);
                   4015:     }
                   4016: 
                   4017:     return 1;
                   4018: }
                   4019: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 4020: 
1.238     foxr     4021: #
                   4022: #  Process the tmpdel command.  This command deletes a temp resource
                   4023: #  created by the tmpput command.
                   4024: #
                   4025: # Parameters:
                   4026: #   $cmd      - Command that got us here.
                   4027: #   $id       - Id of the temporary resource created.
                   4028: #   $client   - socket open on the client process.
                   4029: #
                   4030: # Returns:
                   4031: #   1     - Indicating processing should continue.
                   4032: # Side Effects:
                   4033: #   A file is deleted
                   4034: #   A reply is sent to the client.
                   4035: sub tmp_del_handler {
                   4036:     my ($cmd, $id, $client) = @_;
                   4037:     
                   4038:     my $userinput= "$cmd:$id";
                   4039:     
                   4040:     chomp($id);
                   4041:     $id=~s/\W/\_/g;
                   4042:     my $execdir=$perlvar{'lonDaemons'};
                   4043:     if (unlink("$execdir/tmp/$id.tmp")) {
                   4044: 	&Reply($client, "ok\n", $userinput);
                   4045:     } else {
                   4046: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   4047: 		  "while attempting tmpdel\n", $userinput);
                   4048:     }
                   4049:     
                   4050:     return 1;
                   4051: 
                   4052: }
                   4053: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 4054: 
1.238     foxr     4055: #
1.246     foxr     4056: #   Processes the setannounce command.  This command
                   4057: #   creates a file named announce.txt in the top directory of
                   4058: #   the documentn root and sets its contents.  The announce.txt file is
                   4059: #   printed in its entirety at the LonCAPA login page.  Note:
                   4060: #   once the announcement.txt fileis created it cannot be deleted.
                   4061: #   However, setting the contents of the file to empty removes the
                   4062: #   announcement from the login page of loncapa so who cares.
                   4063: #
                   4064: # Parameters:
                   4065: #    $cmd          - The command that got us dispatched.
                   4066: #    $announcement - The text of the announcement.
                   4067: #    $client       - Socket open on the client process.
                   4068: # Retunrns:
                   4069: #   1             - Indicating request processing should continue
                   4070: # Side Effects:
                   4071: #   The file {DocRoot}/announcement.txt is created.
                   4072: #   A reply is sent to $client.
                   4073: #
                   4074: sub set_announce_handler {
                   4075:     my ($cmd, $announcement, $client) = @_;
                   4076:   
                   4077:     my $userinput    = "$cmd:$announcement";
                   4078: 
                   4079:     chomp($announcement);
                   4080:     $announcement=&unescape($announcement);
                   4081:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   4082: 				'/announcement.txt')) {
                   4083: 	print $store $announcement;
                   4084: 	close $store;
                   4085: 	&Reply($client, "ok\n", $userinput);
                   4086:     } else {
                   4087: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   4088:     }
                   4089: 
                   4090:     return 1;
                   4091: }
                   4092: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 4093: 
1.246     foxr     4094: #
                   4095: #  Return the version of the daemon.  This can be used to determine
                   4096: #  the compatibility of cross version installations or, alternatively to
                   4097: #  simply know who's out of date and who isn't.  Note that the version
                   4098: #  is returned concatenated with the tail.
                   4099: # Parameters:
                   4100: #   $cmd        - the request that dispatched to us.
                   4101: #   $tail       - Tail of the request (client's version?).
                   4102: #   $client     - Socket open on the client.
                   4103: #Returns:
                   4104: #   1 - continue processing requests.
                   4105: # Side Effects:
                   4106: #   Replies with version to $client.
                   4107: sub get_version_handler {
                   4108:     my ($cmd, $tail, $client) = @_;
                   4109: 
                   4110:     my $userinput  = $cmd.$tail;
                   4111:     
                   4112:     &Reply($client, &version($userinput)."\n", $userinput);
                   4113: 
                   4114: 
                   4115:     return 1;
                   4116: }
                   4117: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 4118: 
1.246     foxr     4119: #  Set the current host and domain.  This is used to support
                   4120: #  multihomed systems.  Each IP of the system, or even separate daemons
                   4121: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   4122: #  machine.  This command selects the virtual lonCAPA.  The client always
                   4123: #  knows the right one since it is lonc and it is selecting the domain/system
                   4124: #  from the hosts.tab file.
                   4125: # Parameters:
                   4126: #    $cmd      - Command that dispatched us.
                   4127: #    $tail     - Tail of the command (domain/host requested).
                   4128: #    $socket   - Socket open on the client.
                   4129: #
                   4130: # Returns:
                   4131: #     1   - Indicates the program should continue to process requests.
                   4132: # Side-effects:
                   4133: #     The default domain/system context is modified for this daemon.
                   4134: #     a reply is sent to the client.
                   4135: #
                   4136: sub set_virtual_host_handler {
                   4137:     my ($cmd, $tail, $socket) = @_;
                   4138:   
                   4139:     my $userinput  ="$cmd:$tail";
                   4140: 
                   4141:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   4142: 
                   4143: 
                   4144:     return 1;
                   4145: }
1.247     albertel 4146: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     4147: 
                   4148: #  Process a request to exit:
                   4149: #   - "bye" is sent to the client.
                   4150: #   - The client socket is shutdown and closed.
                   4151: #   - We indicate to the caller that we should exit.
                   4152: # Formal Parameters:
                   4153: #   $cmd                - The command that got us here.
                   4154: #   $tail               - Tail of the command (empty).
                   4155: #   $client             - Socket open on the tail.
                   4156: # Returns:
                   4157: #   0      - Indicating the program should exit!!
                   4158: #
                   4159: sub exit_handler {
                   4160:     my ($cmd, $tail, $client) = @_;
                   4161: 
                   4162:     my $userinput = "$cmd:$tail";
                   4163: 
                   4164:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   4165:     &Reply($client, "bye\n", $userinput);
                   4166:     $client->shutdown(2);        # shutdown the socket forcibly.
                   4167:     $client->close();
                   4168: 
                   4169:     return 0;
                   4170: }
1.248     foxr     4171: &register_handler("exit", \&exit_handler, 0,1,1);
                   4172: &register_handler("init", \&exit_handler, 0,1,1);
                   4173: &register_handler("quit", \&exit_handler, 0,1,1);
                   4174: 
                   4175: #  Determine if auto-enrollment is enabled.
                   4176: #  Note that the original had what I believe to be a defect.
                   4177: #  The original returned 0 if the requestor was not a registerd client.
                   4178: #  It should return "refused".
                   4179: # Formal Parameters:
                   4180: #   $cmd       - The command that invoked us.
                   4181: #   $tail      - The tail of the command (Extra command parameters.
                   4182: #   $client    - The socket open on the client that issued the request.
                   4183: # Returns:
                   4184: #    1         - Indicating processing should continue.
                   4185: #
                   4186: sub enrollment_enabled_handler {
                   4187:     my ($cmd, $tail, $client) = @_;
                   4188:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   4189: 
                   4190:     
                   4191:     my $cdom = split(/:/, $tail);   # Domain we're asking about.
                   4192:     my $outcome  = &localenroll::run($cdom);
                   4193:     &Reply($client, "$outcome\n", $userinput);
                   4194: 
                   4195:     return 1;
                   4196: }
                   4197: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   4198: 
                   4199: #   Get the official sections for which auto-enrollment is possible.
                   4200: #   Since the admin people won't know about 'unofficial sections' 
                   4201: #   we cannot auto-enroll on them.
                   4202: # Formal Parameters:
                   4203: #    $cmd     - The command request that got us dispatched here.
                   4204: #    $tail    - The remainder of the request.  In our case this
                   4205: #               will be split into:
                   4206: #               $coursecode   - The course name from the admin point of view.
                   4207: #               $cdom         - The course's domain(?).
                   4208: #    $client  - Socket open on the client.
                   4209: # Returns:
                   4210: #    1    - Indiciting processing should continue.
                   4211: #
                   4212: sub get_sections_handler {
                   4213:     my ($cmd, $tail, $client) = @_;
                   4214:     my $userinput = "$cmd:$tail";
                   4215: 
                   4216:     my ($coursecode, $cdom) = split(/:/, $tail);
                   4217:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   4218:     my $seclist = &escape(join(':',@secs));
                   4219: 
                   4220:     &Reply($client, "$seclist\n", $userinput);
                   4221:     
                   4222: 
                   4223:     return 1;
                   4224: }
                   4225: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   4226: 
                   4227: #   Validate the owner of a new course section.  
                   4228: #
                   4229: # Formal Parameters:
                   4230: #   $cmd      - Command that got us dispatched.
                   4231: #   $tail     - the remainder of the command.  For us this consists of a
                   4232: #               colon separated string containing:
                   4233: #                  $inst    - Course Id from the institutions point of view.
                   4234: #                  $owner   - Proposed owner of the course.
                   4235: #                  $cdom    - Domain of the course (from the institutions
                   4236: #                             point of view?)..
                   4237: #   $client   - Socket open on the client.
                   4238: #
                   4239: # Returns:
                   4240: #   1        - Processing should continue.
                   4241: #
                   4242: sub validate_course_owner_handler {
                   4243:     my ($cmd, $tail, $client)  = @_;
                   4244:     my $userinput = "$cmd:$tail";
                   4245:     my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
                   4246: 
                   4247:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
                   4248:     &Reply($client, "$outcome\n", $userinput);
                   4249: 
                   4250: 
                   4251: 
                   4252:     return 1;
                   4253: }
                   4254: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 4255: 
1.248     foxr     4256: #
                   4257: #   Validate a course section in the official schedule of classes
                   4258: #   from the institutions point of view (part of autoenrollment).
                   4259: #
                   4260: # Formal Parameters:
                   4261: #   $cmd          - The command request that got us dispatched.
                   4262: #   $tail         - The tail of the command.  In this case,
                   4263: #                   this is a colon separated set of words that will be split
                   4264: #                   into:
                   4265: #                        $inst_course_id - The course/section id from the
                   4266: #                                          institutions point of view.
                   4267: #                        $cdom           - The domain from the institutions
                   4268: #                                          point of view.
                   4269: #   $client       - Socket open on the client.
                   4270: # Returns:
                   4271: #    1           - Indicating processing should continue.
                   4272: #
                   4273: sub validate_course_section_handler {
                   4274:     my ($cmd, $tail, $client) = @_;
                   4275:     my $userinput = "$cmd:$tail";
                   4276:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   4277: 
                   4278:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
                   4279:     &Reply($client, "$outcome\n", $userinput);
                   4280: 
                   4281: 
                   4282:     return 1;
                   4283: }
                   4284: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   4285: 
                   4286: #
                   4287: #   Create a password for a new auto-enrollment user.
                   4288: #   I think/guess, this password allows access to the institutions 
                   4289: #   AIS class list server/services.  Stuart can correct this comment
                   4290: #   when he finds out how wrong I am.
                   4291: #
                   4292: # Formal Parameters:
                   4293: #    $cmd     - The command request that got us dispatched.
                   4294: #    $tail    - The tail of the command.   In this case this is a colon separated
                   4295: #               set of words that will be split into:
                   4296: #               $authparam - An authentication parameter (username??).
                   4297: #               $cdom      - The domain of the course from the institution's
                   4298: #                            point of view.
                   4299: #    $client  - The socket open on the client.
                   4300: # Returns:
                   4301: #    1 - continue processing.
                   4302: #
                   4303: sub create_auto_enroll_password_handler {
                   4304:     my ($cmd, $tail, $client) = @_;
                   4305:     my $userinput = "$cmd:$tail";
                   4306: 
                   4307:     my ($authparam, $cdom) = split(/:/, $userinput);
                   4308: 
                   4309:     my ($create_passwd,$authchk);
                   4310:     ($authparam,
                   4311:      $create_passwd,
                   4312:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   4313: 
                   4314:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   4315: 	   $userinput);
                   4316: 
                   4317: 
                   4318:     return 1;
                   4319: }
                   4320: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   4321: 		  0, 1, 0);
                   4322: 
                   4323: #   Retrieve and remove temporary files created by/during autoenrollment.
                   4324: #
                   4325: # Formal Parameters:
                   4326: #    $cmd      - The command that got us dispatched.
                   4327: #    $tail     - The tail of the command.  In our case this is a colon 
                   4328: #                separated list that will be split into:
                   4329: #                $filename - The name of the file to remove.
                   4330: #                            The filename is given as a path relative to
                   4331: #                            the LonCAPA temp file directory.
                   4332: #    $client   - Socket open on the client.
                   4333: #
                   4334: # Returns:
                   4335: #   1     - Continue processing.
                   4336: sub retrieve_auto_file_handler {
                   4337:     my ($cmd, $tail, $client)    = @_;
                   4338:     my $userinput                = "cmd:$tail";
                   4339: 
                   4340:     my ($filename)   = split(/:/, $tail);
                   4341: 
                   4342:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
                   4343:     if ( (-e $source) && ($filename ne '') ) {
                   4344: 	my $reply = '';
                   4345: 	if (open(my $fh,$source)) {
                   4346: 	    while (<$fh>) {
                   4347: 		chomp($_);
                   4348: 		$_ =~ s/^\s+//g;
                   4349: 		$_ =~ s/\s+$//g;
                   4350: 		$reply .= $_;
                   4351: 	    }
                   4352: 	    close($fh);
                   4353: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   4354: 
                   4355: #   Does this have to be uncommented??!?  (RF).
                   4356: #
                   4357: #                                unlink($source);
                   4358: 	} else {
                   4359: 	    &Failure($client, "error\n", $userinput);
                   4360: 	}
                   4361:     } else {
                   4362: 	&Failure($client, "error\n", $userinput);
                   4363:     }
                   4364:     
                   4365: 
                   4366:     return 1;
                   4367: }
                   4368: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   4369: 
                   4370: #
                   4371: #   Read and retrieve institutional code format (for support form).
                   4372: # Formal Parameters:
                   4373: #    $cmd        - Command that dispatched us.
                   4374: #    $tail       - Tail of the command.  In this case it conatins 
                   4375: #                  the course domain and the coursename.
                   4376: #    $client     - Socket open on the client.
                   4377: # Returns:
                   4378: #    1     - Continue processing.
                   4379: #
                   4380: sub get_institutional_code_format_handler {
                   4381:     my ($cmd, $tail, $client)   = @_;
                   4382:     my $userinput               = "$cmd:$tail";
                   4383: 
                   4384:     my $reply;
                   4385:     my($cdom,$course) = split(/:/,$tail);
                   4386:     my @pairs = split/\&/,$course;
                   4387:     my %instcodes = ();
                   4388:     my %codes = ();
                   4389:     my @codetitles = ();
                   4390:     my %cat_titles = ();
                   4391:     my %cat_order = ();
                   4392:     foreach (@pairs) {
                   4393: 	my ($key,$value) = split/=/,$_;
                   4394: 	$instcodes{&unescape($key)} = &unescape($value);
                   4395:     }
                   4396:     my $formatreply = &localenroll::instcode_format($cdom,
                   4397: 						    \%instcodes,
                   4398: 						    \%codes,
                   4399: 						    \@codetitles,
                   4400: 						    \%cat_titles,
                   4401: 						    \%cat_order);
                   4402:     if ($formatreply eq 'ok') {
                   4403: 	my $codes_str = &hash2str(%codes);
                   4404: 	my $codetitles_str = &array2str(@codetitles);
                   4405: 	my $cat_titles_str = &hash2str(%cat_titles);
                   4406: 	my $cat_order_str = &hash2str(%cat_order);
                   4407: 	&Reply($client,
                   4408: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   4409: 	       .$cat_order_str."\n",
                   4410: 	       $userinput);
                   4411:     } else {
                   4412: 	# this else branch added by RF since if not ok, lonc will
                   4413: 	# hang waiting on reply until timeout.
                   4414: 	#
                   4415: 	&Reply($client, "format_error\n", $userinput);
                   4416:     }
                   4417:     
                   4418:     return 1;
                   4419: }
1.265     albertel 4420: &register_handler("autoinstcodeformat",
                   4421: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     4422: 
1.317     raeburn  4423: # Get domain specific conditions for import of student photographs to a course
                   4424: #
                   4425: # Retrieves information from photo_permission subroutine in localenroll.
                   4426: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   4427: # required to accept conditions of use (yes/no).
                   4428: #
                   4429: #    
                   4430: sub photo_permission_handler {
                   4431:     my ($cmd, $tail, $client)   = @_;
                   4432:     my $userinput               = "$cmd:$tail";
                   4433:     my $cdom = $tail;
                   4434:     my ($perm_reqd,$conditions);
1.320     albertel 4435:     my $outcome;
                   4436:     eval {
                   4437: 	local($SIG{__DIE__})='DEFAULT';
                   4438: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   4439: 						  \$conditions);
                   4440:     };
                   4441:     if (!$@) {
                   4442: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   4443: 	       $userinput);
                   4444:     } else {
                   4445: 	&Failure($client,"unknown_cmd\n",$userinput);
                   4446:     }
                   4447:     return 1;
1.317     raeburn  4448: }
                   4449: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   4450: 
                   4451: #
                   4452: # Checks if student photo is available for a user in the domain, in the user's
                   4453: # directory (in /userfiles/internal/studentphoto.jpg).
                   4454: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   4455: # the student's photo.   
                   4456: 
                   4457: sub photo_check_handler {
                   4458:     my ($cmd, $tail, $client)   = @_;
                   4459:     my $userinput               = "$cmd:$tail";
                   4460:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   4461:     $udom = &unescape($udom);
                   4462:     $uname = &unescape($uname);
                   4463:     $pid = &unescape($pid);
                   4464:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   4465:     if (!-e $path) {
                   4466:         &mkpath($path);
                   4467:     }
                   4468:     my $response;
                   4469:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   4470:     $result .= ':'.$response;
                   4471:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 4472:     return 1;
1.317     raeburn  4473: }
                   4474: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   4475: 
                   4476: #
                   4477: # Retrieve information from localenroll about whether to provide a button     
                   4478: # for users who have enbled import of student photos to initiate an 
                   4479: # update of photo files for registered students. Also include 
                   4480: # comment to display alongside button.  
                   4481: 
                   4482: sub photo_choice_handler {
                   4483:     my ($cmd, $tail, $client) = @_;
                   4484:     my $userinput             = "$cmd:$tail";
                   4485:     my $cdom                  = &unescape($tail);
1.320     albertel 4486:     my ($update,$comment);
                   4487:     eval {
                   4488: 	local($SIG{__DIE__})='DEFAULT';
                   4489: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   4490:     };
                   4491:     if (!$@) {
                   4492: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   4493:     } else {
                   4494: 	&Failure($client,"unknown_cmd\n",$userinput);
                   4495:     }
                   4496:     return 1;
1.317     raeburn  4497: }
                   4498: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   4499: 
1.265     albertel 4500: #
                   4501: # Gets a student's photo to exist (in the correct image type) in the user's 
                   4502: # directory.
                   4503: # Formal Parameters:
                   4504: #    $cmd     - The command request that got us dispatched.
                   4505: #    $tail    - A colon separated set of words that will be split into:
                   4506: #               $domain - student's domain
                   4507: #               $uname  - student username
                   4508: #               $type   - image type desired
                   4509: #    $client  - The socket open on the client.
                   4510: # Returns:
                   4511: #    1 - continue processing.
1.317     raeburn  4512: 
1.265     albertel 4513: sub student_photo_handler {
                   4514:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  4515:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 4516: 
1.317     raeburn  4517:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   4518:     my $filename = 'studentphoto.'.$ext;
                   4519:     if ($type eq 'thumbnail') {
                   4520:         $filename = 'studentphoto_tn.'.$ext;
                   4521:     }
                   4522:     if (-e $path.$filename) {
1.265     albertel 4523: 	&Reply($client,"ok\n","$cmd:$tail");
                   4524: 	return 1;
                   4525:     }
                   4526:     &mkpath($path);
1.317     raeburn  4527:     my $file;
                   4528:     if ($type eq 'thumbnail') {
1.320     albertel 4529: 	eval {
                   4530: 	    local($SIG{__DIE__})='DEFAULT';
                   4531: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   4532: 	};
1.317     raeburn  4533:     } else {
                   4534:         $file=&localstudentphoto::fetch($domain,$uname);
                   4535:     }
1.265     albertel 4536:     if (!$file) {
                   4537: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   4538: 	return 1;
                   4539:     }
1.317     raeburn  4540:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   4541:     if (-e $path.$filename) {
1.265     albertel 4542: 	&Reply($client,"ok\n","$cmd:$tail");
                   4543: 	return 1;
                   4544:     }
                   4545:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   4546:     return 1;
                   4547: }
                   4548: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     4549: 
1.264     albertel 4550: # mkpath makes all directories for a file, expects an absolute path with a
                   4551: # file or a trailing / if just a dir is passed
                   4552: # returns 1 on success 0 on failure
                   4553: sub mkpath {
                   4554:     my ($file)=@_;
                   4555:     my @parts=split(/\//,$file,-1);
                   4556:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   4557:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 4558: 	$now.='/'.$parts[$i]; 
1.264     albertel 4559: 	if (!-e $now) {
                   4560: 	    if  (!mkdir($now,0770)) { return 0; }
                   4561: 	}
                   4562:     }
                   4563:     return 1;
                   4564: }
                   4565: 
1.207     foxr     4566: #---------------------------------------------------------------
                   4567: #
                   4568: #   Getting, decoding and dispatching requests:
                   4569: #
                   4570: #
                   4571: #   Get a Request:
                   4572: #   Gets a Request message from the client.  The transaction
                   4573: #   is defined as a 'line' of text.  We remove the new line
                   4574: #   from the text line.  
1.226     foxr     4575: #
1.211     albertel 4576: sub get_request {
1.207     foxr     4577:     my $input = <$client>;
                   4578:     chomp($input);
1.226     foxr     4579: 
1.234     foxr     4580:     &Debug("get_request: Request = $input\n");
1.207     foxr     4581: 
                   4582:     &status('Processing '.$clientname.':'.$input);
                   4583: 
                   4584:     return $input;
                   4585: }
1.212     foxr     4586: #---------------------------------------------------------------
                   4587: #
                   4588: #  Process a request.  This sub should shrink as each action
                   4589: #  gets farmed out into a separat sub that is registered 
                   4590: #  with the dispatch hash.  
                   4591: #
                   4592: # Parameters:
                   4593: #    user_input   - The request received from the client (lonc).
                   4594: # Returns:
                   4595: #    true to keep processing, false if caller should exit.
                   4596: #
                   4597: sub process_request {
                   4598:     my ($userinput) = @_;      # Easier for now to break style than to
                   4599:                                 # fix all the userinput -> user_input.
                   4600:     my $wasenc    = 0;		# True if request was encrypted.
                   4601: # ------------------------------------------------------------ See if encrypted
1.322     albertel 4602:     # for command
                   4603:     # sethost:<server>
                   4604:     # <command>:<args>
                   4605:     #   we just send it to the processor
                   4606:     # for
                   4607:     # sethost:<server>:<command>:<args>
                   4608:     #  we do the implict set host and then do the command
                   4609:     if ($userinput =~ /^sethost:/) {
                   4610: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   4611: 	if (defined($userinput)) {
                   4612: 	    &sethost("$cmd:$newid");
                   4613: 	} else {
                   4614: 	    $userinput = "$cmd:$newid";
                   4615: 	}
                   4616:     }
                   4617: 
1.212     foxr     4618:     if ($userinput =~ /^enc/) {
                   4619: 	$userinput = decipher($userinput);
                   4620: 	$wasenc=1;
                   4621: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     4622: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     4623: 	    return 0;
                   4624: 	}
                   4625:     }
                   4626:     Debug("process_request: $userinput\n");
                   4627:     
1.213     foxr     4628:     #  
                   4629:     #   The 'correct way' to add a command to lond is now to
                   4630:     #   write a sub to execute it and Add it to the command dispatch
                   4631:     #   hash via a call to register_handler..  The comments to that
                   4632:     #   sub should give you enough to go on to show how to do this
                   4633:     #   along with the examples that are building up as this code
                   4634:     #   is getting refactored.   Until all branches of the
                   4635:     #   if/elseif monster below have been factored out into
                   4636:     #   separate procesor subs, if the dispatch hash is missing
                   4637:     #   the command keyword, we will fall through to the remainder
                   4638:     #   of the if/else chain below in order to keep this thing in 
                   4639:     #   working order throughout the transmogrification.
                   4640: 
                   4641:     my ($command, $tail) = split(/:/, $userinput, 2);
                   4642:     chomp($command);
                   4643:     chomp($tail);
                   4644:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     4645:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   4646:     if(!$tail) {
                   4647: 	$tail ="";		# defined but blank.
                   4648:     }
1.213     foxr     4649: 
                   4650:     &Debug("Command received: $command, encoded = $wasenc");
                   4651: 
                   4652:     if(defined $Dispatcher{$command}) {
                   4653: 
                   4654: 	my $dispatch_info = $Dispatcher{$command};
                   4655: 	my $handler       = $$dispatch_info[0];
                   4656: 	my $need_encode   = $$dispatch_info[1];
                   4657: 	my $client_types  = $$dispatch_info[2];
                   4658: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   4659: 	      ."ClientType $client_types");
                   4660:       
                   4661: 	#  Validate the request:
                   4662:       
                   4663: 	my $ok = 1;
                   4664: 	my $requesterprivs = 0;
                   4665: 	if(&isClient()) {
                   4666: 	    $requesterprivs |= $CLIENT_OK;
                   4667: 	}
                   4668: 	if(&isManager()) {
                   4669: 	    $requesterprivs |= $MANAGER_OK;
                   4670: 	}
                   4671: 	if($need_encode && (!$wasenc)) {
                   4672: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   4673: 	    $ok = 0;
                   4674: 	}
                   4675: 	if(($client_types & $requesterprivs) == 0) {
                   4676: 	    Debug("Client not privileged to do this operation");
                   4677: 	    $ok = 0;
                   4678: 	}
                   4679: 
                   4680: 	if($ok) {
                   4681: 	    Debug("Dispatching to handler $command $tail");
                   4682: 	    my $keep_going = &$handler($command, $tail, $client);
                   4683: 	    return $keep_going;
                   4684: 	} else {
                   4685: 	    Debug("Refusing to dispatch because client did not match requirements");
                   4686: 	    Failure($client, "refused\n", $userinput);
                   4687: 	    return 1;
                   4688: 	}
                   4689: 
                   4690:     }    
                   4691: 
1.262     foxr     4692:     print $client "unknown_cmd\n";
1.212     foxr     4693: # -------------------------------------------------------------------- complete
                   4694:     Debug("process_request - returning 1");
                   4695:     return 1;
                   4696: }
1.207     foxr     4697: #
                   4698: #   Decipher encoded traffic
                   4699: #  Parameters:
                   4700: #     input      - Encoded data.
                   4701: #  Returns:
                   4702: #     Decoded data or undef if encryption key was not yet negotiated.
                   4703: #  Implicit input:
                   4704: #     cipher  - This global holds the negotiated encryption key.
                   4705: #
1.211     albertel 4706: sub decipher {
1.207     foxr     4707:     my ($input)  = @_;
                   4708:     my $output = '';
1.212     foxr     4709:     
                   4710:     
1.207     foxr     4711:     if($cipher) {
                   4712: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   4713: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   4714: 	    $output .= 
                   4715: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   4716: 	}
                   4717: 	return substr($output, 0, $enclength);
                   4718:     } else {
                   4719: 	return undef;
                   4720:     }
                   4721: }
                   4722: 
                   4723: #
                   4724: #   Register a command processor.  This function is invoked to register a sub
                   4725: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   4726: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   4727: #   as well:
                   4728: #    - Is the keyword recognized.
                   4729: #    - Is the proper client type attempting the request.
                   4730: #    - Is the request encrypted if it has to be.
                   4731: #   Parameters:
                   4732: #    $request_name         - Name of the request being registered.
                   4733: #                           This is the command request that will match
                   4734: #                           against the hash keywords to lookup the information
                   4735: #                           associated with the dispatch information.
                   4736: #    $procedure           - Reference to a sub to call to process the request.
                   4737: #                           All subs get called as follows:
                   4738: #                             Procedure($cmd, $tail, $replyfd, $key)
                   4739: #                             $cmd    - the actual keyword that invoked us.
                   4740: #                             $tail   - the tail of the request that invoked us.
                   4741: #                             $replyfd- File descriptor connected to the client
                   4742: #    $must_encode          - True if the request must be encoded to be good.
                   4743: #    $client_ok            - True if it's ok for a client to request this.
                   4744: #    $manager_ok           - True if it's ok for a manager to request this.
                   4745: # Side effects:
                   4746: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   4747: #      - On failure, the program will die as it's a bad internal bug to try to 
                   4748: #        register a duplicate command handler.
                   4749: #
1.211     albertel 4750: sub register_handler {
1.212     foxr     4751:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     4752: 
                   4753:     #  Don't allow duplication#
                   4754:    
                   4755:     if (defined $Dispatcher{$request_name}) {
                   4756: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   4757:     }
                   4758:     #   Build the client type mask:
                   4759:     
                   4760:     my $client_type_mask = 0;
                   4761:     if($client_ok) {
                   4762: 	$client_type_mask  |= $CLIENT_OK;
                   4763:     }
                   4764:     if($manager_ok) {
                   4765: 	$client_type_mask  |= $MANAGER_OK;
                   4766:     }
                   4767:    
                   4768:     #  Enter the hash:
                   4769:       
                   4770:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   4771:    
                   4772:     $Dispatcher{$request_name} = \@entry;
                   4773:    
                   4774: }
                   4775: 
                   4776: 
                   4777: #------------------------------------------------------------------
                   4778: 
                   4779: 
                   4780: 
                   4781: 
1.141     foxr     4782: #
1.96      foxr     4783: #  Convert an error return code from lcpasswd to a string value.
                   4784: #
                   4785: sub lcpasswdstrerror {
                   4786:     my $ErrorCode = shift;
1.97      foxr     4787:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     4788: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   4789:     } else {
1.98      foxr     4790: 	return $passwderrors[$ErrorCode];
1.96      foxr     4791:     }
                   4792: }
                   4793: 
1.97      foxr     4794: #
                   4795: # Convert an error return code from lcuseradd to a string value:
                   4796: #
                   4797: sub lcuseraddstrerror {
                   4798:     my $ErrorCode = shift;
                   4799:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
                   4800: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
                   4801:     } else {
1.98      foxr     4802: 	return $adderrors[$ErrorCode];
1.97      foxr     4803:     }
                   4804: }
                   4805: 
1.23      harris41 4806: # grabs exception and records it to log before exiting
                   4807: sub catchexception {
1.27      albertel 4808:     my ($error)=@_;
1.25      www      4809:     $SIG{'QUIT'}='DEFAULT';
                   4810:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 4811:     &status("Catching exception");
1.190     albertel 4812:     &logthis("<font color='red'>CRITICAL: "
1.134     albertel 4813:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27      albertel 4814:      ."a crash with this error msg->[$error]</font>");
1.57      www      4815:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 4816:     if ($client) { print $client "error: $error\n"; }
1.59      www      4817:     $server->close();
1.27      albertel 4818:     die($error);
1.23      harris41 4819: }
1.63      www      4820: sub timeout {
1.165     albertel 4821:     &status("Handling Timeout");
1.190     albertel 4822:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      4823:     &catchexception('Timeout');
                   4824: }
1.22      harris41 4825: # -------------------------------- Set signal handlers to record abnormal exits
                   4826: 
1.226     foxr     4827: 
1.22      harris41 4828: $SIG{'QUIT'}=\&catchexception;
                   4829: $SIG{__DIE__}=\&catchexception;
                   4830: 
1.81      matthew  4831: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 4832: &status("Read loncapa.conf and loncapa_apache.conf");
                   4833: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     4834: %perlvar=%{$perlvarref};
1.80      harris41 4835: undef $perlvarref;
1.19      www      4836: 
1.35      harris41 4837: # ----------------------------- Make sure this process is running from user=www
                   4838: my $wwwid=getpwnam('www');
                   4839: if ($wwwid!=$<) {
1.134     albertel 4840:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4841:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 4842:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 4843:  mailto $emailto -s '$subj' > /dev/null");
                   4844:    exit 1;
                   4845: }
                   4846: 
1.19      www      4847: # --------------------------------------------- Check if other instance running
                   4848: 
                   4849: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   4850: 
                   4851: if (-e $pidfile) {
                   4852:    my $lfh=IO::File->new("$pidfile");
                   4853:    my $pide=<$lfh>;
                   4854:    chomp($pide);
1.29      harris41 4855:    if (kill 0 => $pide) { die "already running"; }
1.19      www      4856: }
1.1       albertel 4857: 
                   4858: # ------------------------------------------------------------- Read hosts file
                   4859: 
                   4860: 
                   4861: 
                   4862: # establish SERVER socket, bind and listen.
                   4863: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   4864:                                 Type      => SOCK_STREAM,
                   4865:                                 Proto     => 'tcp',
                   4866:                                 Reuse     => 1,
                   4867:                                 Listen    => 10 )
1.29      harris41 4868:   or die "making socket: $@\n";
1.1       albertel 4869: 
                   4870: # --------------------------------------------------------- Do global variables
                   4871: 
                   4872: # global variables
                   4873: 
1.134     albertel 4874: my %children               = ();       # keys are current child process IDs
1.1       albertel 4875: 
                   4876: sub REAPER {                        # takes care of dead children
                   4877:     $SIG{CHLD} = \&REAPER;
1.165     albertel 4878:     &status("Handling child death");
1.178     foxr     4879:     my $pid;
                   4880:     do {
                   4881: 	$pid = waitpid(-1,&WNOHANG());
                   4882: 	if (defined($children{$pid})) {
                   4883: 	    &logthis("Child $pid died");
                   4884: 	    delete($children{$pid});
1.183     albertel 4885: 	} elsif ($pid > 0) {
1.178     foxr     4886: 	    &logthis("Unknown Child $pid died");
                   4887: 	}
                   4888:     } while ( $pid > 0 );
                   4889:     foreach my $child (keys(%children)) {
                   4890: 	$pid = waitpid($child,&WNOHANG());
                   4891: 	if ($pid > 0) {
                   4892: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   4893: 	    delete($children{$pid});
                   4894: 	}
1.176     albertel 4895:     }
1.165     albertel 4896:     &status("Finished Handling child death");
1.1       albertel 4897: }
                   4898: 
                   4899: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 4900:     &status("Killing children (INT)");
1.1       albertel 4901:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   4902:     kill 'INT' => keys %children;
1.59      www      4903:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 4904:     my $execdir=$perlvar{'lonDaemons'};
                   4905:     unlink("$execdir/logs/lond.pid");
1.190     albertel 4906:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 4907:     &status("Done killing children");
1.1       albertel 4908:     exit;                           # clean up with dignity
                   4909: }
                   4910: 
                   4911: sub HUPSMAN {                      # signal handler for SIGHUP
                   4912:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 4913:     &status("Killing children for restart (HUP)");
1.1       albertel 4914:     kill 'INT' => keys %children;
1.59      www      4915:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 4916:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 4917:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 4918:     unlink("$execdir/logs/lond.pid");
1.165     albertel 4919:     &status("Restarting self (HUP)");
1.1       albertel 4920:     exec("$execdir/lond");         # here we go again
                   4921: }
                   4922: 
1.144     foxr     4923: #
1.148     foxr     4924: #    Kill off hashes that describe the host table prior to re-reading it.
                   4925: #    Hashes affected are:
1.200     matthew  4926: #       %hostid, %hostdom %hostip %hostdns.
1.148     foxr     4927: #
                   4928: sub KillHostHashes {
                   4929:     foreach my $key (keys %hostid) {
                   4930: 	delete $hostid{$key};
                   4931:     }
                   4932:     foreach my $key (keys %hostdom) {
                   4933: 	delete $hostdom{$key};
                   4934:     }
                   4935:     foreach my $key (keys %hostip) {
                   4936: 	delete $hostip{$key};
                   4937:     }
1.200     matthew  4938:     foreach my $key (keys %hostdns) {
                   4939: 	delete $hostdns{$key};
                   4940:     }
1.148     foxr     4941: }
                   4942: #
                   4943: #   Read in the host table from file and distribute it into the various hashes:
                   4944: #
                   4945: #    - %hostid  -  Indexed by IP, the loncapa hostname.
                   4946: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
                   4947: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
                   4948: sub ReadHostTable {
                   4949: 
                   4950:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200     matthew  4951:     my $myloncapaname = $perlvar{'lonHostID'};
                   4952:     Debug("My loncapa name is : $myloncapaname");
1.296     albertel 4953:     my %name_to_ip;
1.148     foxr     4954:     while (my $configline=<CONFIG>) {
1.277     albertel 4955: 	if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
                   4956: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   4957: 	    $name=~s/\s//g;
1.296     albertel 4958: 	    my $ip;
                   4959: 	    if (!exists($name_to_ip{$name})) {
                   4960: 		$ip = gethostbyname($name);
                   4961: 		if (!$ip || length($ip) ne 4) {
                   4962: 		    &logthis("Skipping host $id name $name no IP found\n");
                   4963: 		    next;
                   4964: 		}
                   4965: 		$ip=inet_ntoa($ip);
                   4966: 		$name_to_ip{$name} = $ip;
                   4967: 	    } else {
                   4968: 		$ip = $name_to_ip{$name};
1.277     albertel 4969: 	    }
1.200     matthew  4970: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
                   4971: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
1.307     albertel 4972: 	    $hostname{$id}=$name;     # LonCAPA name -> DNS name
1.277     albertel 4973: 	    $hostip{$id}=$ip;         # IP address of host.
1.200     matthew  4974: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
                   4975: 
                   4976: 	    if ($id eq $perlvar{'lonHostID'}) { 
                   4977: 		Debug("Found me in the host table: $name");
                   4978: 		$thisserver=$name; 
                   4979: 	    }
1.178     foxr     4980: 	}
1.148     foxr     4981:     }
                   4982:     close(CONFIG);
                   4983: }
                   4984: #
                   4985: #  Reload the Apache daemon's state.
1.150     foxr     4986: #  This is done by invoking /home/httpd/perl/apachereload
                   4987: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     4988: #
                   4989: sub ReloadApache {
1.150     foxr     4990:     my $execdir = $perlvar{'lonDaemons'};
                   4991:     my $script  = $execdir."/apachereload";
                   4992:     system($script);
1.148     foxr     4993: }
                   4994: 
                   4995: #
1.144     foxr     4996: #   Called in response to a USR2 signal.
                   4997: #   - Reread hosts.tab
                   4998: #   - All children connected to hosts that were removed from hosts.tab
                   4999: #     are killed via SIGINT
                   5000: #   - All children connected to previously existing hosts are sent SIGUSR1
                   5001: #   - Our internal hosts hash is updated to reflect the new contents of
                   5002: #     hosts.tab causing connections from hosts added to hosts.tab to
                   5003: #     now be honored.
                   5004: #
                   5005: sub UpdateHosts {
1.165     albertel 5006:     &status("Reload hosts.tab");
1.147     foxr     5007:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     5008:     #
                   5009:     #  The %children hash has the set of IP's we currently have children
                   5010:     #  on.  These need to be matched against records in the hosts.tab
                   5011:     #  Any ip's no longer in the table get killed off they correspond to
                   5012:     #  either dropped or changed hosts.  Note that the re-read of the table
                   5013:     #  will take care of new and changed hosts as connections come into being.
                   5014: 
                   5015: 
                   5016:     KillHostHashes;
                   5017:     ReadHostTable;
                   5018: 
                   5019:     foreach my $child (keys %children) {
                   5020: 	my $childip = $children{$child};
                   5021: 	if(!$hostid{$childip}) {
1.149     foxr     5022: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   5023: 		    ." $child for ip $childip </font>");
1.148     foxr     5024: 	    kill('INT', $child);
1.149     foxr     5025: 	} else {
                   5026: 	    logthis('<font color="green"> keeping child for ip '
                   5027: 		    ." $childip (pid=$child) </font>");
1.148     foxr     5028: 	}
                   5029:     }
                   5030:     ReloadApache;
1.165     albertel 5031:     &status("Finished reloading hosts.tab");
1.144     foxr     5032: }
                   5033: 
1.148     foxr     5034: 
1.57      www      5035: sub checkchildren {
1.165     albertel 5036:     &status("Checking on the children (sending signals)");
1.57      www      5037:     &initnewstatus();
                   5038:     &logstatus();
                   5039:     &logthis('Going to check on the children');
1.134     albertel 5040:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 5041:     foreach (sort keys %children) {
1.221     albertel 5042: 	#sleep 1;
1.57      www      5043:         unless (kill 'USR1' => $_) {
                   5044: 	    &logthis ('Child '.$_.' is dead');
                   5045:             &logstatus($$.' is dead');
1.221     albertel 5046: 	    delete($children{$_});
1.57      www      5047:         } 
1.61      harris41 5048:     }
1.63      www      5049:     sleep 5;
1.212     foxr     5050:     $SIG{ALRM} = sub { Debug("timeout"); 
                   5051: 		       die "timeout";  };
1.113     albertel 5052:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 5053:     &status("Checking on the children (waiting for reports)");
1.63      www      5054:     foreach (sort keys %children) {
                   5055:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 5056:           eval {
                   5057:             alarm(300);
1.63      www      5058: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 5059: 	    kill 9 => $_;
1.131     albertel 5060: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   5061: 	    #$subj="LON: $currenthostid killed lond process $_";
                   5062: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   5063: 	    #$execdir=$perlvar{'lonDaemons'};
                   5064: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 5065: 	    delete($children{$_});
1.113     albertel 5066: 	    alarm(0);
                   5067: 	  }
1.63      www      5068:         }
                   5069:     }
1.113     albertel 5070:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 5071:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 5072:     &status("Finished checking children");
1.221     albertel 5073:     &logthis('Finished Checking children');
1.57      www      5074: }
                   5075: 
1.1       albertel 5076: # --------------------------------------------------------------------- Logging
                   5077: 
                   5078: sub logthis {
                   5079:     my $message=shift;
                   5080:     my $execdir=$perlvar{'lonDaemons'};
                   5081:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   5082:     my $now=time;
                   5083:     my $local=localtime($now);
1.58      www      5084:     $lastlog=$local.': '.$message;
1.1       albertel 5085:     print $fh "$local ($$): $message\n";
                   5086: }
                   5087: 
1.77      foxr     5088: # ------------------------- Conditional log if $DEBUG true.
                   5089: sub Debug {
                   5090:     my $message = shift;
                   5091:     if($DEBUG) {
                   5092: 	&logthis($message);
                   5093:     }
                   5094: }
1.161     foxr     5095: 
                   5096: #
                   5097: #   Sub to do replies to client.. this gives a hook for some
                   5098: #   debug tracing too:
                   5099: #  Parameters:
                   5100: #     fd      - File open on client.
                   5101: #     reply   - Text to send to client.
                   5102: #     request - Original request from client.
                   5103: #
                   5104: sub Reply {
1.192     foxr     5105:     my ($fd, $reply, $request) = @_;
1.161     foxr     5106:     print $fd $reply;
                   5107:     Debug("Request was $request  Reply was $reply");
                   5108: 
1.212     foxr     5109:     $Transactions++;
                   5110: }
                   5111: 
                   5112: 
                   5113: #
                   5114: #    Sub to report a failure.
                   5115: #    This function:
                   5116: #     -   Increments the failure statistic counters.
                   5117: #     -   Invokes Reply to send the error message to the client.
                   5118: # Parameters:
                   5119: #    fd       - File descriptor open on the client
                   5120: #    reply    - Reply text to emit.
                   5121: #    request  - The original request message (used by Reply
                   5122: #               to debug if that's enabled.
                   5123: # Implicit outputs:
                   5124: #    $Failures- The number of failures is incremented.
                   5125: #    Reply (invoked here) sends a message to the 
                   5126: #    client:
                   5127: #
                   5128: sub Failure {
                   5129:     my $fd      = shift;
                   5130:     my $reply   = shift;
                   5131:     my $request = shift;
                   5132:    
                   5133:     $Failures++;
                   5134:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     5135: }
1.57      www      5136: # ------------------------------------------------------------------ Log status
                   5137: 
                   5138: sub logstatus {
1.178     foxr     5139:     &status("Doing logging");
                   5140:     my $docdir=$perlvar{'lonDocRoot'};
                   5141:     {
                   5142: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  5143:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     5144:         $fh->close();
                   5145:     }
1.221     albertel 5146:     &status("Finished $$.txt");
                   5147:     {
                   5148: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   5149: 	flock(LOG,LOCK_EX);
                   5150: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   5151: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 5152: 	flock(LOG,LOCK_UN);
1.221     albertel 5153: 	close(LOG);
                   5154:     }
1.178     foxr     5155:     &status("Finished logging");
1.57      www      5156: }
                   5157: 
                   5158: sub initnewstatus {
                   5159:     my $docdir=$perlvar{'lonDocRoot'};
                   5160:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
                   5161:     my $now=time;
                   5162:     my $local=localtime($now);
                   5163:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      5164:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 5165:     while (my $filename=readdir(DIR)) {
1.64      www      5166:         unlink("$docdir/lon-status/londchld/$filename");
                   5167:     }
                   5168:     closedir(DIR);
1.57      www      5169: }
                   5170: 
                   5171: # -------------------------------------------------------------- Status setting
                   5172: 
                   5173: sub status {
                   5174:     my $what=shift;
                   5175:     my $now=time;
                   5176:     my $local=localtime($now);
1.178     foxr     5177:     $status=$local.': '.$what;
                   5178:     $0='lond: '.$what.' '.$local;
1.57      www      5179: }
1.11      www      5180: 
1.1       albertel 5181: # ----------------------------------------------------------- Send USR1 to lonc
                   5182: 
                   5183: sub reconlonc {
                   5184:     my $peerfile=shift;
                   5185:     &logthis("Trying to reconnect for $peerfile");
                   5186:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                   5187:     if (my $fh=IO::File->new("$loncfile")) {
                   5188: 	my $loncpid=<$fh>;
                   5189:         chomp($loncpid);
                   5190:         if (kill 0 => $loncpid) {
                   5191: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                   5192:             kill USR1 => $loncpid;
                   5193:         } else {
1.9       www      5194: 	    &logthis(
1.190     albertel 5195:               "<font color='red'>CRITICAL: "
1.9       www      5196:              ."lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel 5197:         }
                   5198:     } else {
1.190     albertel 5199:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1       albertel 5200:     }
                   5201: }
                   5202: 
                   5203: # -------------------------------------------------- Non-critical communication
1.11      www      5204: 
1.1       albertel 5205: sub subreply {
                   5206:     my ($cmd,$server)=@_;
1.307     albertel 5207:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.1       albertel 5208:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   5209:                                       Type    => SOCK_STREAM,
                   5210:                                       Timeout => 10)
                   5211:        or return "con_lost";
1.307     albertel 5212:     print $sclient "sethost:$server:$cmd\n";
1.1       albertel 5213:     my $answer=<$sclient>;
                   5214:     chomp($answer);
                   5215:     if (!$answer) { $answer="con_lost"; }
                   5216:     return $answer;
                   5217: }
                   5218: 
                   5219: sub reply {
                   5220:   my ($cmd,$server)=@_;
                   5221:   my $answer;
1.115     albertel 5222:   if ($server ne $currenthostid) { 
1.1       albertel 5223:     $answer=subreply($cmd,$server);
                   5224:     if ($answer eq 'con_lost') {
                   5225: 	$answer=subreply("ping",$server);
                   5226:         if ($answer ne $server) {
1.115     albertel 5227: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
1.307     albertel 5228:            &reconlonc("$perlvar{'lonSockDir'}/".$hostname{$server});
1.1       albertel 5229:         }
                   5230:         $answer=subreply($cmd,$server);
                   5231:     }
                   5232:   } else {
                   5233:     $answer='self_reply';
                   5234:   } 
                   5235:   return $answer;
                   5236: }
                   5237: 
1.13      www      5238: # -------------------------------------------------------------- Talk to lonsql
                   5239: 
1.234     foxr     5240: sub sql_reply {
1.12      harris41 5241:     my ($cmd)=@_;
1.234     foxr     5242:     my $answer=&sub_sql_reply($cmd);
                   5243:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 5244:     return $answer;
                   5245: }
                   5246: 
1.234     foxr     5247: sub sub_sql_reply {
1.12      harris41 5248:     my ($cmd)=@_;
                   5249:     my $unixsock="mysqlsock";
                   5250:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   5251:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   5252:                                       Type    => SOCK_STREAM,
                   5253:                                       Timeout => 10)
                   5254:        or return "con_lost";
1.319     www      5255:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 5256:     my $answer=<$sclient>;
                   5257:     chomp($answer);
                   5258:     if (!$answer) { $answer="con_lost"; }
                   5259:     return $answer;
                   5260: }
                   5261: 
1.1       albertel 5262: # -------------------------------------------- Return path to profile directory
1.11      www      5263: 
1.1       albertel 5264: sub propath {
                   5265:     my ($udom,$uname)=@_;
                   5266:     $udom=~s/\W//g;
                   5267:     $uname=~s/\W//g;
1.16      www      5268:     my $subdir=$uname.'__';
1.1       albertel 5269:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5270:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   5271:     return $proname;
                   5272: } 
                   5273: 
                   5274: # --------------------------------------- Is this the home server of an author?
1.11      www      5275: 
1.1       albertel 5276: sub ishome {
                   5277:     my $author=shift;
                   5278:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   5279:     my ($udom,$uname)=split(/\//,$author);
                   5280:     my $proname=propath($udom,$uname);
                   5281:     if (-e $proname) {
                   5282: 	return 'owner';
                   5283:     } else {
                   5284:         return 'not_owner';
                   5285:     }
                   5286: }
                   5287: 
                   5288: # ======================================================= Continue main program
                   5289: # ---------------------------------------------------- Fork once and dissociate
                   5290: 
1.134     albertel 5291: my $fpid=fork;
1.1       albertel 5292: exit if $fpid;
1.29      harris41 5293: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 5294: 
1.29      harris41 5295: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 5296: 
                   5297: # ------------------------------------------------------- Write our PID on disk
                   5298: 
1.134     albertel 5299: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 5300: open (PIDSAVE,">$execdir/logs/lond.pid");
                   5301: print PIDSAVE "$$\n";
                   5302: close(PIDSAVE);
1.190     albertel 5303: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      5304: &status('Starting');
1.1       albertel 5305: 
1.106     foxr     5306: 
1.1       albertel 5307: 
                   5308: # ----------------------------------------------------- Install signal handlers
                   5309: 
1.57      www      5310: 
1.1       albertel 5311: $SIG{CHLD} = \&REAPER;
                   5312: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   5313: $SIG{HUP}  = \&HUPSMAN;
1.57      www      5314: $SIG{USR1} = \&checkchildren;
1.144     foxr     5315: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     5316: 
1.148     foxr     5317: #  Read the host hashes:
                   5318: 
                   5319: ReadHostTable;
1.106     foxr     5320: 
1.286     albertel 5321: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
                   5322: 
1.106     foxr     5323: # --------------------------------------------------------------
                   5324: #   Accept connections.  When a connection comes in, it is validated
                   5325: #   and if good, a child process is created to process transactions
                   5326: #   along the connection.
                   5327: 
1.1       albertel 5328: while (1) {
1.165     albertel 5329:     &status('Starting accept');
1.106     foxr     5330:     $client = $server->accept() or next;
1.165     albertel 5331:     &status('Accepted '.$client.' off to spawn');
1.106     foxr     5332:     make_new_child($client);
1.165     albertel 5333:     &status('Finished spawning');
1.1       albertel 5334: }
                   5335: 
1.212     foxr     5336: sub make_new_child {
                   5337:     my $pid;
                   5338: #    my $cipher;     # Now global
                   5339:     my $sigset;
1.178     foxr     5340: 
1.212     foxr     5341:     $client = shift;
                   5342:     &status('Starting new child '.$client);
                   5343:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   5344: 	     ")</font>");    
                   5345:     # block signal for fork
                   5346:     $sigset = POSIX::SigSet->new(SIGINT);
                   5347:     sigprocmask(SIG_BLOCK, $sigset)
                   5348:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     5349: 
1.212     foxr     5350:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     5351: 
1.212     foxr     5352:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   5353: 	                               # connection liveness.
1.178     foxr     5354: 
1.212     foxr     5355:     #
                   5356:     #  Figure out who we're talking to so we can record the peer in 
                   5357:     #  the pid hash.
                   5358:     #
                   5359:     my $caller = getpeername($client);
                   5360:     my ($port,$iaddr);
                   5361:     if (defined($caller) && length($caller) > 0) {
                   5362: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   5363:     } else {
                   5364: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   5365:     }
                   5366:     if (defined($iaddr)) {
                   5367: 	$clientip  = inet_ntoa($iaddr);
                   5368: 	Debug("Connected with $clientip");
                   5369:     } else {
                   5370: 	&logthis("Unable to determine clientip");
                   5371: 	$clientip='Unavailable';
                   5372:     }
                   5373:     
                   5374:     if ($pid) {
                   5375:         # Parent records the child's birth and returns.
                   5376:         sigprocmask(SIG_UNBLOCK, $sigset)
                   5377:             or die "Can't unblock SIGINT for fork: $!\n";
                   5378:         $children{$pid} = $clientip;
                   5379:         &status('Started child '.$pid);
                   5380:         return;
                   5381:     } else {
                   5382:         # Child can *not* return from this subroutine.
                   5383:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   5384:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   5385:                                 #don't get intercepted
                   5386:         $SIG{USR1}= \&logstatus;
                   5387:         $SIG{ALRM}= \&timeout;
                   5388:         $lastlog='Forked ';
                   5389:         $status='Forked';
1.178     foxr     5390: 
1.212     foxr     5391:         # unblock signals
                   5392:         sigprocmask(SIG_UNBLOCK, $sigset)
                   5393:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     5394: 
1.212     foxr     5395: #        my $tmpsnum=0;            # Now global
                   5396: #---------------------------------------------------- kerberos 5 initialization
                   5397:         &Authen::Krb5::init_context();
1.297     raeburn  5398: 	unless (($dist eq 'fedora4') || ($dist eq 'suse9.3')) {
1.286     albertel 5399: 	    &Authen::Krb5::init_ets();
                   5400: 	}
1.209     albertel 5401: 
1.212     foxr     5402: 	&status('Accepted connection');
                   5403: # =============================================================================
                   5404:             # do something with the connection
                   5405: # -----------------------------------------------------------------------------
                   5406: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     5407: 
1.212     foxr     5408: 	ReadManagerTable;	# May also be a manager!!
                   5409: 	
1.278     albertel 5410: 	my $outsideip=$clientip;
                   5411: 	if ($clientip eq '127.0.0.1') {
                   5412: 	    $outsideip=$hostip{$perlvar{'lonHostID'}};
                   5413: 	}
                   5414: 
                   5415: 	my $clientrec=($hostid{$outsideip}     ne undef);
                   5416: 	my $ismanager=($managers{$outsideip}    ne undef);
1.212     foxr     5417: 	$clientname  = "[unknonwn]";
                   5418: 	if($clientrec) {	# Establish client type.
                   5419: 	    $ConnectionType = "client";
1.278     albertel 5420: 	    $clientname = $hostid{$outsideip};
1.212     foxr     5421: 	    if($ismanager) {
                   5422: 		$ConnectionType = "both";
                   5423: 	    }
                   5424: 	} else {
                   5425: 	    $ConnectionType = "manager";
1.278     albertel 5426: 	    $clientname = $managers{$outsideip};
1.212     foxr     5427: 	}
                   5428: 	my $clientok;
1.178     foxr     5429: 
1.212     foxr     5430: 	if ($clientrec || $ismanager) {
                   5431: 	    &status("Waiting for init from $clientip $clientname");
                   5432: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   5433: 		     $clientip.
                   5434: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   5435: 	    &status("Connecting $clientip  ($clientname))"); 
                   5436: 	    my $remotereq=<$client>;
                   5437: 	    chomp($remotereq);
                   5438: 	    Debug("Got init: $remotereq");
                   5439: 	    my $inikeyword = split(/:/, $remotereq);
                   5440: 	    if ($remotereq =~ /^init/) {
                   5441: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   5442: 		#
                   5443: 		#  If the remote is attempting a local init... give that a try:
                   5444: 		#
                   5445: 		my ($i, $inittype) = split(/:/, $remotereq);
1.209     albertel 5446: 
1.212     foxr     5447: 		# If the connection type is ssl, but I didn't get my
                   5448: 		# certificate files yet, then I'll drop  back to 
                   5449: 		# insecure (if allowed).
                   5450: 		
                   5451: 		if($inittype eq "ssl") {
                   5452: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   5453: 		    my $kfile       = lonssl::KeyFile;
                   5454: 		    if((!$ca)   || 
                   5455: 		       (!$cert) || 
                   5456: 		       (!$kfile)) {
                   5457: 			$inittype = ""; # This forces insecure attempt.
                   5458: 			&logthis("<font color=\"blue\"> Certificates not "
                   5459: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     5460: 		    } else {	# SSL certificates are in place so
1.212     foxr     5461: 		    }		# Leave the inittype alone.
                   5462: 		}
                   5463: 
                   5464: 		if($inittype eq "local") {
                   5465: 		    my $key = LocalConnection($client, $remotereq);
                   5466: 		    if($key) {
                   5467: 			Debug("Got local key $key");
                   5468: 			$clientok     = 1;
                   5469: 			my $cipherkey = pack("H32", $key);
                   5470: 			$cipher       = new IDEA($cipherkey);
                   5471: 			print $client "ok:local\n";
                   5472: 			&logthis('<font color="green"'
                   5473: 				 . "Successful local authentication </font>");
                   5474: 			$keymode = "local"
1.178     foxr     5475: 		    } else {
1.212     foxr     5476: 			Debug("Failed to get local key");
                   5477: 			$clientok = 0;
                   5478: 			shutdown($client, 3);
                   5479: 			close $client;
1.178     foxr     5480: 		    }
1.212     foxr     5481: 		} elsif ($inittype eq "ssl") {
                   5482: 		    my $key = SSLConnection($client);
                   5483: 		    if ($key) {
                   5484: 			$clientok = 1;
                   5485: 			my $cipherkey = pack("H32", $key);
                   5486: 			$cipher       = new IDEA($cipherkey);
                   5487: 			&logthis('<font color="green">'
                   5488: 				 ."Successfull ssl authentication with $clientname </font>");
                   5489: 			$keymode = "ssl";
                   5490: 	     
1.178     foxr     5491: 		    } else {
1.212     foxr     5492: 			$clientok = 0;
                   5493: 			close $client;
1.178     foxr     5494: 		    }
1.212     foxr     5495: 	   
                   5496: 		} else {
                   5497: 		    my $ok = InsecureConnection($client);
                   5498: 		    if($ok) {
                   5499: 			$clientok = 1;
                   5500: 			&logthis('<font color="green">'
                   5501: 				 ."Successful insecure authentication with $clientname </font>");
                   5502: 			print $client "ok\n";
                   5503: 			$keymode = "insecure";
1.178     foxr     5504: 		    } else {
1.212     foxr     5505: 			&logthis('<font color="yellow">'
                   5506: 				  ."Attempted insecure connection disallowed </font>");
                   5507: 			close $client;
                   5508: 			$clientok = 0;
1.178     foxr     5509: 			
                   5510: 		    }
                   5511: 		}
1.212     foxr     5512: 	    } else {
                   5513: 		&logthis(
                   5514: 			 "<font color='blue'>WARNING: "
                   5515: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   5516: 		&status('No init '.$clientip);
                   5517: 	    }
                   5518: 	    
                   5519: 	} else {
                   5520: 	    &logthis(
                   5521: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   5522: 	    &status('Hung up on '.$clientip);
                   5523: 	}
                   5524:  
                   5525: 	if ($clientok) {
                   5526: # ---------------- New known client connecting, could mean machine online again
                   5527: 	    
                   5528: 	    foreach my $id (keys(%hostip)) {
                   5529: 		if ($hostip{$id} ne $clientip ||
                   5530: 		    $hostip{$currenthostid} eq $clientip) {
                   5531: 		    # no need to try to do recon's to myself
                   5532: 		    next;
                   5533: 		}
1.307     albertel 5534: 		&reconlonc("$perlvar{'lonSockDir'}/".$hostname{$id});
1.212     foxr     5535: 	    }
                   5536: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   5537: 	    &status('Will listen to '.$clientname);
                   5538: # ------------------------------------------------------------ Process requests
                   5539: 	    my $keep_going = 1;
                   5540: 	    my $user_input;
                   5541: 	    while(($user_input = get_request) && $keep_going) {
                   5542: 		alarm(120);
                   5543: 		Debug("Main: Got $user_input\n");
                   5544: 		$keep_going = &process_request($user_input);
1.178     foxr     5545: 		alarm(0);
1.212     foxr     5546: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     5547: 	    }
1.212     foxr     5548: 
1.59      www      5549: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     5550: 	}  else {
1.161     foxr     5551: 	    print $client "refused\n";
                   5552: 	    $client->close();
1.190     albertel 5553: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     5554: 		     ."Rejected client $clientip, closing connection</font>");
                   5555: 	}
1.212     foxr     5556:     }            
1.161     foxr     5557:     
1.1       albertel 5558: # =============================================================================
1.161     foxr     5559:     
1.190     albertel 5560:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     5561: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   5562:     
                   5563:     
                   5564:     # this exit is VERY important, otherwise the child will become
                   5565:     # a producer of more and more children, forking yourself into
                   5566:     # process death.
                   5567:     exit;
1.106     foxr     5568:     
1.78      foxr     5569: }
1.261     foxr     5570: #
                   5571: #   Determine if a user is an author for the indicated domain.
                   5572: #
                   5573: # Parameters:
                   5574: #    domain          - domain to check in .
                   5575: #    user            - Name of user to check.
                   5576: #
                   5577: # Return:
                   5578: #     1             - User is an author for domain.
                   5579: #     0             - User is not an author for domain.
                   5580: sub is_author {
                   5581:     my ($domain, $user) = @_;
                   5582: 
                   5583:     &Debug("is_author: $user @ $domain");
                   5584: 
                   5585:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   5586: 				 &GDBM_READER());
                   5587: 
                   5588:     #  Author role should show up as a key /domain/_au
1.78      foxr     5589: 
1.321     albertel 5590:     my $key    = "/$domain/_au";
                   5591:     my $value;
                   5592:     if (defined($hashref)) {
                   5593: 	$value = $hashref->{$key};
                   5594:     }
1.78      foxr     5595: 
1.261     foxr     5596:     if(defined($value)) {
                   5597: 	&Debug("$user @ $domain is an author");
                   5598:     }
                   5599: 
                   5600:     return defined($value);
                   5601: }
1.78      foxr     5602: #
                   5603: #   Checks to see if the input roleput request was to set
                   5604: # an author role.  If so, invokes the lchtmldir script to set
                   5605: # up a correct public_html 
                   5606: # Parameters:
                   5607: #    request   - The request sent to the rolesput subchunk.
                   5608: #                We're looking for  /domain/_au
                   5609: #    domain    - The domain in which the user is having roles doctored.
                   5610: #    user      - Name of the user for which the role is being put.
                   5611: #    authtype  - The authentication type associated with the user.
                   5612: #
1.289     albertel 5613: sub manage_permissions {
1.192     foxr     5614:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     5615: 
1.261     foxr     5616:     &Debug("manage_permissions: $request $domain $user $authtype");
                   5617: 
1.78      foxr     5618:     # See if the request is of the form /$domain/_au
1.289     albertel 5619:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.78      foxr     5620: 	my $execdir = $perlvar{'lonDaemons'};
                   5621: 	my $userhome= "/home/$user" ;
1.134     albertel 5622: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261     foxr     5623: 	&Debug("Setting homedir permissions for $userhome");
1.78      foxr     5624: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   5625:     }
                   5626: }
1.222     foxr     5627: 
                   5628: 
                   5629: #
                   5630: #  Return the full path of a user password file, whether it exists or not.
                   5631: # Parameters:
                   5632: #   domain     - Domain in which the password file lives.
                   5633: #   user       - name of the user.
                   5634: # Returns:
                   5635: #    Full passwd path:
                   5636: #
                   5637: sub password_path {
                   5638:     my ($domain, $user) = @_;
1.264     albertel 5639:     return &propath($domain, $user).'/passwd';
1.222     foxr     5640: }
                   5641: 
                   5642: #   Password Filename
                   5643: #   Returns the path to a passwd file given domain and user... only if
                   5644: #  it exists.
                   5645: # Parameters:
                   5646: #   domain    - Domain in which to search.
                   5647: #   user      - username.
                   5648: # Returns:
                   5649: #   - If the password file exists returns its path.
                   5650: #   - If the password file does not exist, returns undefined.
                   5651: #
                   5652: sub password_filename {
                   5653:     my ($domain, $user) = @_;
                   5654: 
                   5655:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   5656: 
                   5657:     my $path  = &password_path($domain, $user);
                   5658:     Debug("PasswordFilename got path: $path");
                   5659:     if(-e $path) {
                   5660: 	return $path;
                   5661:     } else {
                   5662: 	return undef;
                   5663:     }
                   5664: }
                   5665: 
                   5666: #
                   5667: #   Rewrite the contents of the user's passwd file.
                   5668: #  Parameters:
                   5669: #    domain    - domain of the user.
                   5670: #    name      - User's name.
                   5671: #    contents  - New contents of the file.
                   5672: # Returns:
                   5673: #   0    - Failed.
                   5674: #   1    - Success.
                   5675: #
                   5676: sub rewrite_password_file {
                   5677:     my ($domain, $user, $contents) = @_;
                   5678: 
                   5679:     my $file = &password_filename($domain, $user);
                   5680:     if (defined $file) {
                   5681: 	my $pf = IO::File->new(">$file");
                   5682: 	if($pf) {
                   5683: 	    print $pf "$contents\n";
                   5684: 	    return 1;
                   5685: 	} else {
                   5686: 	    return 0;
                   5687: 	}
                   5688:     } else {
                   5689: 	return 0;
                   5690:     }
                   5691: 
                   5692: }
                   5693: 
1.78      foxr     5694: #
1.222     foxr     5695: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     5696: 
                   5697: #     Returns the authorization type or nouser if there is no such user.
                   5698: #
1.222     foxr     5699: sub get_auth_type 
1.78      foxr     5700: {
1.192     foxr     5701: 
                   5702:     my ($domain, $user)  = @_;
1.78      foxr     5703: 
1.222     foxr     5704:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     5705:     my $proname    = &propath($domain, $user); 
                   5706:     my $passwdfile = "$proname/passwd";
                   5707:     if( -e $passwdfile ) {
                   5708: 	my $pf = IO::File->new($passwdfile);
                   5709: 	my $realpassword = <$pf>;
                   5710: 	chomp($realpassword);
1.79      foxr     5711: 	Debug("Password info = $realpassword\n");
1.78      foxr     5712: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     5713: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  5714: 	return "$authtype:$contentpwd";     
1.224     foxr     5715:     } else {
1.79      foxr     5716: 	Debug("Returning nouser");
1.78      foxr     5717: 	return "nouser";
                   5718:     }
1.1       albertel 5719: }
                   5720: 
1.220     foxr     5721: #
                   5722: #  Validate a user given their domain, name and password.  This utility
                   5723: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   5724: #  to validate the login credentials of a user.
                   5725: # Parameters:
                   5726: #    $domain    - The domain being logged into (this is required due to
                   5727: #                 the capability for multihomed systems.
                   5728: #    $user      - The name of the user being validated.
                   5729: #    $password  - The user's propoposed password.
                   5730: #
                   5731: # Returns:
                   5732: #     1        - The domain,user,pasword triplet corresponds to a valid
                   5733: #                user.
                   5734: #     0        - The domain,user,password triplet is not a valid user.
                   5735: #
                   5736: sub validate_user {
                   5737:     my ($domain, $user, $password) = @_;
                   5738: 
                   5739: 
                   5740:     # Why negative ~pi you may well ask?  Well this function is about
                   5741:     # authentication, and therefore very important to get right.
                   5742:     # I've initialized the flag that determines whether or not I've 
                   5743:     # validated correctly to a value it's not supposed to get.
                   5744:     # At the end of this function. I'll ensure that it's not still that
                   5745:     # value so we don't just wind up returning some accidental value
                   5746:     # as a result of executing an unforseen code path that
1.249     foxr     5747:     # did not set $validated.  At the end of valid execution paths,
                   5748:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     5749: 
                   5750:     my $validated = -3.14159;
                   5751: 
                   5752:     #  How we authenticate is determined by the type of authentication
                   5753:     #  the user has been assigned.  If the authentication type is
                   5754:     #  "nouser", the user does not exist so we will return 0.
                   5755: 
1.222     foxr     5756:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     5757:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   5758: 
                   5759:     my $null = pack("C",0);	# Used by kerberos auth types.
                   5760: 
                   5761:     if ($howpwd ne 'nouser') {
                   5762: 
                   5763: 	if($howpwd eq "internal") { # Encrypted is in local password file.
                   5764: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
                   5765: 	}
                   5766: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   5767: 	    $contentpwd = (getpwnam($user))[1];
                   5768: 	    if($contentpwd) {
                   5769: 		if($contentpwd eq 'x') { # Shadow password file...
                   5770: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   5771: 		    open PWAUTH,  "|$pwauth_path" or
                   5772: 			die "Cannot invoke authentication";
                   5773: 		    print PWAUTH "$user\n$password\n";
                   5774: 		    close PWAUTH;
                   5775: 		    $validated = ! $?;
                   5776: 
                   5777: 		} else { 	         # Passwords in /etc/passwd. 
                   5778: 		    $validated = (crypt($password,
                   5779: 					$contentpwd) eq $contentpwd);
                   5780: 		}
                   5781: 	    } else {
                   5782: 		$validated = 0;
                   5783: 	    }
                   5784: 	}
                   5785: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   5786: 	    if(! ($password =~ /$null/) ) {
                   5787: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   5788: 							   "",
                   5789: 							   $contentpwd,,
                   5790: 							   'krbtgt',
                   5791: 							   $contentpwd,
                   5792: 							   1,
                   5793: 							   $password);
                   5794: 		if(!$k4error) {
                   5795: 		    $validated = 1;
1.224     foxr     5796: 		} else {
1.220     foxr     5797: 		    $validated = 0;
                   5798: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   5799: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   5800: 		}
1.224     foxr     5801: 	    } else {
1.220     foxr     5802: 		$validated = 0; # Password has a match with null.
                   5803: 	    }
1.224     foxr     5804: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220     foxr     5805: 	    if(!($password =~ /$null/)) { # Null password not allowed.
                   5806: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   5807: 							  .$contentpwd);
                   5808: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   5809: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   5810: 		my $credentials= &Authen::Krb5::cc_default();
                   5811: 		$credentials->initialize($krbclient);
1.270     matthew  5812: 		my $krbreturn  = &Authen::Krb5::get_in_tkt_with_password($krbclient,
1.220     foxr     5813: 									 $krbserver,
                   5814: 									 $password,
                   5815: 									 $credentials);
                   5816: 		$validated = ($krbreturn == 1);
1.224     foxr     5817: 	    } else {
1.220     foxr     5818: 		$validated = 0;
                   5819: 	    }
1.224     foxr     5820: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     5821: 	    #  Authenticate via installation specific authentcation method:
                   5822: 	    $validated = &localauth::localauth($user, 
                   5823: 					       $password, 
                   5824: 					       $contentpwd);
1.224     foxr     5825: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     5826: 	    $validated = 0;
                   5827: 	}
                   5828:     } else {
                   5829: 	$validated = 0;
                   5830:     }
                   5831:     #
                   5832:     #  $validated has the correct stat of the authentication:
                   5833:     #
                   5834: 
                   5835:     unless ($validated != -3.14159) {
1.249     foxr     5836: 	#  I >really really< want to know if this happens.
                   5837: 	#  since it indicates that user authentication is badly
                   5838: 	#  broken in some code path.
                   5839:         #
                   5840: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     5841:     }
                   5842:     return $validated;
                   5843: }
                   5844: 
                   5845: 
1.84      albertel 5846: sub addline {
                   5847:     my ($fname,$hostid,$ip,$newline)=@_;
                   5848:     my $contents;
                   5849:     my $found=0;
                   5850:     my $expr='^'.$hostid.':'.$ip.':';
                   5851:     $expr =~ s/\./\\\./g;
1.134     albertel 5852:     my $sh;
1.84      albertel 5853:     if ($sh=IO::File->new("$fname.subscription")) {
                   5854: 	while (my $subline=<$sh>) {
                   5855: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   5856: 	}
                   5857: 	$sh->close();
                   5858:     }
                   5859:     $sh=IO::File->new(">$fname.subscription");
                   5860:     if ($contents) { print $sh $contents; }
                   5861:     if ($newline) { print $sh $newline; }
                   5862:     $sh->close();
                   5863:     return $found;
1.86      www      5864: }
                   5865: 
1.234     foxr     5866: sub get_chat {
1.324     raeburn  5867:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 5868: 
1.87      www      5869:     my @entries=();
1.324     raeburn  5870:     my $namespace = 'nohist_chatroom';
                   5871:     my $namespace_inroom = 'nohist_inchatroom';
                   5872:     if (defined($group)) {
                   5873:         $namespace .= '_'.$group;
                   5874:         $namespace_inroom .= '_'.$group;
                   5875:     }
                   5876:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 5877: 				 &GDBM_READER());
                   5878:     if ($hashref) {
                   5879: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 5880: 	&untie_user_hash($hashref);
1.123     www      5881:     }
1.124     www      5882:     my @participants=();
1.134     albertel 5883:     my $cutoff=time-60;
1.324     raeburn  5884:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 5885: 			      &GDBM_WRCREAT());
                   5886:     if ($hashref) {
                   5887:         $hashref->{$uname.':'.$udom}=time;
                   5888:         foreach my $user (sort(keys(%$hashref))) {
                   5889: 	    if ($hashref->{$user}>$cutoff) {
                   5890: 		push(@participants, 'active_participant:'.$user);
1.123     www      5891:             }
                   5892:         }
1.311     albertel 5893:         &untie_user_hash($hashref);
1.86      www      5894:     }
1.124     www      5895:     return (@participants,@entries);
1.86      www      5896: }
                   5897: 
1.234     foxr     5898: sub chat_add {
1.324     raeburn  5899:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 5900:     my @entries=();
1.142     www      5901:     my $time=time;
1.324     raeburn  5902:     my $namespace = 'nohist_chatroom';
                   5903:     my $logfile = 'chatroom.log';
                   5904:     if (defined($group)) {
                   5905:         $namespace .= '_'.$group;
                   5906:         $logfile = 'chatroom_'.$group.'.log';
                   5907:     }
                   5908:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 5909: 				 &GDBM_WRCREAT());
                   5910:     if ($hashref) {
                   5911: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 5912: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   5913: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   5914: 	my $newid=$time.'_000000';
                   5915: 	if ($thentime==$time) {
                   5916: 	    $idnum=~s/^0+//;
                   5917: 	    $idnum++;
                   5918: 	    $idnum=substr('000000'.$idnum,-6,6);
                   5919: 	    $newid=$time.'_'.$idnum;
                   5920: 	}
1.310     albertel 5921: 	$hashref->{$newid}=$newchat;
1.88      albertel 5922: 	my $expired=$time-3600;
1.310     albertel 5923: 	foreach my $comment (keys(%$hashref)) {
                   5924: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 5925: 	    if ($thistime<$expired) {
1.310     albertel 5926: 		delete $hashref->{$comment};
1.88      albertel 5927: 	    }
                   5928: 	}
1.310     albertel 5929: 	{
                   5930: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  5931: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 5932: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   5933: 	    }
                   5934: 	    close(CHATLOG);
1.142     www      5935: 	}
1.311     albertel 5936: 	&untie_user_hash($hashref);
1.86      www      5937:     }
1.84      albertel 5938: }
                   5939: 
                   5940: sub unsub {
                   5941:     my ($fname,$clientip)=@_;
                   5942:     my $result;
1.188     foxr     5943:     my $unsubs = 0;		# Number of successful unsubscribes:
                   5944: 
                   5945: 
                   5946:     # An old way subscriptions were handled was to have a 
                   5947:     # subscription marker file:
                   5948: 
                   5949:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     5950:     if (unlink("$fname.$clientname")) {
1.188     foxr     5951: 	$unsubs++;		# Successful unsub via marker file.
                   5952:     } 
                   5953: 
                   5954:     # The more modern way to do it is to have a subscription list
                   5955:     # file:
                   5956: 
1.84      albertel 5957:     if (-e "$fname.subscription") {
1.161     foxr     5958: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     5959: 	if ($found) { 
                   5960: 	    $unsubs++;
                   5961: 	}
                   5962:     } 
                   5963: 
                   5964:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   5965:     #  resource we can return ok:
                   5966: 
                   5967:     if($unsubs) {
                   5968: 	$result = "ok\n";
1.84      albertel 5969:     } else {
1.188     foxr     5970: 	$result = "not_subscribed\n";
1.84      albertel 5971:     }
1.188     foxr     5972: 
1.84      albertel 5973:     return $result;
                   5974: }
                   5975: 
1.101     www      5976: sub currentversion {
                   5977:     my $fname=shift;
                   5978:     my $version=-1;
                   5979:     my $ulsdir='';
                   5980:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   5981:        $ulsdir=$1;
                   5982:     }
1.114     albertel 5983:     my ($fnamere1,$fnamere2);
                   5984:     # remove version if already specified
1.101     www      5985:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 5986:     # get the bits that go before and after the version number
                   5987:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   5988: 	$fnamere1=$1;
                   5989: 	$fnamere2='.'.$2;
                   5990:     }
1.101     www      5991:     if (-e $fname) { $version=1; }
                   5992:     if (-e $ulsdir) {
1.134     albertel 5993: 	if(-d $ulsdir) {
                   5994: 	    if (opendir(LSDIR,$ulsdir)) {
                   5995: 		my $ulsfn;
                   5996: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      5997: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 5998: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   5999: 		    unless (-l $thisfile) {
1.160     www      6000: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 6001: 			    if ($1>$version) { $version=$1; }
                   6002: 			}
                   6003: 		    }
                   6004: 		}
                   6005: 		closedir(LSDIR);
                   6006: 		$version++;
                   6007: 	    }
                   6008: 	}
                   6009:     }
                   6010:     return $version;
1.101     www      6011: }
                   6012: 
                   6013: sub thisversion {
                   6014:     my $fname=shift;
                   6015:     my $version=-1;
                   6016:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   6017: 	$version=$1;
                   6018:     }
                   6019:     return $version;
                   6020: }
                   6021: 
1.84      albertel 6022: sub subscribe {
                   6023:     my ($userinput,$clientip)=@_;
                   6024:     my $result;
1.293     albertel 6025:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 6026:     my $ownership=&ishome($fname);
                   6027:     if ($ownership eq 'owner') {
1.101     www      6028: # explitly asking for the current version?
                   6029:         unless (-e $fname) {
                   6030:             my $currentversion=&currentversion($fname);
                   6031: 	    if (&thisversion($fname)==$currentversion) {
                   6032:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   6033: 		    my $root=$1;
                   6034:                     my $extension=$2;
                   6035:                     symlink($root.'.'.$extension,
                   6036:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      6037:                     unless ($extension=~/\.meta$/) {
                   6038:                        symlink($root.'.'.$extension.'.meta',
                   6039:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   6040: 		    }
1.101     www      6041:                 }
                   6042:             }
                   6043:         }
1.84      albertel 6044: 	if (-e $fname) {
                   6045: 	    if (-d $fname) {
                   6046: 		$result="directory\n";
                   6047: 	    } else {
1.161     foxr     6048: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 6049: 		my $now=time;
1.161     foxr     6050: 		my $found=&addline($fname,$clientname,$clientip,
                   6051: 				   "$clientname:$clientip:$now\n");
1.84      albertel 6052: 		if ($found) { $result="$fname\n"; }
                   6053: 		# if they were subscribed to only meta data, delete that
                   6054:                 # subscription, when you subscribe to a file you also get
                   6055:                 # the metadata
                   6056: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   6057: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
                   6058: 		$fname="http://$thisserver/".$fname;
                   6059: 		$result="$fname\n";
                   6060: 	    }
                   6061: 	} else {
                   6062: 	    $result="not_found\n";
                   6063: 	}
                   6064:     } else {
                   6065: 	$result="rejected\n";
                   6066:     }
                   6067:     return $result;
                   6068: }
1.287     foxr     6069: #  Change the passwd of a unix user.  The caller must have
                   6070: #  first verified that the user is a loncapa user.
                   6071: #
                   6072: # Parameters:
                   6073: #    user      - Unix user name to change.
                   6074: #    pass      - New password for the user.
                   6075: # Returns:
                   6076: #    ok    - if success
                   6077: #    other - Some meaningfule error message string.
                   6078: # NOTE:
                   6079: #    invokes a setuid script to change the passwd.
                   6080: sub change_unix_password {
                   6081:     my ($user, $pass) = @_;
                   6082: 
                   6083:     &Debug("change_unix_password");
                   6084:     my $execdir=$perlvar{'lonDaemons'};
                   6085:     &Debug("Opening lcpasswd pipeline");
                   6086:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   6087: 			   ."$perlvar{'lonDaemons'}"
                   6088: 			   ."/logs/lcpasswd.log");
                   6089:     print $pf "$user\n$pass\n$pass\n";
                   6090:     close $pf;
                   6091:     my $err = $?;
                   6092:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   6093: 	"pwchange_falure - unknown error";
                   6094: 
                   6095:     
                   6096: }
                   6097: 
1.91      albertel 6098: 
                   6099: sub make_passwd_file {
1.98      foxr     6100:     my ($uname, $umode,$npass,$passfilename)=@_;
1.91      albertel 6101:     my $result="ok\n";
                   6102:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   6103: 	{
                   6104: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     6105: 	    if ($pf) {
                   6106: 		print $pf "$umode:$npass\n";
                   6107: 	    } else {
                   6108: 		$result = "pass_file_failed_error";
                   6109: 	    }
1.91      albertel 6110: 	}
                   6111:     } elsif ($umode eq 'internal') {
                   6112: 	my $salt=time;
                   6113: 	$salt=substr($salt,6,2);
                   6114: 	my $ncpass=crypt($npass,$salt);
                   6115: 	{
                   6116: 	    &Debug("Creating internal auth");
                   6117: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     6118: 	    if($pf) {
                   6119: 		print $pf "internal:$ncpass\n"; 
                   6120: 	    } else {
                   6121: 		$result = "pass_file_failed_error";
                   6122: 	    }
1.91      albertel 6123: 	}
                   6124:     } elsif ($umode eq 'localauth') {
                   6125: 	{
                   6126: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     6127: 	    if($pf) {
                   6128: 		print $pf "localauth:$npass\n";
                   6129: 	    } else {
                   6130: 		$result = "pass_file_failed_error";
                   6131: 	    }
1.91      albertel 6132: 	}
                   6133:     } elsif ($umode eq 'unix') {
                   6134: 	{
1.186     foxr     6135: 	    #
                   6136: 	    #  Don't allow the creation of privileged accounts!!! that would
                   6137: 	    #  be real bad!!!
                   6138: 	    #
                   6139: 	    my $uid = getpwnam($uname);
                   6140: 	    if((defined $uid) && ($uid == 0)) {
                   6141: 		&logthis(">>>Attempted to create privilged account blocked");
                   6142: 		return "no_priv_account_error\n";
                   6143: 	    }
                   6144: 
1.223     foxr     6145: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224     foxr     6146: 
                   6147: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
1.91      albertel 6148: 	    {
                   6149: 		&Debug("Executing external: ".$execpath);
1.98      foxr     6150: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  6151: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 6152: 		print $se "$uname\n";
                   6153: 		print $se "$npass\n";
                   6154: 		print $se "$npass\n";
1.223     foxr     6155: 		print $se "$lc_error_file\n"; # Status -> unique file.
1.97      foxr     6156: 	    }
1.285     foxr     6157: 	    if (-r $lc_error_file) {
                   6158: 		&Debug("Opening error file: $lc_error_file");
                   6159: 		my $error = IO::File->new("< $lc_error_file");
                   6160: 		my $useraddok = <$error>;
                   6161: 		$error->close;
                   6162: 		unlink($lc_error_file);
                   6163: 		
                   6164: 		chomp $useraddok;
                   6165: 	
                   6166: 		if($useraddok > 0) {
                   6167: 		    my $error_text = &lcuseraddstrerror($useraddok);
                   6168: 		    &logthis("Failed lcuseradd: $error_text");
                   6169: 		    $result = "lcuseradd_failed:$error_text\n";
                   6170: 		}  else {
                   6171: 		    my $pf = IO::File->new(">$passfilename");
                   6172: 		    if($pf) {
                   6173: 			print $pf "unix:\n";
                   6174: 		    } else {
                   6175: 			$result = "pass_file_failed_error";
                   6176: 		    }
                   6177: 		}
1.224     foxr     6178: 	    }  else {
1.285     foxr     6179: 		&Debug("Could not locate lcuseradd error: $lc_error_file");
                   6180: 		$result="bug_lcuseradd_no_output_file";
1.91      albertel 6181: 	    }
                   6182: 	}
                   6183:     } elsif ($umode eq 'none') {
                   6184: 	{
1.223     foxr     6185: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     6186: 	    if($pf) {
                   6187: 		print $pf "none:\n";
                   6188: 	    } else {
                   6189: 		$result = "pass_file_failed_error";
                   6190: 	    }
1.91      albertel 6191: 	}
                   6192:     } else {
                   6193: 	$result="auth_mode_error\n";
                   6194:     }
                   6195:     return $result;
1.121     albertel 6196: }
                   6197: 
1.265     albertel 6198: sub convert_photo {
                   6199:     my ($start,$dest)=@_;
                   6200:     system("convert $start $dest");
                   6201: }
                   6202: 
1.121     albertel 6203: sub sethost {
                   6204:     my ($remotereq) = @_;
                   6205:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 6206:     # ignore sethost if we are already correct
                   6207:     if ($hostid eq $currenthostid) {
                   6208: 	return 'ok';
                   6209:     }
                   6210: 
1.121     albertel 6211:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
                   6212:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200     matthew  6213: 	$currenthostid  =$hostid;
1.121     albertel 6214: 	$currentdomainid=$hostdom{$hostid};
                   6215: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
                   6216:     } else {
                   6217: 	&logthis("Requested host id $hostid not an alias of ".
                   6218: 		 $perlvar{'lonHostID'}." refusing connection");
                   6219: 	return 'unable_to_set';
                   6220:     }
                   6221:     return 'ok';
                   6222: }
                   6223: 
                   6224: sub version {
                   6225:     my ($userinput)=@_;
                   6226:     $remoteVERSION=(split(/:/,$userinput))[1];
                   6227:     return "version:$VERSION";
1.127     albertel 6228: }
1.178     foxr     6229: 
1.128     albertel 6230: #There is a copy of this in lonnet.pm
1.127     albertel 6231: sub userload {
                   6232:     my $numusers=0;
                   6233:     {
                   6234: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   6235: 	my $filename;
                   6236: 	my $curtime=time;
                   6237: 	while ($filename=readdir(LONIDS)) {
                   6238: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.138     albertel 6239: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159     albertel 6240: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.127     albertel 6241: 	}
                   6242: 	closedir(LONIDS);
                   6243:     }
                   6244:     my $userloadpercent=0;
                   6245:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   6246:     if ($maxuserload) {
1.129     albertel 6247: 	$userloadpercent=100*$numusers/$maxuserload;
1.127     albertel 6248:     }
1.130     albertel 6249:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127     albertel 6250:     return $userloadpercent;
1.91      albertel 6251: }
                   6252: 
1.205     raeburn  6253: # Routines for serializing arrays and hashes (copies from lonnet)
                   6254: 
                   6255: sub array2str {
                   6256:   my (@array) = @_;
                   6257:   my $result=&arrayref2str(\@array);
                   6258:   $result=~s/^__ARRAY_REF__//;
                   6259:   $result=~s/__END_ARRAY_REF__$//;
                   6260:   return $result;
                   6261: }
                   6262:                                                                                  
                   6263: sub arrayref2str {
                   6264:   my ($arrayref) = @_;
                   6265:   my $result='__ARRAY_REF__';
                   6266:   foreach my $elem (@$arrayref) {
                   6267:     if(ref($elem) eq 'ARRAY') {
                   6268:       $result.=&arrayref2str($elem).'&';
                   6269:     } elsif(ref($elem) eq 'HASH') {
                   6270:       $result.=&hashref2str($elem).'&';
                   6271:     } elsif(ref($elem)) {
                   6272:       #print("Got a ref of ".(ref($elem))." skipping.");
                   6273:     } else {
                   6274:       $result.=&escape($elem).'&';
                   6275:     }
                   6276:   }
                   6277:   $result=~s/\&$//;
                   6278:   $result .= '__END_ARRAY_REF__';
                   6279:   return $result;
                   6280: }
                   6281:                                                                                  
                   6282: sub hash2str {
                   6283:   my (%hash) = @_;
                   6284:   my $result=&hashref2str(\%hash);
                   6285:   $result=~s/^__HASH_REF__//;
                   6286:   $result=~s/__END_HASH_REF__$//;
                   6287:   return $result;
                   6288: }
                   6289:                                                                                  
                   6290: sub hashref2str {
                   6291:   my ($hashref)=@_;
                   6292:   my $result='__HASH_REF__';
                   6293:   foreach (sort(keys(%$hashref))) {
                   6294:     if (ref($_) eq 'ARRAY') {
                   6295:       $result.=&arrayref2str($_).'=';
                   6296:     } elsif (ref($_) eq 'HASH') {
                   6297:       $result.=&hashref2str($_).'=';
                   6298:     } elsif (ref($_)) {
                   6299:       $result.='=';
                   6300:       #print("Got a ref of ".(ref($_))." skipping.");
                   6301:     } else {
                   6302:         if ($_) {$result.=&escape($_).'=';} else { last; }
                   6303:     }
                   6304: 
                   6305:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   6306:       $result.=&arrayref2str($hashref->{$_}).'&';
                   6307:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   6308:       $result.=&hashref2str($hashref->{$_}).'&';
                   6309:     } elsif(ref($hashref->{$_})) {
                   6310:        $result.='&';
                   6311:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
                   6312:     } else {
                   6313:       $result.=&escape($hashref->{$_}).'&';
                   6314:     }
                   6315:   }
                   6316:   $result=~s/\&$//;
                   6317:   $result .= '__END_HASH_REF__';
                   6318:   return $result;
                   6319: }
1.200     matthew  6320: 
1.61      harris41 6321: # ----------------------------------- POD (plain old documentation, CPAN style)
                   6322: 
                   6323: =head1 NAME
                   6324: 
                   6325: lond - "LON Daemon" Server (port "LOND" 5663)
                   6326: 
                   6327: =head1 SYNOPSIS
                   6328: 
1.74      harris41 6329: Usage: B<lond>
                   6330: 
                   6331: Should only be run as user=www.  This is a command-line script which
                   6332: is invoked by B<loncron>.  There is no expectation that a typical user
                   6333: will manually start B<lond> from the command-line.  (In other words,
                   6334: DO NOT START B<lond> YOURSELF.)
1.61      harris41 6335: 
                   6336: =head1 DESCRIPTION
                   6337: 
1.74      harris41 6338: There are two characteristics associated with the running of B<lond>,
                   6339: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   6340: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   6341: subscriptions, etc).  These are described in two large
                   6342: sections below.
                   6343: 
                   6344: B<PROCESS MANAGEMENT>
                   6345: 
1.61      harris41 6346: Preforker - server who forks first. Runs as a daemon. HUPs.
                   6347: Uses IDEA encryption
                   6348: 
1.74      harris41 6349: B<lond> forks off children processes that correspond to the other servers
                   6350: in the network.  Management of these processes can be done at the
                   6351: parent process level or the child process level.
                   6352: 
                   6353: B<logs/lond.log> is the location of log messages.
                   6354: 
                   6355: The process management is now explained in terms of linux shell commands,
                   6356: subroutines internal to this code, and signal assignments:
                   6357: 
                   6358: =over 4
                   6359: 
                   6360: =item *
                   6361: 
                   6362: PID is stored in B<logs/lond.pid>
                   6363: 
                   6364: This is the process id number of the parent B<lond> process.
                   6365: 
                   6366: =item *
                   6367: 
                   6368: SIGTERM and SIGINT
                   6369: 
                   6370: Parent signal assignment:
                   6371:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   6372: 
                   6373: Child signal assignment:
                   6374:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   6375: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   6376:  to restart a new child.)
                   6377: 
                   6378: Command-line invocations:
                   6379:  B<kill> B<-s> SIGTERM I<PID>
                   6380:  B<kill> B<-s> SIGINT I<PID>
                   6381: 
                   6382: Subroutine B<HUNTSMAN>:
                   6383:  This is only invoked for the B<lond> parent I<PID>.
                   6384: This kills all the children, and then the parent.
                   6385: The B<lonc.pid> file is cleared.
                   6386: 
                   6387: =item *
                   6388: 
                   6389: SIGHUP
                   6390: 
                   6391: Current bug:
                   6392:  This signal can only be processed the first time
                   6393: on the parent process.  Subsequent SIGHUP signals
                   6394: have no effect.
                   6395: 
                   6396: Parent signal assignment:
                   6397:  $SIG{HUP}  = \&HUPSMAN;
                   6398: 
                   6399: Child signal assignment:
                   6400:  none (nothing happens)
                   6401: 
                   6402: Command-line invocations:
                   6403:  B<kill> B<-s> SIGHUP I<PID>
                   6404: 
                   6405: Subroutine B<HUPSMAN>:
                   6406:  This is only invoked for the B<lond> parent I<PID>,
                   6407: This kills all the children, and then the parent.
                   6408: The B<lond.pid> file is cleared.
                   6409: 
                   6410: =item *
                   6411: 
                   6412: SIGUSR1
                   6413: 
                   6414: Parent signal assignment:
                   6415:  $SIG{USR1} = \&USRMAN;
                   6416: 
                   6417: Child signal assignment:
                   6418:  $SIG{USR1}= \&logstatus;
                   6419: 
                   6420: Command-line invocations:
                   6421:  B<kill> B<-s> SIGUSR1 I<PID>
                   6422: 
                   6423: Subroutine B<USRMAN>:
                   6424:  When invoked for the B<lond> parent I<PID>,
                   6425: SIGUSR1 is sent to all the children, and the status of
                   6426: each connection is logged.
1.144     foxr     6427: 
                   6428: =item *
                   6429: 
                   6430: SIGUSR2
                   6431: 
                   6432: Parent Signal assignment:
                   6433:     $SIG{USR2} = \&UpdateHosts
                   6434: 
                   6435: Child signal assignment:
                   6436:     NONE
                   6437: 
1.74      harris41 6438: 
                   6439: =item *
                   6440: 
                   6441: SIGCHLD
                   6442: 
                   6443: Parent signal assignment:
                   6444:  $SIG{CHLD} = \&REAPER;
                   6445: 
                   6446: Child signal assignment:
                   6447:  none
                   6448: 
                   6449: Command-line invocations:
                   6450:  B<kill> B<-s> SIGCHLD I<PID>
                   6451: 
                   6452: Subroutine B<REAPER>:
                   6453:  This is only invoked for the B<lond> parent I<PID>.
                   6454: Information pertaining to the child is removed.
                   6455: The socket port is cleaned up.
                   6456: 
                   6457: =back
                   6458: 
                   6459: B<SERVER-SIDE ACTIVITIES>
                   6460: 
                   6461: Server-side information can be accepted in an encrypted or non-encrypted
                   6462: method.
                   6463: 
                   6464: =over 4
                   6465: 
                   6466: =item ping
                   6467: 
                   6468: Query a client in the hosts.tab table; "Are you there?"
                   6469: 
                   6470: =item pong
                   6471: 
                   6472: Respond to a ping query.
                   6473: 
                   6474: =item ekey
                   6475: 
                   6476: Read in encrypted key, make cipher.  Respond with a buildkey.
                   6477: 
                   6478: =item load
                   6479: 
                   6480: Respond with CPU load based on a computation upon /proc/loadavg.
                   6481: 
                   6482: =item currentauth
                   6483: 
                   6484: Reply with current authentication information (only over an
                   6485: encrypted channel).
                   6486: 
                   6487: =item auth
                   6488: 
                   6489: Only over an encrypted channel, reply as to whether a user's
                   6490: authentication information can be validated.
                   6491: 
                   6492: =item passwd
                   6493: 
                   6494: Allow for a password to be set.
                   6495: 
                   6496: =item makeuser
                   6497: 
                   6498: Make a user.
                   6499: 
                   6500: =item passwd
                   6501: 
                   6502: Allow for authentication mechanism and password to be changed.
                   6503: 
                   6504: =item home
1.61      harris41 6505: 
1.74      harris41 6506: Respond to a question "are you the home for a given user?"
                   6507: 
                   6508: =item update
                   6509: 
                   6510: Update contents of a subscribed resource.
                   6511: 
                   6512: =item unsubscribe
                   6513: 
                   6514: The server is unsubscribing from a resource.
                   6515: 
                   6516: =item subscribe
                   6517: 
                   6518: The server is subscribing to a resource.
                   6519: 
                   6520: =item log
                   6521: 
                   6522: Place in B<logs/lond.log>
                   6523: 
                   6524: =item put
                   6525: 
                   6526: stores hash in namespace
                   6527: 
1.230     foxr     6528: =item rolesputy
1.74      harris41 6529: 
                   6530: put a role into a user's environment
                   6531: 
                   6532: =item get
                   6533: 
                   6534: returns hash with keys from array
                   6535: reference filled in from namespace
                   6536: 
                   6537: =item eget
                   6538: 
                   6539: returns hash with keys from array
                   6540: reference filled in from namesp (encrypts the return communication)
                   6541: 
                   6542: =item rolesget
                   6543: 
                   6544: get a role from a user's environment
                   6545: 
                   6546: =item del
                   6547: 
                   6548: deletes keys out of array from namespace
                   6549: 
                   6550: =item keys
                   6551: 
                   6552: returns namespace keys
                   6553: 
                   6554: =item dump
                   6555: 
                   6556: dumps the complete (or key matching regexp) namespace into a hash
                   6557: 
                   6558: =item store
                   6559: 
                   6560: stores hash permanently
                   6561: for this url; hashref needs to be given and should be a \%hashname; the
                   6562: remaining args aren't required and if they aren't passed or are '' they will
                   6563: be derived from the ENV
                   6564: 
                   6565: =item restore
                   6566: 
                   6567: returns a hash for a given url
                   6568: 
                   6569: =item querysend
                   6570: 
                   6571: Tells client about the lonsql process that has been launched in response
                   6572: to a sent query.
                   6573: 
                   6574: =item queryreply
                   6575: 
                   6576: Accept information from lonsql and make appropriate storage in temporary
                   6577: file space.
                   6578: 
                   6579: =item idput
                   6580: 
                   6581: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   6582: for each student, defined perhaps by the institutional Registrar.)
                   6583: 
                   6584: =item idget
                   6585: 
                   6586: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   6587: for each student, defined perhaps by the institutional Registrar.)
                   6588: 
                   6589: =item tmpput
                   6590: 
                   6591: Accept and store information in temporary space.
                   6592: 
                   6593: =item tmpget
                   6594: 
                   6595: Send along temporarily stored information.
                   6596: 
                   6597: =item ls
                   6598: 
                   6599: List part of a user's directory.
                   6600: 
1.135     foxr     6601: =item pushtable
                   6602: 
                   6603: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   6604: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   6605: must be restored manually in case of a problem with the new table file.
                   6606: pushtable requires that the request be encrypted and validated via
                   6607: ValidateManager.  The form of the command is:
                   6608: enc:pushtable tablename <tablecontents> \n
                   6609: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   6610: cleartext newline.
                   6611: 
1.74      harris41 6612: =item Hanging up (exit or init)
                   6613: 
                   6614: What to do when a client tells the server that they (the client)
                   6615: are leaving the network.
                   6616: 
                   6617: =item unknown command
                   6618: 
                   6619: If B<lond> is sent an unknown command (not in the list above),
                   6620: it replys to the client "unknown_cmd".
1.135     foxr     6621: 
1.74      harris41 6622: 
                   6623: =item UNKNOWN CLIENT
                   6624: 
                   6625: If the anti-spoofing algorithm cannot verify the client,
                   6626: the client is rejected (with a "refused" message sent
                   6627: to the client, and the connection is closed.
                   6628: 
                   6629: =back
1.61      harris41 6630: 
                   6631: =head1 PREREQUISITES
                   6632: 
                   6633: IO::Socket
                   6634: IO::File
                   6635: Apache::File
                   6636: Symbol
                   6637: POSIX
                   6638: Crypt::IDEA
                   6639: LWP::UserAgent()
                   6640: GDBM_File
                   6641: Authen::Krb4
1.91      albertel 6642: Authen::Krb5
1.61      harris41 6643: 
                   6644: =head1 COREQUISITES
                   6645: 
                   6646: =head1 OSNAMES
                   6647: 
                   6648: linux
                   6649: 
                   6650: =head1 SCRIPT CATEGORIES
                   6651: 
                   6652: Server/Process
                   6653: 
                   6654: =cut

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