Annotation of loncom/lond, revision 1.345

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

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