Annotation of loncom/lond, revision 1.283

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

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