Annotation of loncom/lond, revision 1.285

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.285   ! foxr        5: # $Id: lond,v 1.284 2005/06/03 18:23:19 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.285   ! foxr       61: my $VERSION='$Revision: 1.284 $'; #' 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);
1.284     raeburn  2448:                 $value = &unescape($value);
1.230     foxr     2449: 		# We could check that we have a number...
                   2450: 		if (! defined($value) || $value eq '') {
                   2451: 		    $value = 1;
                   2452: 		}
                   2453: 		$hashref->{$key}+=$value;
1.284     raeburn  2454:                 if ($namespace eq 'nohist_resourcetracker') {
                   2455:                     if ($hashref->{$key} < 0) {
                   2456:                         $hashref->{$key} = 0;
                   2457:                     }
                   2458:                 }
1.230     foxr     2459: 	    }
                   2460: 	    if (untie(%$hashref)) {
                   2461: 		&Reply( $client, "ok\n", $userinput);
                   2462: 	    } else {
                   2463: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2464: 			 "while attempting inc\n", $userinput);
                   2465: 	    }
                   2466: 	} else {
                   2467: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2468: 		     "while attempting inc\n", $userinput);
                   2469: 	}
                   2470:     } else {
                   2471: 	&Failure($client, "refused\n", $userinput);
                   2472:     }
                   2473:     
                   2474:     return 1;
                   2475: }
                   2476: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   2477: 
                   2478: #
                   2479: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   2480: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   2481: #   for a person grants the permissions packaged with that role
                   2482: #   to that user when the role is selected.
                   2483: #
                   2484: # Parameters:
                   2485: #    $cmd       - The command string (rolesput).
                   2486: #    $tail      - The remainder of the request line.  For rolesput this
                   2487: #                 consists of a colon separated list that contains:
                   2488: #                 The domain and user that is granting the role (logged).
                   2489: #                 The domain and user that is getting the role.
                   2490: #                 The roles being granted as a set of & separated pairs.
                   2491: #                 each pair a key value pair.
                   2492: #    $client    - File descriptor connected to the client.
                   2493: # Returns:
                   2494: #     0         - If the daemon should exit
                   2495: #     1         - To continue processing.
                   2496: #
                   2497: #
                   2498: sub roles_put_handler {
                   2499:     my ($cmd, $tail, $client) = @_;
                   2500: 
                   2501:     my $userinput  = "$cmd:$tail";
                   2502: 
                   2503:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   2504:     
                   2505: 
                   2506:     my $namespace='roles';
                   2507:     chomp($what);
                   2508:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2509: 				 &GDBM_WRCREAT(), "P",
                   2510: 				 "$exedom:$exeuser:$what");
                   2511:     #
                   2512:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   2513:     #  handle is open for the minimal amount of time.  Since the flush
                   2514:     #  is done on close this improves the chances the log will be an un-
                   2515:     #  corrupted ordered thing.
                   2516:     if ($hashref) {
1.261     foxr     2517: 	my $pass_entry = &get_auth_type($udom, $uname);
                   2518: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   2519: 	$auth_type = $auth_type.":";
1.230     foxr     2520: 	my @pairs=split(/\&/,$what);
                   2521: 	foreach my $pair (@pairs) {
                   2522: 	    my ($key,$value)=split(/=/,$pair);
                   2523: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     2524: 			       $auth_type);
1.230     foxr     2525: 	    $hashref->{$key}=$value;
                   2526: 	}
                   2527: 	if (untie($hashref)) {
                   2528: 	    &Reply($client, "ok\n", $userinput);
                   2529: 	} else {
                   2530: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2531: 		     "while attempting rolesput\n", $userinput);
                   2532: 	}
                   2533:     } else {
                   2534: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2535: 		 "while attempting rolesput\n", $userinput);
                   2536:     }
                   2537:     return 1;
                   2538: }
                   2539: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   2540: 
                   2541: #
1.231     foxr     2542: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   2543: #  a permissions package associated with the role from the user's profile.
                   2544: #
                   2545: # Parameters:
                   2546: #     $cmd                 - The command (rolesdel)
                   2547: #     $tail                - The remainder of the request line. This consists
                   2548: #                             of:
                   2549: #                             The domain and user requesting the change (logged)
                   2550: #                             The domain and user being changed.
                   2551: #                             The roles being revoked.  These are shipped to us
                   2552: #                             as a bunch of & separated role name keywords.
                   2553: #     $client              - The file handle open on the client.
                   2554: # Returns:
                   2555: #     1                    - Continue processing
                   2556: #     0                    - Exit.
                   2557: #
                   2558: sub roles_delete_handler {
                   2559:     my ($cmd, $tail, $client)  = @_;
                   2560: 
                   2561:     my $userinput    = "$cmd:$tail";
                   2562:    
                   2563:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   2564:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   2565: 	   "what = ".$what);
                   2566:     my $namespace='roles';
                   2567:     chomp($what);
                   2568:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2569: 				 &GDBM_WRCREAT(), "D",
                   2570: 				 "$exedom:$exeuser:$what");
                   2571:     
                   2572:     if ($hashref) {
                   2573: 	my @rolekeys=split(/\&/,$what);
                   2574: 	
                   2575: 	foreach my $key (@rolekeys) {
                   2576: 	    delete $hashref->{$key};
                   2577: 	}
                   2578: 	if (untie(%$hashref)) {
                   2579: 	    &Reply($client, "ok\n", $userinput);
                   2580: 	} else {
                   2581: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2582: 		     "while attempting rolesdel\n", $userinput);
                   2583: 	}
                   2584:     } else {
                   2585:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2586: 		 "while attempting rolesdel\n", $userinput);
                   2587:     }
                   2588:     
                   2589:     return 1;
                   2590: }
                   2591: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   2592: 
                   2593: # Unencrypted get from a user's profile database.  See 
                   2594: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   2595: # This function retrieves a keyed item from a specific named database in the
                   2596: # user's directory.
                   2597: #
                   2598: # Parameters:
                   2599: #   $cmd             - Command request keyword (get).
                   2600: #   $tail            - Tail of the command.  This is a colon separated list
                   2601: #                      consisting of the domain and username that uniquely
                   2602: #                      identifies the profile,
                   2603: #                      The 'namespace' which selects the gdbm file to 
                   2604: #                      do the lookup in, 
                   2605: #                      & separated list of keys to lookup.  Note that
                   2606: #                      the values are returned as an & separated list too.
                   2607: #   $client          - File descriptor open on the client.
                   2608: # Returns:
                   2609: #   1       - Continue processing.
                   2610: #   0       - Exit.
                   2611: #
                   2612: sub get_profile_entry {
                   2613:     my ($cmd, $tail, $client) = @_;
                   2614: 
                   2615:     my $userinput= "$cmd:$tail";
                   2616:    
                   2617:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2618:     chomp($what);
1.255     foxr     2619: 
                   2620:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   2621:     my ($first) = split(/:/,$replystring);
                   2622:     if($first ne "error") {
                   2623: 	&Reply($client, "$replystring\n", $userinput);
1.231     foxr     2624:     } else {
1.255     foxr     2625: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     2626:     }
                   2627:     return 1;
1.255     foxr     2628: 
                   2629: 
1.231     foxr     2630: }
                   2631: &register_handler("get", \&get_profile_entry, 0,1,0);
                   2632: 
                   2633: #
                   2634: #  Process the encrypted get request.  Note that the request is sent
                   2635: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   2636: #  information about the sensitive keys is given to the snooper.  Just not
                   2637: #  information about the values of the sensitive key.  Hmm if I wanted to
                   2638: #  know these I'd snoop for the egets. Get the profile item names from them
                   2639: #  and then issue a get for them since there's no enforcement of the
                   2640: #  requirement of an encrypted get for particular profile items.  If I
                   2641: #  were re-doing this, I'd force the request to be encrypted as well as the
                   2642: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   2643: #  that would prevent any covert channel snooping.
                   2644: #
                   2645: #  Parameters:
                   2646: #     $cmd               - Command keyword of request (eget).
                   2647: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
                   2648: #     $client            - File open on the client.
                   2649: #  Returns:
                   2650: #     1      - Continue processing
                   2651: #     0      - server should exit.
                   2652: sub get_profile_entry_encrypted {
                   2653:     my ($cmd, $tail, $client) = @_;
                   2654: 
                   2655:     my $userinput = "$cmd:$tail";
                   2656:    
                   2657:     my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
                   2658:     chomp($what);
1.255     foxr     2659:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   2660:     my ($first) = split(/:/, $qresult);
                   2661:     if($first ne "error") {
                   2662: 	
                   2663: 	if ($cipher) {
                   2664: 	    my $cmdlength=length($qresult);
                   2665: 	    $qresult.="         ";
                   2666: 	    my $encqresult='';
                   2667: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   2668: 		$encqresult.= unpack("H16", 
                   2669: 				     $cipher->encrypt(substr($qresult,
                   2670: 							     $encidx,
                   2671: 							     8)));
                   2672: 	    }
                   2673: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   2674: 	} else {
1.231     foxr     2675: 		&Failure( $client, "error:no_key\n", $userinput);
                   2676: 	    }
                   2677:     } else {
1.255     foxr     2678: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   2679: 
1.231     foxr     2680:     }
                   2681:     
                   2682:     return 1;
                   2683: }
1.255     foxr     2684: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 2685: 
1.231     foxr     2686: #
                   2687: #   Deletes a key in a user profile database.
                   2688: #   
                   2689: #   Parameters:
                   2690: #       $cmd                  - Command keyword (del).
                   2691: #       $tail                 - Command tail.  IN this case a colon
                   2692: #                               separated list containing:
                   2693: #                               The domain and user that identifies uniquely
                   2694: #                               the identity of the user.
                   2695: #                               The profile namespace (name of the profile
                   2696: #                               database file).
                   2697: #                               & separated list of keywords to delete.
                   2698: #       $client              - File open on client socket.
                   2699: # Returns:
                   2700: #     1   - Continue processing
                   2701: #     0   - Exit server.
                   2702: #
                   2703: #
                   2704: sub delete_profile_entry {
                   2705:     my ($cmd, $tail, $client) = @_;
                   2706: 
                   2707:     my $userinput = "cmd:$tail";
                   2708: 
                   2709:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   2710:     chomp($what);
                   2711:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2712: 				 &GDBM_WRCREAT(),
                   2713: 				 "D",$what);
                   2714:     if ($hashref) {
                   2715:         my @keys=split(/\&/,$what);
                   2716: 	foreach my $key (@keys) {
                   2717: 	    delete($hashref->{$key});
                   2718: 	}
                   2719: 	if (untie(%$hashref)) {
                   2720: 	    &Reply($client, "ok\n", $userinput);
                   2721: 	} else {
                   2722: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2723: 		    "while attempting del\n", $userinput);
                   2724: 	}
                   2725:     } else {
                   2726: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2727: 		 "while attempting del\n", $userinput);
                   2728:     }
                   2729:     return 1;
                   2730: }
                   2731: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 2732: 
1.231     foxr     2733: #
                   2734: #  List the set of keys that are defined in a profile database file.
                   2735: #  A successful reply from this will contain an & separated list of
                   2736: #  the keys. 
                   2737: # Parameters:
                   2738: #     $cmd              - Command request (keys).
                   2739: #     $tail             - Remainder of the request, a colon separated
                   2740: #                         list containing domain/user that identifies the
                   2741: #                         user being queried, and the database namespace
                   2742: #                         (database filename essentially).
                   2743: #     $client           - File open on the client.
                   2744: #  Returns:
                   2745: #    1    - Continue processing.
                   2746: #    0    - Exit the server.
                   2747: #
                   2748: sub get_profile_keys {
                   2749:     my ($cmd, $tail, $client) = @_;
                   2750: 
                   2751:     my $userinput = "$cmd:$tail";
                   2752: 
                   2753:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   2754:     my $qresult='';
                   2755:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2756: 				  &GDBM_READER());
                   2757:     if ($hashref) {
                   2758: 	foreach my $key (keys %$hashref) {
                   2759: 	    $qresult.="$key&";
                   2760: 	}
                   2761: 	if (untie(%$hashref)) {
                   2762: 	    $qresult=~s/\&$//;
                   2763: 	    &Reply($client, "$qresult\n", $userinput);
                   2764: 	} else {
                   2765: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2766: 		    "while attempting keys\n", $userinput);
                   2767: 	}
                   2768:     } else {
                   2769: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2770: 		 "while attempting keys\n", $userinput);
                   2771:     }
                   2772:    
                   2773:     return 1;
                   2774: }
                   2775: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   2776: 
                   2777: #
                   2778: #   Dump the contents of a user profile database.
                   2779: #   Note that this constitutes a very large covert channel too since
                   2780: #   the dump will return sensitive information that is not encrypted.
                   2781: #   The naive security assumption is that the session negotiation ensures
                   2782: #   our client is trusted and I don't believe that's assured at present.
                   2783: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   2784: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   2785: # 
                   2786: #  Parameters:
                   2787: #     $cmd           - The command request keyword (currentdump).
                   2788: #     $tail          - Remainder of the request, consisting of a colon
                   2789: #                      separated list that has the domain/username and
                   2790: #                      the namespace to dump (database file).
                   2791: #     $client        - file open on the remote client.
                   2792: # Returns:
                   2793: #     1    - Continue processing.
                   2794: #     0    - Exit the server.
                   2795: #
                   2796: sub dump_profile_database {
                   2797:     my ($cmd, $tail, $client) = @_;
                   2798: 
                   2799:     my $userinput = "$cmd:$tail";
                   2800:    
                   2801:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   2802:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2803: 				 &GDBM_READER());
                   2804:     if ($hashref) {
                   2805: 	# Structure of %data:
                   2806: 	# $data{$symb}->{$parameter}=$value;
                   2807: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   2808: 	# since $parameter will be unescaped, we do not
                   2809:  	# have to worry about silly parameter names...
                   2810: 	
                   2811:         my $qresult='';
                   2812: 	my %data = ();                     # A hash of anonymous hashes..
                   2813: 	while (my ($key,$value) = each(%$hashref)) {
                   2814: 	    my ($v,$symb,$param) = split(/:/,$key);
                   2815: 	    next if ($v eq 'version' || $symb eq 'keys');
                   2816: 	    next if (exists($data{$symb}) && 
                   2817: 		     exists($data{$symb}->{$param}) &&
                   2818: 		     $data{$symb}->{'v.'.$param} > $v);
                   2819: 	    $data{$symb}->{$param}=$value;
                   2820: 	    $data{$symb}->{'v.'.$param}=$v;
                   2821: 	}
                   2822: 	if (untie(%$hashref)) {
                   2823: 	    while (my ($symb,$param_hash) = each(%data)) {
                   2824: 		while(my ($param,$value) = each (%$param_hash)){
                   2825: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   2826: 		    #
                   2827: 		    #   Just dump the symb=value pairs separated by &
                   2828: 		    #
                   2829: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   2830: 		}
                   2831: 	    }
                   2832: 	    chop($qresult);
                   2833: 	    &Reply($client , "$qresult\n", $userinput);
                   2834: 	} else {
                   2835: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2836: 		     "while attempting currentdump\n", $userinput);
                   2837: 	}
                   2838:     } else {
                   2839: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2840: 		"while attempting currentdump\n", $userinput);
                   2841:     }
                   2842: 
                   2843:     return 1;
                   2844: }
                   2845: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   2846: 
                   2847: #
                   2848: #   Dump a profile database with an optional regular expression
                   2849: #   to match against the keys.  In this dump, no effort is made
                   2850: #   to separate symb from version information. Presumably the
                   2851: #   databases that are dumped by this command are of a different
                   2852: #   structure.  Need to look at this and improve the documentation of
                   2853: #   both this and the currentdump handler.
                   2854: # Parameters:
                   2855: #    $cmd                     - The command keyword.
                   2856: #    $tail                    - All of the characters after the $cmd:
                   2857: #                               These are expected to be a colon
                   2858: #                               separated list containing:
                   2859: #                               domain/user - identifying the user.
                   2860: #                               namespace   - identifying the database.
                   2861: #                               regexp      - optional regular expression
                   2862: #                                             that is matched against
                   2863: #                                             database keywords to do
                   2864: #                                             selective dumps.
                   2865: #   $client                   - Channel open on the client.
                   2866: # Returns:
                   2867: #    1    - Continue processing.
                   2868: # Side effects:
                   2869: #    response is written to $client.
                   2870: #
                   2871: sub dump_with_regexp {
                   2872:     my ($cmd, $tail, $client) = @_;
                   2873: 
                   2874: 
                   2875:     my $userinput = "$cmd:$tail";
                   2876: 
                   2877:     my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);
                   2878:     if (defined($regexp)) {
                   2879: 	$regexp=&unescape($regexp);
                   2880:     } else {
                   2881: 	$regexp='.';
                   2882:     }
                   2883:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2884: 				 &GDBM_READER());
                   2885:     if ($hashref) {
                   2886:         my $qresult='';
                   2887: 	while (my ($key,$value) = each(%$hashref)) {
                   2888: 	    if ($regexp eq '.') {
                   2889: 		$qresult.=$key.'='.$value.'&';
                   2890: 	    } else {
                   2891: 		my $unescapeKey = &unescape($key);
                   2892: 		if (eval('$unescapeKey=~/$regexp/')) {
                   2893: 		    $qresult.="$key=$value&";
                   2894: 		}
                   2895: 	    }
                   2896: 	}
                   2897: 	if (untie(%$hashref)) {
                   2898: 	    chop($qresult);
                   2899: 	    &Reply($client, "$qresult\n", $userinput);
                   2900: 	} else {
                   2901: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2902: 		     "while attempting dump\n", $userinput);
                   2903: 	}
                   2904:     } else {
                   2905: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2906: 		"while attempting dump\n", $userinput);
                   2907:     }
                   2908: 
                   2909:     return 1;
                   2910: }
                   2911: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   2912: 
                   2913: #  Store a set of key=value pairs associated with a versioned name.
                   2914: #
                   2915: #  Parameters:
                   2916: #    $cmd                - Request command keyword.
                   2917: #    $tail               - Tail of the request.  This is a colon
                   2918: #                          separated list containing:
                   2919: #                          domain/user - User and authentication domain.
                   2920: #                          namespace   - Name of the database being modified
                   2921: #                          rid         - Resource keyword to modify.
                   2922: #                          what        - new value associated with rid.
                   2923: #
                   2924: #    $client             - Socket open on the client.
                   2925: #
                   2926: #
                   2927: #  Returns:
                   2928: #      1 (keep on processing).
                   2929: #  Side-Effects:
                   2930: #    Writes to the client
                   2931: sub store_handler {
                   2932:     my ($cmd, $tail, $client) = @_;
                   2933:  
                   2934:     my $userinput = "$cmd:$tail";
                   2935: 
                   2936:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
                   2937:     if ($namespace ne 'roles') {
                   2938: 
                   2939: 	chomp($what);
                   2940: 	my @pairs=split(/\&/,$what);
                   2941: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 2942: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     2943: 				       "$rid:$what");
                   2944: 	if ($hashref) {
                   2945: 	    my $now = time;
                   2946: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
                   2947: 	    my $key;
                   2948: 	    $hashref->{"version:$rid"}++;
                   2949: 	    my $version=$hashref->{"version:$rid"};
                   2950: 	    my $allkeys=''; 
                   2951: 	    foreach my $pair (@pairs) {
                   2952: 		my ($key,$value)=split(/=/,$pair);
                   2953: 		$allkeys.=$key.':';
                   2954: 		$hashref->{"$version:$rid:$key"}=$value;
                   2955: 	    }
                   2956: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   2957: 	    $allkeys.='timestamp';
                   2958: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
                   2959: 	    if (untie($hashref)) {
                   2960: 		&Reply($client, "ok\n", $userinput);
                   2961: 	    } else {
                   2962: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   2963: 			"while attempting store\n", $userinput);
                   2964: 	    }
                   2965: 	} else {
                   2966: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   2967: 		     "while attempting store\n", $userinput);
                   2968: 	}
                   2969:     } else {
                   2970: 	&Failure($client, "refused\n", $userinput);
                   2971:     }
                   2972: 
                   2973:     return 1;
                   2974: }
                   2975: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 2976: 
1.231     foxr     2977: #
                   2978: #  Dump out all versions of a resource that has key=value pairs associated
                   2979: # with it for each version.  These resources are built up via the store
                   2980: # command.
                   2981: #
                   2982: #  Parameters:
                   2983: #     $cmd               - Command keyword.
                   2984: #     $tail              - Remainder of the request which consists of:
                   2985: #                          domain/user   - User and auth. domain.
                   2986: #                          namespace     - name of resource database.
                   2987: #                          rid           - Resource id.
                   2988: #    $client             - socket open on the client.
                   2989: #
                   2990: # Returns:
                   2991: #      1  indicating the caller should not yet exit.
                   2992: # Side-effects:
                   2993: #   Writes a reply to the client.
                   2994: #   The reply is a string of the following shape:
                   2995: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   2996: #    Where the 1 above represents version 1.
                   2997: #    this continues for all pairs of keys in all versions.
                   2998: #
                   2999: #
                   3000: #    
                   3001: #
                   3002: sub restore_handler {
                   3003:     my ($cmd, $tail, $client) = @_;
                   3004: 
                   3005:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
                   3006: 
                   3007:     my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
                   3008:     $namespace=~s/\//\_/g;
                   3009:     $namespace=~s/\W//g;
                   3010:     chomp($rid);
                   3011:     my $proname=&propath($udom,$uname);
                   3012:     my $qresult='';
                   3013:     my %hash;
                   3014:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
                   3015: 	    &GDBM_READER(),0640)) {
                   3016: 	my $version=$hash{"version:$rid"};
                   3017: 	$qresult.="version=$version&";
                   3018: 	my $scope;
                   3019: 	for ($scope=1;$scope<=$version;$scope++) {
                   3020: 	    my $vkeys=$hash{"$scope:keys:$rid"};
                   3021: 	    my @keys=split(/:/,$vkeys);
                   3022: 	    my $key;
                   3023: 	    $qresult.="$scope:keys=$vkeys&";
                   3024: 	    foreach $key (@keys) {
                   3025: 		$qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
                   3026: 	    }                                  
                   3027: 	}
                   3028: 	if (untie(%hash)) {
                   3029: 	    $qresult=~s/\&$//;
                   3030: 	    &Reply( $client, "$qresult\n", $userinput);
                   3031: 	} else {
                   3032: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3033: 		    "while attempting restore\n", $userinput);
                   3034: 	}
                   3035:     } else {
                   3036: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3037: 		"while attempting restore\n", $userinput);
                   3038:     }
                   3039:   
                   3040:     return 1;
                   3041: 
                   3042: 
                   3043: }
                   3044: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3045: 
                   3046: #
                   3047: #   Add a chat message to to a discussion board.
                   3048: #
                   3049: # Parameters:
                   3050: #    $cmd                - Request keyword.
                   3051: #    $tail               - Tail of the command. A colon separated list
                   3052: #                          containing:
                   3053: #                          cdom    - Domain on which the chat board lives
                   3054: #                          cnum    - Identifier of the discussion group.
                   3055: #                          post    - Body of the posting.
                   3056: #   $client              - Socket open on the client.
                   3057: # Returns:
                   3058: #   1    - Indicating caller should keep on processing.
                   3059: #
                   3060: # Side-effects:
                   3061: #   writes a reply to the client.
                   3062: #
                   3063: #
                   3064: sub send_chat_handler {
                   3065:     my ($cmd, $tail, $client) = @_;
                   3066: 
                   3067:     
                   3068:     my $userinput = "$cmd:$tail";
                   3069: 
                   3070:     my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
                   3071:     &chat_add($cdom,$cnum,$newpost);
                   3072:     &Reply($client, "ok\n", $userinput);
                   3073: 
                   3074:     return 1;
                   3075: }
                   3076: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3077: 
1.234     foxr     3078: #
                   3079: #   Retrieve the set of chat messagss from a discussion board.
                   3080: #
                   3081: #  Parameters:
                   3082: #    $cmd             - Command keyword that initiated the request.
                   3083: #    $tail            - Remainder of the request after the command
                   3084: #                       keyword.  In this case a colon separated list of
                   3085: #                       chat domain    - Which discussion board.
                   3086: #                       chat id        - Discussion thread(?)
                   3087: #                       domain/user    - Authentication domain and username
                   3088: #                                        of the requesting person.
                   3089: #   $client           - Socket open on the client program.
                   3090: # Returns:
                   3091: #    1     - continue processing
                   3092: # Side effects:
                   3093: #    Response is written to the client.
                   3094: #
                   3095: sub retrieve_chat_handler {
                   3096:     my ($cmd, $tail, $client) = @_;
                   3097: 
                   3098: 
                   3099:     my $userinput = "$cmd:$tail";
                   3100: 
                   3101:     my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
                   3102:     my $reply='';
                   3103:     foreach (&get_chat($cdom,$cnum,$udom,$uname)) {
                   3104: 	$reply.=&escape($_).':';
                   3105:     }
                   3106:     $reply=~s/\:$//;
                   3107:     &Reply($client, $reply."\n", $userinput);
                   3108: 
                   3109: 
                   3110:     return 1;
                   3111: }
                   3112: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3113: 
                   3114: #
                   3115: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3116: #  a file for later retrieval.  This prevents sql query results from
                   3117: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3118: #  less of an issue since multiple outstanding requests can be concurrently
                   3119: #  serviced.
                   3120: #
                   3121: #  Parameters:
                   3122: #     $cmd       - COmmand keyword that initiated the request.
                   3123: #     $tail      - Remainder of the command after the keyword.
                   3124: #                  For this function, this consists of a query and
                   3125: #                  3 arguments that are self-documentingly labelled
                   3126: #                  in the original arg1, arg2, arg3.
                   3127: #     $client    - Socket open on the client.
                   3128: # Return:
                   3129: #    1   - Indicating processing should continue.
                   3130: # Side-effects:
                   3131: #    a reply is written to $client.
                   3132: #
                   3133: sub send_query_handler {
                   3134:     my ($cmd, $tail, $client) = @_;
                   3135: 
                   3136: 
                   3137:     my $userinput = "$cmd:$tail";
                   3138: 
                   3139:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3140:     $query=~s/\n*$//g;
                   3141:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   3142: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   3143: 	  $userinput);
                   3144:     
                   3145:     return 1;
                   3146: }
                   3147: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   3148: 
                   3149: #
                   3150: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   3151: #   The query is submitted via a "querysend" transaction.
                   3152: #   There it is passed on to the lonsql daemon, queued and issued to
                   3153: #   mysql.
                   3154: #     This transaction is invoked when the sql transaction is complete
                   3155: #   it stores the query results in flie and indicates query completion.
                   3156: #   presumably local software then fetches this response... I'm guessing
                   3157: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   3158: #   lonsql on completion of the query interacts with the lond of our
                   3159: #   client to do a query reply storing two files:
                   3160: #    - id     - The results of the query.
                   3161: #    - id.end - Indicating the transaction completed. 
                   3162: #    NOTE: id is a unique id assigned to the query and querysend time.
                   3163: # Parameters:
                   3164: #    $cmd        - Command keyword that initiated this request.
                   3165: #    $tail       - Remainder of the tail.  In this case that's a colon
                   3166: #                  separated list containing the query Id and the 
                   3167: #                  results of the query.
                   3168: #    $client     - Socket open on the client.
                   3169: # Return:
                   3170: #    1           - Indicating that we should continue processing.
                   3171: # Side effects:
                   3172: #    ok written to the client.
                   3173: #
                   3174: sub reply_query_handler {
                   3175:     my ($cmd, $tail, $client) = @_;
                   3176: 
                   3177: 
                   3178:     my $userinput = "$cmd:$tail";
                   3179: 
                   3180:     my ($cmd,$id,$reply)=split(/:/,$userinput); 
                   3181:     my $store;
                   3182:     my $execdir=$perlvar{'lonDaemons'};
                   3183:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   3184: 	$reply=~s/\&/\n/g;
                   3185: 	print $store $reply;
                   3186: 	close $store;
                   3187: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   3188: 	print $store2 "done\n";
                   3189: 	close $store2;
                   3190: 	&Reply($client, "ok\n", $userinput);
                   3191:     } else {
                   3192: 	&Failure($client, "error: ".($!+0)
                   3193: 		." IO::File->new Failed ".
                   3194: 		"while attempting queryreply\n", $userinput);
                   3195:     }
                   3196:  
                   3197: 
                   3198:     return 1;
                   3199: }
                   3200: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   3201: 
                   3202: #
                   3203: #  Process the courseidput request.  Not quite sure what this means
                   3204: #  at the system level sense.  It appears a gdbm file in the 
                   3205: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   3206: #  a set of entries made in that database.
                   3207: #
                   3208: # Parameters:
                   3209: #   $cmd      - The command keyword that initiated this request.
                   3210: #   $tail     - Tail of the command.  In this case consists of a colon
                   3211: #               separated list contaning the domain to apply this to and
                   3212: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  3213: #               Each value is a colon separated list that includes:  
                   3214: #               description, institutional code and course owner.
                   3215: #               For backward compatibility with versions included
                   3216: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   3217: #               code and/or course owner are preserved from the existing 
                   3218: #               record when writing a new record in response to 1.1 or 
                   3219: #               1.2 implementations of lonnet::flushcourselogs().   
                   3220: #                      
1.234     foxr     3221: #   $client   - Socket open on the client.
                   3222: # Returns:
                   3223: #   1    - indicating that processing should continue
                   3224: #
                   3225: # Side effects:
                   3226: #   reply is written to the client.
                   3227: #
                   3228: sub put_course_id_handler {
                   3229:     my ($cmd, $tail, $client) = @_;
                   3230: 
                   3231: 
                   3232:     my $userinput = "$cmd:$tail";
                   3233: 
1.266     raeburn  3234:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     3235:     chomp($what);
                   3236:     my $now=time;
                   3237:     my @pairs=split(/\&/,$what);
                   3238: 
                   3239:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3240:     if ($hashref) {
                   3241: 	foreach my $pair (@pairs) {
1.271     raeburn  3242:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   3243:             $courseinfo =~ s/=/:/g;
1.272     raeburn  3244: 
1.273     albertel 3245:             my @current_items = split(/:/,$hashref->{$key});
                   3246:             shift(@current_items); # remove description
                   3247:             pop(@current_items);   # remove last access
1.272     raeburn  3248:             my $numcurrent = scalar(@current_items);
                   3249: 
1.273     albertel 3250:             my @new_items = split(/:/,$courseinfo);
1.272     raeburn  3251:             my $numnew = scalar(@new_items);
                   3252:             if ($numcurrent > 0) {
                   3253:                 if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
                   3254:                     $courseinfo .= ':'.join(':',@current_items);
                   3255:                 } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
                   3256:                     $courseinfo .= ':'.$current_items[$numcurrent-1];
                   3257:                 }
                   3258:             }
1.266     raeburn  3259: 	    $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     3260: 	}
                   3261: 	if (untie(%$hashref)) {
1.253     foxr     3262: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     3263: 	} else {
1.253     foxr     3264: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     3265: 		     ." untie(GDBM) Failed ".
                   3266: 		     "while attempting courseidput\n", $userinput);
                   3267: 	}
                   3268:     } else {
1.253     foxr     3269: 	&Failure($client, "error: ".($!+0)
1.234     foxr     3270: 		 ." tie(GDBM) Failed ".
                   3271: 		 "while attempting courseidput\n", $userinput);
                   3272:     }
1.253     foxr     3273:     
1.234     foxr     3274: 
                   3275:     return 1;
                   3276: }
                   3277: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   3278: 
                   3279: #  Retrieves the value of a course id resource keyword pattern
                   3280: #  defined since a starting date.  Both the starting date and the
                   3281: #  keyword pattern are optional.  If the starting date is not supplied it
                   3282: #  is treated as the beginning of time.  If the pattern is not found,
                   3283: #  it is treatred as "." matching everything.
                   3284: #
                   3285: #  Parameters:
                   3286: #     $cmd     - Command keyword that resulted in us being dispatched.
                   3287: #     $tail    - The remainder of the command that, in this case, consists
                   3288: #                of a colon separated list of:
                   3289: #                 domain   - The domain in which the course database is 
                   3290: #                            defined.
                   3291: #                 since    - Optional parameter describing the minimum
                   3292: #                            time of definition(?) of the resources that
                   3293: #                            will match the dump.
                   3294: #                 description - regular expression that is used to filter
                   3295: #                            the dump.  Only keywords matching this regexp
                   3296: #                            will be used.
1.272     raeburn  3297: #                 institutional code - optional supplied code to filter 
                   3298: #                            the dump. Only courses with an institutional code 
                   3299: #                            that match the supplied code will be returned.
                   3300: #                 owner    - optional supplied username of owner to filter
                   3301: #                            the dump.  Only courses for which the course 
                   3302: #                            owner matches the supplied username will be
1.274     albertel 3303: #                            returned. Implicit assumption that owner
                   3304: #                            is a user in the domain in which the
                   3305: #                            course database is defined.
1.234     foxr     3306: #     $client  - The socket open on the client.
                   3307: # Returns:
                   3308: #    1     - Continue processing.
                   3309: # Side Effects:
                   3310: #   a reply is written to $client.
                   3311: sub dump_course_id_handler {
                   3312:     my ($cmd, $tail, $client) = @_;
                   3313: 
                   3314:     my $userinput = "$cmd:$tail";
                   3315: 
1.282     raeburn  3316:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter) =split(/:/,$tail);
1.234     foxr     3317:     if (defined($description)) {
                   3318: 	$description=&unescape($description);
                   3319:     } else {
                   3320: 	$description='.';
                   3321:     }
1.266     raeburn  3322:     if (defined($instcodefilter)) {
                   3323:         $instcodefilter=&unescape($instcodefilter);
                   3324:     } else {
                   3325:         $instcodefilter='.';
                   3326:     }
                   3327:     if (defined($ownerfilter)) {
                   3328:         $ownerfilter=&unescape($ownerfilter);
                   3329:     } else {
                   3330:         $ownerfilter='.';
                   3331:     }
1.282     raeburn  3332:     if (defined($coursefilter)) {
                   3333:         $coursefilter=&unescape($coursefilter);
                   3334:     } else {
                   3335:         $coursefilter='.';
                   3336:     }
1.266     raeburn  3337: 
1.234     foxr     3338:     unless (defined($since)) { $since=0; }
                   3339:     my $qresult='';
                   3340:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3341:     if ($hashref) {
                   3342: 	while (my ($key,$value) = each(%$hashref)) {
1.266     raeburn  3343: 	    my ($descr,$lasttime,$inst_code,$owner);
1.274     albertel 3344:             my @courseitems = split(/:/,$value);
                   3345:             $lasttime = pop(@courseitems);
                   3346: 	    ($descr,$inst_code,$owner)=@courseitems;
1.234     foxr     3347: 	    if ($lasttime<$since) { next; }
1.266     raeburn  3348:             my $match = 1;
                   3349: 	    unless ($description eq '.') {
                   3350: 		my $unescapeDescr = &unescape($descr);
                   3351: 		unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
                   3352:                     $match = 0;
1.234     foxr     3353: 		}
1.266     raeburn  3354:             }
                   3355:             unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
                   3356:                 my $unescapeInstcode = &unescape($inst_code);
                   3357:                 unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
                   3358:                     $match = 0;
                   3359:                 }
1.234     foxr     3360: 	    }
1.266     raeburn  3361:             unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
                   3362:                 my $unescapeOwner = &unescape($owner);
                   3363:                 unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
                   3364:                     $match = 0;
                   3365:                 }
                   3366:             }
1.282     raeburn  3367:             unless ($coursefilter eq '.' || !defined($coursefilter)) {
                   3368:                 my $unescapeCourse = &unescape($key);
                   3369:                 unless (eval('$unescapeCourse=~/^$udom(_)\Q$coursefilter\E$/')) {
                   3370:                     $match = 0;
                   3371:                 }
                   3372:             }
1.266     raeburn  3373:             if ($match == 1) {
                   3374:                 $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
                   3375:             }
1.234     foxr     3376: 	}
                   3377: 	if (untie(%$hashref)) {
                   3378: 	    chop($qresult);
                   3379: 	    &Reply($client, "$qresult\n", $userinput);
                   3380: 	} else {
                   3381: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3382: 		    "while attempting courseiddump\n", $userinput);
                   3383: 	}
                   3384:     } else {
                   3385: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3386: 		"while attempting courseiddump\n", $userinput);
                   3387:     }
                   3388: 
                   3389: 
                   3390:     return 1;
                   3391: }
                   3392: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     3393: 
                   3394: #
                   3395: #  Puts an id to a domains id database. 
                   3396: #
                   3397: #  Parameters:
                   3398: #   $cmd     - The command that triggered us.
                   3399: #   $tail    - Remainder of the request other than the command. This is a 
                   3400: #              colon separated list containing:
                   3401: #              $domain  - The domain for which we are writing the id.
                   3402: #              $pairs  - The id info to write... this is and & separated list
                   3403: #                        of keyword=value.
                   3404: #   $client  - Socket open on the client.
                   3405: #  Returns:
                   3406: #    1   - Continue processing.
                   3407: #  Side effects:
                   3408: #     reply is written to $client.
                   3409: #
                   3410: sub put_id_handler {
                   3411:     my ($cmd,$tail,$client) = @_;
                   3412: 
                   3413: 
                   3414:     my $userinput = "$cmd:$tail";
                   3415: 
                   3416:     my ($udom,$what)=split(/:/,$tail);
                   3417:     chomp($what);
                   3418:     my @pairs=split(/\&/,$what);
                   3419:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   3420: 				   "P", $what);
                   3421:     if ($hashref) {
                   3422: 	foreach my $pair (@pairs) {
                   3423: 	    my ($key,$value)=split(/=/,$pair);
                   3424: 	    $hashref->{$key}=$value;
                   3425: 	}
                   3426: 	if (untie(%$hashref)) {
                   3427: 	    &Reply($client, "ok\n", $userinput);
                   3428: 	} else {
                   3429: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3430: 		     "while attempting idput\n", $userinput);
                   3431: 	}
                   3432:     } else {
                   3433: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3434: 		  "while attempting idput\n", $userinput);
                   3435:     }
                   3436: 
                   3437:     return 1;
                   3438: }
1.263     albertel 3439: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     3440: 
                   3441: #
                   3442: #  Retrieves a set of id values from the id database.
                   3443: #  Returns an & separated list of results, one for each requested id to the
                   3444: #  client.
                   3445: #
                   3446: # Parameters:
                   3447: #   $cmd       - Command keyword that caused us to be dispatched.
                   3448: #   $tail      - Tail of the command.  Consists of a colon separated:
                   3449: #               domain - the domain whose id table we dump
                   3450: #               ids      Consists of an & separated list of
                   3451: #                        id keywords whose values will be fetched.
                   3452: #                        nonexisting keywords will have an empty value.
                   3453: #   $client    - Socket open on the client.
                   3454: #
                   3455: # Returns:
                   3456: #    1 - indicating processing should continue.
                   3457: # Side effects:
                   3458: #   An & separated list of results is written to $client.
                   3459: #
                   3460: sub get_id_handler {
                   3461:     my ($cmd, $tail, $client) = @_;
                   3462: 
                   3463:     
                   3464:     my $userinput = "$client:$tail";
                   3465:     
                   3466:     my ($udom,$what)=split(/:/,$tail);
                   3467:     chomp($what);
                   3468:     my @queries=split(/\&/,$what);
                   3469:     my $qresult='';
                   3470:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   3471:     if ($hashref) {
                   3472: 	for (my $i=0;$i<=$#queries;$i++) {
                   3473: 	    $qresult.="$hashref->{$queries[$i]}&";
                   3474: 	}
                   3475: 	if (untie(%$hashref)) {
                   3476: 	    $qresult=~s/\&$//;
                   3477: 	    &Reply($client, "$qresult\n", $userinput);
                   3478: 	} else {
                   3479: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3480: 		      "while attempting idget\n",$userinput);
                   3481: 	}
                   3482:     } else {
                   3483: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3484: 		 "while attempting idget\n",$userinput);
                   3485:     }
                   3486:     
                   3487:     return 1;
                   3488: }
1.263     albertel 3489: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     3490: 
                   3491: #
                   3492: #  Process the tmpput command I'm not sure what this does.. Seems to
                   3493: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   3494: # where Id is the client's ip concatenated with a sequence number.
                   3495: # The file will contain some value that is passed in.  Is this e.g.
                   3496: # a login token?
                   3497: #
                   3498: # Parameters:
                   3499: #    $cmd     - The command that got us dispatched.
                   3500: #    $tail    - The remainder of the request following $cmd:
                   3501: #               In this case this will be the contents of the file.
                   3502: #    $client  - Socket connected to the client.
                   3503: # Returns:
                   3504: #    1 indicating processing can continue.
                   3505: # Side effects:
                   3506: #   A file is created in the local filesystem.
                   3507: #   A reply is sent to the client.
                   3508: sub tmp_put_handler {
                   3509:     my ($cmd, $what, $client) = @_;
                   3510: 
                   3511:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   3512: 
                   3513: 
                   3514:     my $store;
                   3515:     $tmpsnum++;
                   3516:     my $id=$$.'_'.$clientip.'_'.$tmpsnum;
                   3517:     $id=~s/\W/\_/g;
                   3518:     $what=~s/\n//g;
                   3519:     my $execdir=$perlvar{'lonDaemons'};
                   3520:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
                   3521: 	print $store $what;
                   3522: 	close $store;
                   3523: 	&Reply($client, "$id\n", $userinput);
                   3524:     } else {
                   3525: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   3526: 		  "while attempting tmpput\n", $userinput);
                   3527:     }
                   3528:     return 1;
                   3529:   
                   3530: }
                   3531: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 3532: 
1.238     foxr     3533: #   Processes the tmpget command.  This command returns the contents
                   3534: #  of a temporary resource file(?) created via tmpput.
                   3535: #
                   3536: # Paramters:
                   3537: #    $cmd      - Command that got us dispatched.
                   3538: #    $id       - Tail of the command, contain the id of the resource
                   3539: #                we want to fetch.
                   3540: #    $client   - socket open on the client.
                   3541: # Return:
                   3542: #    1         - Inidcating processing can continue.
                   3543: # Side effects:
                   3544: #   A reply is sent to the client.
                   3545: #
                   3546: sub tmp_get_handler {
                   3547:     my ($cmd, $id, $client) = @_;
                   3548: 
                   3549:     my $userinput = "$cmd:$id"; 
                   3550:     
                   3551: 
                   3552:     $id=~s/\W/\_/g;
                   3553:     my $store;
                   3554:     my $execdir=$perlvar{'lonDaemons'};
                   3555:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   3556: 	my $reply=<$store>;
                   3557: 	&Reply( $client, "$reply\n", $userinput);
                   3558: 	close $store;
                   3559:     } else {
                   3560: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   3561: 		  "while attempting tmpget\n", $userinput);
                   3562:     }
                   3563: 
                   3564:     return 1;
                   3565: }
                   3566: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 3567: 
1.238     foxr     3568: #
                   3569: #  Process the tmpdel command.  This command deletes a temp resource
                   3570: #  created by the tmpput command.
                   3571: #
                   3572: # Parameters:
                   3573: #   $cmd      - Command that got us here.
                   3574: #   $id       - Id of the temporary resource created.
                   3575: #   $client   - socket open on the client process.
                   3576: #
                   3577: # Returns:
                   3578: #   1     - Indicating processing should continue.
                   3579: # Side Effects:
                   3580: #   A file is deleted
                   3581: #   A reply is sent to the client.
                   3582: sub tmp_del_handler {
                   3583:     my ($cmd, $id, $client) = @_;
                   3584:     
                   3585:     my $userinput= "$cmd:$id";
                   3586:     
                   3587:     chomp($id);
                   3588:     $id=~s/\W/\_/g;
                   3589:     my $execdir=$perlvar{'lonDaemons'};
                   3590:     if (unlink("$execdir/tmp/$id.tmp")) {
                   3591: 	&Reply($client, "ok\n", $userinput);
                   3592:     } else {
                   3593: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   3594: 		  "while attempting tmpdel\n", $userinput);
                   3595:     }
                   3596:     
                   3597:     return 1;
                   3598: 
                   3599: }
                   3600: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 3601: 
1.238     foxr     3602: #
1.246     foxr     3603: #   Processes the setannounce command.  This command
                   3604: #   creates a file named announce.txt in the top directory of
                   3605: #   the documentn root and sets its contents.  The announce.txt file is
                   3606: #   printed in its entirety at the LonCAPA login page.  Note:
                   3607: #   once the announcement.txt fileis created it cannot be deleted.
                   3608: #   However, setting the contents of the file to empty removes the
                   3609: #   announcement from the login page of loncapa so who cares.
                   3610: #
                   3611: # Parameters:
                   3612: #    $cmd          - The command that got us dispatched.
                   3613: #    $announcement - The text of the announcement.
                   3614: #    $client       - Socket open on the client process.
                   3615: # Retunrns:
                   3616: #   1             - Indicating request processing should continue
                   3617: # Side Effects:
                   3618: #   The file {DocRoot}/announcement.txt is created.
                   3619: #   A reply is sent to $client.
                   3620: #
                   3621: sub set_announce_handler {
                   3622:     my ($cmd, $announcement, $client) = @_;
                   3623:   
                   3624:     my $userinput    = "$cmd:$announcement";
                   3625: 
                   3626:     chomp($announcement);
                   3627:     $announcement=&unescape($announcement);
                   3628:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   3629: 				'/announcement.txt')) {
                   3630: 	print $store $announcement;
                   3631: 	close $store;
                   3632: 	&Reply($client, "ok\n", $userinput);
                   3633:     } else {
                   3634: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   3635:     }
                   3636: 
                   3637:     return 1;
                   3638: }
                   3639: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 3640: 
1.246     foxr     3641: #
                   3642: #  Return the version of the daemon.  This can be used to determine
                   3643: #  the compatibility of cross version installations or, alternatively to
                   3644: #  simply know who's out of date and who isn't.  Note that the version
                   3645: #  is returned concatenated with the tail.
                   3646: # Parameters:
                   3647: #   $cmd        - the request that dispatched to us.
                   3648: #   $tail       - Tail of the request (client's version?).
                   3649: #   $client     - Socket open on the client.
                   3650: #Returns:
                   3651: #   1 - continue processing requests.
                   3652: # Side Effects:
                   3653: #   Replies with version to $client.
                   3654: sub get_version_handler {
                   3655:     my ($cmd, $tail, $client) = @_;
                   3656: 
                   3657:     my $userinput  = $cmd.$tail;
                   3658:     
                   3659:     &Reply($client, &version($userinput)."\n", $userinput);
                   3660: 
                   3661: 
                   3662:     return 1;
                   3663: }
                   3664: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 3665: 
1.246     foxr     3666: #  Set the current host and domain.  This is used to support
                   3667: #  multihomed systems.  Each IP of the system, or even separate daemons
                   3668: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   3669: #  machine.  This command selects the virtual lonCAPA.  The client always
                   3670: #  knows the right one since it is lonc and it is selecting the domain/system
                   3671: #  from the hosts.tab file.
                   3672: # Parameters:
                   3673: #    $cmd      - Command that dispatched us.
                   3674: #    $tail     - Tail of the command (domain/host requested).
                   3675: #    $socket   - Socket open on the client.
                   3676: #
                   3677: # Returns:
                   3678: #     1   - Indicates the program should continue to process requests.
                   3679: # Side-effects:
                   3680: #     The default domain/system context is modified for this daemon.
                   3681: #     a reply is sent to the client.
                   3682: #
                   3683: sub set_virtual_host_handler {
                   3684:     my ($cmd, $tail, $socket) = @_;
                   3685:   
                   3686:     my $userinput  ="$cmd:$tail";
                   3687: 
                   3688:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   3689: 
                   3690: 
                   3691:     return 1;
                   3692: }
1.247     albertel 3693: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     3694: 
                   3695: #  Process a request to exit:
                   3696: #   - "bye" is sent to the client.
                   3697: #   - The client socket is shutdown and closed.
                   3698: #   - We indicate to the caller that we should exit.
                   3699: # Formal Parameters:
                   3700: #   $cmd                - The command that got us here.
                   3701: #   $tail               - Tail of the command (empty).
                   3702: #   $client             - Socket open on the tail.
                   3703: # Returns:
                   3704: #   0      - Indicating the program should exit!!
                   3705: #
                   3706: sub exit_handler {
                   3707:     my ($cmd, $tail, $client) = @_;
                   3708: 
                   3709:     my $userinput = "$cmd:$tail";
                   3710: 
                   3711:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   3712:     &Reply($client, "bye\n", $userinput);
                   3713:     $client->shutdown(2);        # shutdown the socket forcibly.
                   3714:     $client->close();
                   3715: 
                   3716:     return 0;
                   3717: }
1.248     foxr     3718: &register_handler("exit", \&exit_handler, 0,1,1);
                   3719: &register_handler("init", \&exit_handler, 0,1,1);
                   3720: &register_handler("quit", \&exit_handler, 0,1,1);
                   3721: 
                   3722: #  Determine if auto-enrollment is enabled.
                   3723: #  Note that the original had what I believe to be a defect.
                   3724: #  The original returned 0 if the requestor was not a registerd client.
                   3725: #  It should return "refused".
                   3726: # Formal Parameters:
                   3727: #   $cmd       - The command that invoked us.
                   3728: #   $tail      - The tail of the command (Extra command parameters.
                   3729: #   $client    - The socket open on the client that issued the request.
                   3730: # Returns:
                   3731: #    1         - Indicating processing should continue.
                   3732: #
                   3733: sub enrollment_enabled_handler {
                   3734:     my ($cmd, $tail, $client) = @_;
                   3735:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   3736: 
                   3737:     
                   3738:     my $cdom = split(/:/, $tail);   # Domain we're asking about.
                   3739:     my $outcome  = &localenroll::run($cdom);
                   3740:     &Reply($client, "$outcome\n", $userinput);
                   3741: 
                   3742:     return 1;
                   3743: }
                   3744: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   3745: 
                   3746: #   Get the official sections for which auto-enrollment is possible.
                   3747: #   Since the admin people won't know about 'unofficial sections' 
                   3748: #   we cannot auto-enroll on them.
                   3749: # Formal Parameters:
                   3750: #    $cmd     - The command request that got us dispatched here.
                   3751: #    $tail    - The remainder of the request.  In our case this
                   3752: #               will be split into:
                   3753: #               $coursecode   - The course name from the admin point of view.
                   3754: #               $cdom         - The course's domain(?).
                   3755: #    $client  - Socket open on the client.
                   3756: # Returns:
                   3757: #    1    - Indiciting processing should continue.
                   3758: #
                   3759: sub get_sections_handler {
                   3760:     my ($cmd, $tail, $client) = @_;
                   3761:     my $userinput = "$cmd:$tail";
                   3762: 
                   3763:     my ($coursecode, $cdom) = split(/:/, $tail);
                   3764:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   3765:     my $seclist = &escape(join(':',@secs));
                   3766: 
                   3767:     &Reply($client, "$seclist\n", $userinput);
                   3768:     
                   3769: 
                   3770:     return 1;
                   3771: }
                   3772: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   3773: 
                   3774: #   Validate the owner of a new course section.  
                   3775: #
                   3776: # Formal Parameters:
                   3777: #   $cmd      - Command that got us dispatched.
                   3778: #   $tail     - the remainder of the command.  For us this consists of a
                   3779: #               colon separated string containing:
                   3780: #                  $inst    - Course Id from the institutions point of view.
                   3781: #                  $owner   - Proposed owner of the course.
                   3782: #                  $cdom    - Domain of the course (from the institutions
                   3783: #                             point of view?)..
                   3784: #   $client   - Socket open on the client.
                   3785: #
                   3786: # Returns:
                   3787: #   1        - Processing should continue.
                   3788: #
                   3789: sub validate_course_owner_handler {
                   3790:     my ($cmd, $tail, $client)  = @_;
                   3791:     my $userinput = "$cmd:$tail";
                   3792:     my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
                   3793: 
                   3794:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
                   3795:     &Reply($client, "$outcome\n", $userinput);
                   3796: 
                   3797: 
                   3798: 
                   3799:     return 1;
                   3800: }
                   3801: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 3802: 
1.248     foxr     3803: #
                   3804: #   Validate a course section in the official schedule of classes
                   3805: #   from the institutions point of view (part of autoenrollment).
                   3806: #
                   3807: # Formal Parameters:
                   3808: #   $cmd          - The command request that got us dispatched.
                   3809: #   $tail         - The tail of the command.  In this case,
                   3810: #                   this is a colon separated set of words that will be split
                   3811: #                   into:
                   3812: #                        $inst_course_id - The course/section id from the
                   3813: #                                          institutions point of view.
                   3814: #                        $cdom           - The domain from the institutions
                   3815: #                                          point of view.
                   3816: #   $client       - Socket open on the client.
                   3817: # Returns:
                   3818: #    1           - Indicating processing should continue.
                   3819: #
                   3820: sub validate_course_section_handler {
                   3821:     my ($cmd, $tail, $client) = @_;
                   3822:     my $userinput = "$cmd:$tail";
                   3823:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   3824: 
                   3825:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
                   3826:     &Reply($client, "$outcome\n", $userinput);
                   3827: 
                   3828: 
                   3829:     return 1;
                   3830: }
                   3831: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   3832: 
                   3833: #
                   3834: #   Create a password for a new auto-enrollment user.
                   3835: #   I think/guess, this password allows access to the institutions 
                   3836: #   AIS class list server/services.  Stuart can correct this comment
                   3837: #   when he finds out how wrong I am.
                   3838: #
                   3839: # Formal Parameters:
                   3840: #    $cmd     - The command request that got us dispatched.
                   3841: #    $tail    - The tail of the command.   In this case this is a colon separated
                   3842: #               set of words that will be split into:
                   3843: #               $authparam - An authentication parameter (username??).
                   3844: #               $cdom      - The domain of the course from the institution's
                   3845: #                            point of view.
                   3846: #    $client  - The socket open on the client.
                   3847: # Returns:
                   3848: #    1 - continue processing.
                   3849: #
                   3850: sub create_auto_enroll_password_handler {
                   3851:     my ($cmd, $tail, $client) = @_;
                   3852:     my $userinput = "$cmd:$tail";
                   3853: 
                   3854:     my ($authparam, $cdom) = split(/:/, $userinput);
                   3855: 
                   3856:     my ($create_passwd,$authchk);
                   3857:     ($authparam,
                   3858:      $create_passwd,
                   3859:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   3860: 
                   3861:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   3862: 	   $userinput);
                   3863: 
                   3864: 
                   3865:     return 1;
                   3866: }
                   3867: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   3868: 		  0, 1, 0);
                   3869: 
                   3870: #   Retrieve and remove temporary files created by/during autoenrollment.
                   3871: #
                   3872: # Formal Parameters:
                   3873: #    $cmd      - The command that got us dispatched.
                   3874: #    $tail     - The tail of the command.  In our case this is a colon 
                   3875: #                separated list that will be split into:
                   3876: #                $filename - The name of the file to remove.
                   3877: #                            The filename is given as a path relative to
                   3878: #                            the LonCAPA temp file directory.
                   3879: #    $client   - Socket open on the client.
                   3880: #
                   3881: # Returns:
                   3882: #   1     - Continue processing.
                   3883: sub retrieve_auto_file_handler {
                   3884:     my ($cmd, $tail, $client)    = @_;
                   3885:     my $userinput                = "cmd:$tail";
                   3886: 
                   3887:     my ($filename)   = split(/:/, $tail);
                   3888: 
                   3889:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
                   3890:     if ( (-e $source) && ($filename ne '') ) {
                   3891: 	my $reply = '';
                   3892: 	if (open(my $fh,$source)) {
                   3893: 	    while (<$fh>) {
                   3894: 		chomp($_);
                   3895: 		$_ =~ s/^\s+//g;
                   3896: 		$_ =~ s/\s+$//g;
                   3897: 		$reply .= $_;
                   3898: 	    }
                   3899: 	    close($fh);
                   3900: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   3901: 
                   3902: #   Does this have to be uncommented??!?  (RF).
                   3903: #
                   3904: #                                unlink($source);
                   3905: 	} else {
                   3906: 	    &Failure($client, "error\n", $userinput);
                   3907: 	}
                   3908:     } else {
                   3909: 	&Failure($client, "error\n", $userinput);
                   3910:     }
                   3911:     
                   3912: 
                   3913:     return 1;
                   3914: }
                   3915: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   3916: 
                   3917: #
                   3918: #   Read and retrieve institutional code format (for support form).
                   3919: # Formal Parameters:
                   3920: #    $cmd        - Command that dispatched us.
                   3921: #    $tail       - Tail of the command.  In this case it conatins 
                   3922: #                  the course domain and the coursename.
                   3923: #    $client     - Socket open on the client.
                   3924: # Returns:
                   3925: #    1     - Continue processing.
                   3926: #
                   3927: sub get_institutional_code_format_handler {
                   3928:     my ($cmd, $tail, $client)   = @_;
                   3929:     my $userinput               = "$cmd:$tail";
                   3930: 
                   3931:     my $reply;
                   3932:     my($cdom,$course) = split(/:/,$tail);
                   3933:     my @pairs = split/\&/,$course;
                   3934:     my %instcodes = ();
                   3935:     my %codes = ();
                   3936:     my @codetitles = ();
                   3937:     my %cat_titles = ();
                   3938:     my %cat_order = ();
                   3939:     foreach (@pairs) {
                   3940: 	my ($key,$value) = split/=/,$_;
                   3941: 	$instcodes{&unescape($key)} = &unescape($value);
                   3942:     }
                   3943:     my $formatreply = &localenroll::instcode_format($cdom,
                   3944: 						    \%instcodes,
                   3945: 						    \%codes,
                   3946: 						    \@codetitles,
                   3947: 						    \%cat_titles,
                   3948: 						    \%cat_order);
                   3949:     if ($formatreply eq 'ok') {
                   3950: 	my $codes_str = &hash2str(%codes);
                   3951: 	my $codetitles_str = &array2str(@codetitles);
                   3952: 	my $cat_titles_str = &hash2str(%cat_titles);
                   3953: 	my $cat_order_str = &hash2str(%cat_order);
                   3954: 	&Reply($client,
                   3955: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   3956: 	       .$cat_order_str."\n",
                   3957: 	       $userinput);
                   3958:     } else {
                   3959: 	# this else branch added by RF since if not ok, lonc will
                   3960: 	# hang waiting on reply until timeout.
                   3961: 	#
                   3962: 	&Reply($client, "format_error\n", $userinput);
                   3963:     }
                   3964:     
                   3965:     return 1;
                   3966: }
1.265     albertel 3967: &register_handler("autoinstcodeformat",
                   3968: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     3969: 
1.265     albertel 3970: #
                   3971: # Gets a student's photo to exist (in the correct image type) in the user's 
                   3972: # directory.
                   3973: # Formal Parameters:
                   3974: #    $cmd     - The command request that got us dispatched.
                   3975: #    $tail    - A colon separated set of words that will be split into:
                   3976: #               $domain - student's domain
                   3977: #               $uname  - student username
                   3978: #               $type   - image type desired
                   3979: #    $client  - The socket open on the client.
                   3980: # Returns:
                   3981: #    1 - continue processing.
                   3982: sub student_photo_handler {
                   3983:     my ($cmd, $tail, $client) = @_;
                   3984:     my ($domain,$uname,$type) = split(/:/, $tail);
                   3985: 
                   3986:     my $path=&propath($domain,$uname).
                   3987: 	'/userfiles/internal/studentphoto.'.$type;
                   3988:     if (-e $path) {
                   3989: 	&Reply($client,"ok\n","$cmd:$tail");
                   3990: 	return 1;
                   3991:     }
                   3992:     &mkpath($path);
                   3993:     my $file=&localstudentphoto::fetch($domain,$uname);
                   3994:     if (!$file) {
                   3995: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   3996: 	return 1;
                   3997:     }
                   3998:     if (!-e $path) { &convert_photo($file,$path); }
                   3999:     if (-e $path) {
                   4000: 	&Reply($client,"ok\n","$cmd:$tail");
                   4001: 	return 1;
                   4002:     }
                   4003:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   4004:     return 1;
                   4005: }
                   4006: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     4007: 
1.264     albertel 4008: # mkpath makes all directories for a file, expects an absolute path with a
                   4009: # file or a trailing / if just a dir is passed
                   4010: # returns 1 on success 0 on failure
                   4011: sub mkpath {
                   4012:     my ($file)=@_;
                   4013:     my @parts=split(/\//,$file,-1);
                   4014:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   4015:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 4016: 	$now.='/'.$parts[$i]; 
1.264     albertel 4017: 	if (!-e $now) {
                   4018: 	    if  (!mkdir($now,0770)) { return 0; }
                   4019: 	}
                   4020:     }
                   4021:     return 1;
                   4022: }
                   4023: 
1.207     foxr     4024: #---------------------------------------------------------------
                   4025: #
                   4026: #   Getting, decoding and dispatching requests:
                   4027: #
                   4028: #
                   4029: #   Get a Request:
                   4030: #   Gets a Request message from the client.  The transaction
                   4031: #   is defined as a 'line' of text.  We remove the new line
                   4032: #   from the text line.  
1.226     foxr     4033: #
1.211     albertel 4034: sub get_request {
1.207     foxr     4035:     my $input = <$client>;
                   4036:     chomp($input);
1.226     foxr     4037: 
1.234     foxr     4038:     &Debug("get_request: Request = $input\n");
1.207     foxr     4039: 
                   4040:     &status('Processing '.$clientname.':'.$input);
                   4041: 
                   4042:     return $input;
                   4043: }
1.212     foxr     4044: #---------------------------------------------------------------
                   4045: #
                   4046: #  Process a request.  This sub should shrink as each action
                   4047: #  gets farmed out into a separat sub that is registered 
                   4048: #  with the dispatch hash.  
                   4049: #
                   4050: # Parameters:
                   4051: #    user_input   - The request received from the client (lonc).
                   4052: # Returns:
                   4053: #    true to keep processing, false if caller should exit.
                   4054: #
                   4055: sub process_request {
                   4056:     my ($userinput) = @_;      # Easier for now to break style than to
                   4057:                                 # fix all the userinput -> user_input.
                   4058:     my $wasenc    = 0;		# True if request was encrypted.
                   4059: # ------------------------------------------------------------ See if encrypted
                   4060:     if ($userinput =~ /^enc/) {
                   4061: 	$userinput = decipher($userinput);
                   4062: 	$wasenc=1;
                   4063: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     4064: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     4065: 	    return 0;
                   4066: 	}
                   4067:     }
                   4068:     Debug("process_request: $userinput\n");
                   4069:     
1.213     foxr     4070:     #  
                   4071:     #   The 'correct way' to add a command to lond is now to
                   4072:     #   write a sub to execute it and Add it to the command dispatch
                   4073:     #   hash via a call to register_handler..  The comments to that
                   4074:     #   sub should give you enough to go on to show how to do this
                   4075:     #   along with the examples that are building up as this code
                   4076:     #   is getting refactored.   Until all branches of the
                   4077:     #   if/elseif monster below have been factored out into
                   4078:     #   separate procesor subs, if the dispatch hash is missing
                   4079:     #   the command keyword, we will fall through to the remainder
                   4080:     #   of the if/else chain below in order to keep this thing in 
                   4081:     #   working order throughout the transmogrification.
                   4082: 
                   4083:     my ($command, $tail) = split(/:/, $userinput, 2);
                   4084:     chomp($command);
                   4085:     chomp($tail);
                   4086:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     4087:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   4088:     if(!$tail) {
                   4089: 	$tail ="";		# defined but blank.
                   4090:     }
1.213     foxr     4091: 
                   4092:     &Debug("Command received: $command, encoded = $wasenc");
                   4093: 
                   4094:     if(defined $Dispatcher{$command}) {
                   4095: 
                   4096: 	my $dispatch_info = $Dispatcher{$command};
                   4097: 	my $handler       = $$dispatch_info[0];
                   4098: 	my $need_encode   = $$dispatch_info[1];
                   4099: 	my $client_types  = $$dispatch_info[2];
                   4100: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   4101: 	      ."ClientType $client_types");
                   4102:       
                   4103: 	#  Validate the request:
                   4104:       
                   4105: 	my $ok = 1;
                   4106: 	my $requesterprivs = 0;
                   4107: 	if(&isClient()) {
                   4108: 	    $requesterprivs |= $CLIENT_OK;
                   4109: 	}
                   4110: 	if(&isManager()) {
                   4111: 	    $requesterprivs |= $MANAGER_OK;
                   4112: 	}
                   4113: 	if($need_encode && (!$wasenc)) {
                   4114: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   4115: 	    $ok = 0;
                   4116: 	}
                   4117: 	if(($client_types & $requesterprivs) == 0) {
                   4118: 	    Debug("Client not privileged to do this operation");
                   4119: 	    $ok = 0;
                   4120: 	}
                   4121: 
                   4122: 	if($ok) {
                   4123: 	    Debug("Dispatching to handler $command $tail");
                   4124: 	    my $keep_going = &$handler($command, $tail, $client);
                   4125: 	    return $keep_going;
                   4126: 	} else {
                   4127: 	    Debug("Refusing to dispatch because client did not match requirements");
                   4128: 	    Failure($client, "refused\n", $userinput);
                   4129: 	    return 1;
                   4130: 	}
                   4131: 
                   4132:     }    
                   4133: 
1.262     foxr     4134:     print $client "unknown_cmd\n";
1.212     foxr     4135: # -------------------------------------------------------------------- complete
                   4136:     Debug("process_request - returning 1");
                   4137:     return 1;
                   4138: }
1.207     foxr     4139: #
                   4140: #   Decipher encoded traffic
                   4141: #  Parameters:
                   4142: #     input      - Encoded data.
                   4143: #  Returns:
                   4144: #     Decoded data or undef if encryption key was not yet negotiated.
                   4145: #  Implicit input:
                   4146: #     cipher  - This global holds the negotiated encryption key.
                   4147: #
1.211     albertel 4148: sub decipher {
1.207     foxr     4149:     my ($input)  = @_;
                   4150:     my $output = '';
1.212     foxr     4151:     
                   4152:     
1.207     foxr     4153:     if($cipher) {
                   4154: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   4155: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   4156: 	    $output .= 
                   4157: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   4158: 	}
                   4159: 	return substr($output, 0, $enclength);
                   4160:     } else {
                   4161: 	return undef;
                   4162:     }
                   4163: }
                   4164: 
                   4165: #
                   4166: #   Register a command processor.  This function is invoked to register a sub
                   4167: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   4168: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   4169: #   as well:
                   4170: #    - Is the keyword recognized.
                   4171: #    - Is the proper client type attempting the request.
                   4172: #    - Is the request encrypted if it has to be.
                   4173: #   Parameters:
                   4174: #    $request_name         - Name of the request being registered.
                   4175: #                           This is the command request that will match
                   4176: #                           against the hash keywords to lookup the information
                   4177: #                           associated with the dispatch information.
                   4178: #    $procedure           - Reference to a sub to call to process the request.
                   4179: #                           All subs get called as follows:
                   4180: #                             Procedure($cmd, $tail, $replyfd, $key)
                   4181: #                             $cmd    - the actual keyword that invoked us.
                   4182: #                             $tail   - the tail of the request that invoked us.
                   4183: #                             $replyfd- File descriptor connected to the client
                   4184: #    $must_encode          - True if the request must be encoded to be good.
                   4185: #    $client_ok            - True if it's ok for a client to request this.
                   4186: #    $manager_ok           - True if it's ok for a manager to request this.
                   4187: # Side effects:
                   4188: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   4189: #      - On failure, the program will die as it's a bad internal bug to try to 
                   4190: #        register a duplicate command handler.
                   4191: #
1.211     albertel 4192: sub register_handler {
1.212     foxr     4193:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     4194: 
                   4195:     #  Don't allow duplication#
                   4196:    
                   4197:     if (defined $Dispatcher{$request_name}) {
                   4198: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   4199:     }
                   4200:     #   Build the client type mask:
                   4201:     
                   4202:     my $client_type_mask = 0;
                   4203:     if($client_ok) {
                   4204: 	$client_type_mask  |= $CLIENT_OK;
                   4205:     }
                   4206:     if($manager_ok) {
                   4207: 	$client_type_mask  |= $MANAGER_OK;
                   4208:     }
                   4209:    
                   4210:     #  Enter the hash:
                   4211:       
                   4212:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   4213:    
                   4214:     $Dispatcher{$request_name} = \@entry;
                   4215:    
                   4216: }
                   4217: 
                   4218: 
                   4219: #------------------------------------------------------------------
                   4220: 
                   4221: 
                   4222: 
                   4223: 
1.141     foxr     4224: #
1.96      foxr     4225: #  Convert an error return code from lcpasswd to a string value.
                   4226: #
                   4227: sub lcpasswdstrerror {
                   4228:     my $ErrorCode = shift;
1.97      foxr     4229:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     4230: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   4231:     } else {
1.98      foxr     4232: 	return $passwderrors[$ErrorCode];
1.96      foxr     4233:     }
                   4234: }
                   4235: 
1.97      foxr     4236: #
                   4237: # Convert an error return code from lcuseradd to a string value:
                   4238: #
                   4239: sub lcuseraddstrerror {
                   4240:     my $ErrorCode = shift;
                   4241:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
                   4242: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
                   4243:     } else {
1.98      foxr     4244: 	return $adderrors[$ErrorCode];
1.97      foxr     4245:     }
                   4246: }
                   4247: 
1.23      harris41 4248: # grabs exception and records it to log before exiting
                   4249: sub catchexception {
1.27      albertel 4250:     my ($error)=@_;
1.25      www      4251:     $SIG{'QUIT'}='DEFAULT';
                   4252:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 4253:     &status("Catching exception");
1.190     albertel 4254:     &logthis("<font color='red'>CRITICAL: "
1.134     albertel 4255:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27      albertel 4256:      ."a crash with this error msg->[$error]</font>");
1.57      www      4257:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 4258:     if ($client) { print $client "error: $error\n"; }
1.59      www      4259:     $server->close();
1.27      albertel 4260:     die($error);
1.23      harris41 4261: }
1.63      www      4262: sub timeout {
1.165     albertel 4263:     &status("Handling Timeout");
1.190     albertel 4264:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      4265:     &catchexception('Timeout');
                   4266: }
1.22      harris41 4267: # -------------------------------- Set signal handlers to record abnormal exits
                   4268: 
1.226     foxr     4269: 
1.22      harris41 4270: $SIG{'QUIT'}=\&catchexception;
                   4271: $SIG{__DIE__}=\&catchexception;
                   4272: 
1.81      matthew  4273: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 4274: &status("Read loncapa.conf and loncapa_apache.conf");
                   4275: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     4276: %perlvar=%{$perlvarref};
1.80      harris41 4277: undef $perlvarref;
1.19      www      4278: 
1.35      harris41 4279: # ----------------------------- Make sure this process is running from user=www
                   4280: my $wwwid=getpwnam('www');
                   4281: if ($wwwid!=$<) {
1.134     albertel 4282:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4283:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 4284:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 4285:  mailto $emailto -s '$subj' > /dev/null");
                   4286:    exit 1;
                   4287: }
                   4288: 
1.19      www      4289: # --------------------------------------------- Check if other instance running
                   4290: 
                   4291: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   4292: 
                   4293: if (-e $pidfile) {
                   4294:    my $lfh=IO::File->new("$pidfile");
                   4295:    my $pide=<$lfh>;
                   4296:    chomp($pide);
1.29      harris41 4297:    if (kill 0 => $pide) { die "already running"; }
1.19      www      4298: }
1.1       albertel 4299: 
                   4300: # ------------------------------------------------------------- Read hosts file
                   4301: 
                   4302: 
                   4303: 
                   4304: # establish SERVER socket, bind and listen.
                   4305: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   4306:                                 Type      => SOCK_STREAM,
                   4307:                                 Proto     => 'tcp',
                   4308:                                 Reuse     => 1,
                   4309:                                 Listen    => 10 )
1.29      harris41 4310:   or die "making socket: $@\n";
1.1       albertel 4311: 
                   4312: # --------------------------------------------------------- Do global variables
                   4313: 
                   4314: # global variables
                   4315: 
1.134     albertel 4316: my %children               = ();       # keys are current child process IDs
1.1       albertel 4317: 
                   4318: sub REAPER {                        # takes care of dead children
                   4319:     $SIG{CHLD} = \&REAPER;
1.165     albertel 4320:     &status("Handling child death");
1.178     foxr     4321:     my $pid;
                   4322:     do {
                   4323: 	$pid = waitpid(-1,&WNOHANG());
                   4324: 	if (defined($children{$pid})) {
                   4325: 	    &logthis("Child $pid died");
                   4326: 	    delete($children{$pid});
1.183     albertel 4327: 	} elsif ($pid > 0) {
1.178     foxr     4328: 	    &logthis("Unknown Child $pid died");
                   4329: 	}
                   4330:     } while ( $pid > 0 );
                   4331:     foreach my $child (keys(%children)) {
                   4332: 	$pid = waitpid($child,&WNOHANG());
                   4333: 	if ($pid > 0) {
                   4334: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   4335: 	    delete($children{$pid});
                   4336: 	}
1.176     albertel 4337:     }
1.165     albertel 4338:     &status("Finished Handling child death");
1.1       albertel 4339: }
                   4340: 
                   4341: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 4342:     &status("Killing children (INT)");
1.1       albertel 4343:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   4344:     kill 'INT' => keys %children;
1.59      www      4345:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 4346:     my $execdir=$perlvar{'lonDaemons'};
                   4347:     unlink("$execdir/logs/lond.pid");
1.190     albertel 4348:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 4349:     &status("Done killing children");
1.1       albertel 4350:     exit;                           # clean up with dignity
                   4351: }
                   4352: 
                   4353: sub HUPSMAN {                      # signal handler for SIGHUP
                   4354:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 4355:     &status("Killing children for restart (HUP)");
1.1       albertel 4356:     kill 'INT' => keys %children;
1.59      www      4357:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 4358:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 4359:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 4360:     unlink("$execdir/logs/lond.pid");
1.165     albertel 4361:     &status("Restarting self (HUP)");
1.1       albertel 4362:     exec("$execdir/lond");         # here we go again
                   4363: }
                   4364: 
1.144     foxr     4365: #
1.148     foxr     4366: #    Kill off hashes that describe the host table prior to re-reading it.
                   4367: #    Hashes affected are:
1.200     matthew  4368: #       %hostid, %hostdom %hostip %hostdns.
1.148     foxr     4369: #
                   4370: sub KillHostHashes {
                   4371:     foreach my $key (keys %hostid) {
                   4372: 	delete $hostid{$key};
                   4373:     }
                   4374:     foreach my $key (keys %hostdom) {
                   4375: 	delete $hostdom{$key};
                   4376:     }
                   4377:     foreach my $key (keys %hostip) {
                   4378: 	delete $hostip{$key};
                   4379:     }
1.200     matthew  4380:     foreach my $key (keys %hostdns) {
                   4381: 	delete $hostdns{$key};
                   4382:     }
1.148     foxr     4383: }
                   4384: #
                   4385: #   Read in the host table from file and distribute it into the various hashes:
                   4386: #
                   4387: #    - %hostid  -  Indexed by IP, the loncapa hostname.
                   4388: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
                   4389: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
                   4390: sub ReadHostTable {
                   4391: 
                   4392:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200     matthew  4393:     my $myloncapaname = $perlvar{'lonHostID'};
                   4394:     Debug("My loncapa name is : $myloncapaname");
1.148     foxr     4395:     while (my $configline=<CONFIG>) {
1.277     albertel 4396: 	if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
                   4397: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   4398: 	    $name=~s/\s//g;
1.279     albertel 4399: 	    my $ip = gethostbyname($name);
1.277     albertel 4400: 	    if (length($ip) ne 4) {
                   4401: 		&logthis("Skipping host $id name $name no IP $ip found\n");
                   4402: 		next;
                   4403: 	    }
                   4404: 	    $ip=inet_ntoa($ip);
1.200     matthew  4405: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
                   4406: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
1.277     albertel 4407: 	    $hostip{$id}=$ip;         # IP address of host.
1.200     matthew  4408: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
                   4409: 
                   4410: 	    if ($id eq $perlvar{'lonHostID'}) { 
                   4411: 		Debug("Found me in the host table: $name");
                   4412: 		$thisserver=$name; 
                   4413: 	    }
1.178     foxr     4414: 	}
1.148     foxr     4415:     }
                   4416:     close(CONFIG);
                   4417: }
                   4418: #
                   4419: #  Reload the Apache daemon's state.
1.150     foxr     4420: #  This is done by invoking /home/httpd/perl/apachereload
                   4421: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     4422: #
                   4423: sub ReloadApache {
1.150     foxr     4424:     my $execdir = $perlvar{'lonDaemons'};
                   4425:     my $script  = $execdir."/apachereload";
                   4426:     system($script);
1.148     foxr     4427: }
                   4428: 
                   4429: #
1.144     foxr     4430: #   Called in response to a USR2 signal.
                   4431: #   - Reread hosts.tab
                   4432: #   - All children connected to hosts that were removed from hosts.tab
                   4433: #     are killed via SIGINT
                   4434: #   - All children connected to previously existing hosts are sent SIGUSR1
                   4435: #   - Our internal hosts hash is updated to reflect the new contents of
                   4436: #     hosts.tab causing connections from hosts added to hosts.tab to
                   4437: #     now be honored.
                   4438: #
                   4439: sub UpdateHosts {
1.165     albertel 4440:     &status("Reload hosts.tab");
1.147     foxr     4441:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     4442:     #
                   4443:     #  The %children hash has the set of IP's we currently have children
                   4444:     #  on.  These need to be matched against records in the hosts.tab
                   4445:     #  Any ip's no longer in the table get killed off they correspond to
                   4446:     #  either dropped or changed hosts.  Note that the re-read of the table
                   4447:     #  will take care of new and changed hosts as connections come into being.
                   4448: 
                   4449: 
                   4450:     KillHostHashes;
                   4451:     ReadHostTable;
                   4452: 
                   4453:     foreach my $child (keys %children) {
                   4454: 	my $childip = $children{$child};
                   4455: 	if(!$hostid{$childip}) {
1.149     foxr     4456: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   4457: 		    ." $child for ip $childip </font>");
1.148     foxr     4458: 	    kill('INT', $child);
1.149     foxr     4459: 	} else {
                   4460: 	    logthis('<font color="green"> keeping child for ip '
                   4461: 		    ." $childip (pid=$child) </font>");
1.148     foxr     4462: 	}
                   4463:     }
                   4464:     ReloadApache;
1.165     albertel 4465:     &status("Finished reloading hosts.tab");
1.144     foxr     4466: }
                   4467: 
1.148     foxr     4468: 
1.57      www      4469: sub checkchildren {
1.165     albertel 4470:     &status("Checking on the children (sending signals)");
1.57      www      4471:     &initnewstatus();
                   4472:     &logstatus();
                   4473:     &logthis('Going to check on the children');
1.134     albertel 4474:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 4475:     foreach (sort keys %children) {
1.221     albertel 4476: 	#sleep 1;
1.57      www      4477:         unless (kill 'USR1' => $_) {
                   4478: 	    &logthis ('Child '.$_.' is dead');
                   4479:             &logstatus($$.' is dead');
1.221     albertel 4480: 	    delete($children{$_});
1.57      www      4481:         } 
1.61      harris41 4482:     }
1.63      www      4483:     sleep 5;
1.212     foxr     4484:     $SIG{ALRM} = sub { Debug("timeout"); 
                   4485: 		       die "timeout";  };
1.113     albertel 4486:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 4487:     &status("Checking on the children (waiting for reports)");
1.63      www      4488:     foreach (sort keys %children) {
                   4489:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 4490:           eval {
                   4491:             alarm(300);
1.63      www      4492: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 4493: 	    kill 9 => $_;
1.131     albertel 4494: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   4495: 	    #$subj="LON: $currenthostid killed lond process $_";
                   4496: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   4497: 	    #$execdir=$perlvar{'lonDaemons'};
                   4498: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 4499: 	    delete($children{$_});
1.113     albertel 4500: 	    alarm(0);
                   4501: 	  }
1.63      www      4502:         }
                   4503:     }
1.113     albertel 4504:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 4505:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 4506:     &status("Finished checking children");
1.221     albertel 4507:     &logthis('Finished Checking children');
1.57      www      4508: }
                   4509: 
1.1       albertel 4510: # --------------------------------------------------------------------- Logging
                   4511: 
                   4512: sub logthis {
                   4513:     my $message=shift;
                   4514:     my $execdir=$perlvar{'lonDaemons'};
                   4515:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   4516:     my $now=time;
                   4517:     my $local=localtime($now);
1.58      www      4518:     $lastlog=$local.': '.$message;
1.1       albertel 4519:     print $fh "$local ($$): $message\n";
                   4520: }
                   4521: 
1.77      foxr     4522: # ------------------------- Conditional log if $DEBUG true.
                   4523: sub Debug {
                   4524:     my $message = shift;
                   4525:     if($DEBUG) {
                   4526: 	&logthis($message);
                   4527:     }
                   4528: }
1.161     foxr     4529: 
                   4530: #
                   4531: #   Sub to do replies to client.. this gives a hook for some
                   4532: #   debug tracing too:
                   4533: #  Parameters:
                   4534: #     fd      - File open on client.
                   4535: #     reply   - Text to send to client.
                   4536: #     request - Original request from client.
                   4537: #
                   4538: sub Reply {
1.192     foxr     4539:     my ($fd, $reply, $request) = @_;
1.161     foxr     4540:     print $fd $reply;
                   4541:     Debug("Request was $request  Reply was $reply");
                   4542: 
1.212     foxr     4543:     $Transactions++;
                   4544: }
                   4545: 
                   4546: 
                   4547: #
                   4548: #    Sub to report a failure.
                   4549: #    This function:
                   4550: #     -   Increments the failure statistic counters.
                   4551: #     -   Invokes Reply to send the error message to the client.
                   4552: # Parameters:
                   4553: #    fd       - File descriptor open on the client
                   4554: #    reply    - Reply text to emit.
                   4555: #    request  - The original request message (used by Reply
                   4556: #               to debug if that's enabled.
                   4557: # Implicit outputs:
                   4558: #    $Failures- The number of failures is incremented.
                   4559: #    Reply (invoked here) sends a message to the 
                   4560: #    client:
                   4561: #
                   4562: sub Failure {
                   4563:     my $fd      = shift;
                   4564:     my $reply   = shift;
                   4565:     my $request = shift;
                   4566:    
                   4567:     $Failures++;
                   4568:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     4569: }
1.57      www      4570: # ------------------------------------------------------------------ Log status
                   4571: 
                   4572: sub logstatus {
1.178     foxr     4573:     &status("Doing logging");
                   4574:     my $docdir=$perlvar{'lonDocRoot'};
                   4575:     {
                   4576: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  4577:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     4578:         $fh->close();
                   4579:     }
1.221     albertel 4580:     &status("Finished $$.txt");
                   4581:     {
                   4582: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   4583: 	flock(LOG,LOCK_EX);
                   4584: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   4585: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 4586: 	flock(LOG,LOCK_UN);
1.221     albertel 4587: 	close(LOG);
                   4588:     }
1.178     foxr     4589:     &status("Finished logging");
1.57      www      4590: }
                   4591: 
                   4592: sub initnewstatus {
                   4593:     my $docdir=$perlvar{'lonDocRoot'};
                   4594:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
                   4595:     my $now=time;
                   4596:     my $local=localtime($now);
                   4597:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      4598:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 4599:     while (my $filename=readdir(DIR)) {
1.64      www      4600:         unlink("$docdir/lon-status/londchld/$filename");
                   4601:     }
                   4602:     closedir(DIR);
1.57      www      4603: }
                   4604: 
                   4605: # -------------------------------------------------------------- Status setting
                   4606: 
                   4607: sub status {
                   4608:     my $what=shift;
                   4609:     my $now=time;
                   4610:     my $local=localtime($now);
1.178     foxr     4611:     $status=$local.': '.$what;
                   4612:     $0='lond: '.$what.' '.$local;
1.57      www      4613: }
1.11      www      4614: 
                   4615: # -------------------------------------------------------- Escape Special Chars
                   4616: 
                   4617: sub escape {
                   4618:     my $str=shift;
                   4619:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   4620:     return $str;
                   4621: }
                   4622: 
                   4623: # ----------------------------------------------------- Un-Escape Special Chars
                   4624: 
                   4625: sub unescape {
                   4626:     my $str=shift;
                   4627:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   4628:     return $str;
                   4629: }
                   4630: 
1.1       albertel 4631: # ----------------------------------------------------------- Send USR1 to lonc
                   4632: 
                   4633: sub reconlonc {
                   4634:     my $peerfile=shift;
                   4635:     &logthis("Trying to reconnect for $peerfile");
                   4636:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
                   4637:     if (my $fh=IO::File->new("$loncfile")) {
                   4638: 	my $loncpid=<$fh>;
                   4639:         chomp($loncpid);
                   4640:         if (kill 0 => $loncpid) {
                   4641: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                   4642:             kill USR1 => $loncpid;
                   4643:         } else {
1.9       www      4644: 	    &logthis(
1.190     albertel 4645:               "<font color='red'>CRITICAL: "
1.9       www      4646:              ."lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel 4647:         }
                   4648:     } else {
1.190     albertel 4649:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1       albertel 4650:     }
                   4651: }
                   4652: 
                   4653: # -------------------------------------------------- Non-critical communication
1.11      www      4654: 
1.1       albertel 4655: sub subreply {
                   4656:     my ($cmd,$server)=@_;
                   4657:     my $peerfile="$perlvar{'lonSockDir'}/$server";
                   4658:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   4659:                                       Type    => SOCK_STREAM,
                   4660:                                       Timeout => 10)
                   4661:        or return "con_lost";
                   4662:     print $sclient "$cmd\n";
                   4663:     my $answer=<$sclient>;
                   4664:     chomp($answer);
                   4665:     if (!$answer) { $answer="con_lost"; }
                   4666:     return $answer;
                   4667: }
                   4668: 
                   4669: sub reply {
                   4670:   my ($cmd,$server)=@_;
                   4671:   my $answer;
1.115     albertel 4672:   if ($server ne $currenthostid) { 
1.1       albertel 4673:     $answer=subreply($cmd,$server);
                   4674:     if ($answer eq 'con_lost') {
                   4675: 	$answer=subreply("ping",$server);
                   4676:         if ($answer ne $server) {
1.115     albertel 4677: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1       albertel 4678:            &reconlonc("$perlvar{'lonSockDir'}/$server");
                   4679:         }
                   4680:         $answer=subreply($cmd,$server);
                   4681:     }
                   4682:   } else {
                   4683:     $answer='self_reply';
                   4684:   } 
                   4685:   return $answer;
                   4686: }
                   4687: 
1.13      www      4688: # -------------------------------------------------------------- Talk to lonsql
                   4689: 
1.234     foxr     4690: sub sql_reply {
1.12      harris41 4691:     my ($cmd)=@_;
1.234     foxr     4692:     my $answer=&sub_sql_reply($cmd);
                   4693:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 4694:     return $answer;
                   4695: }
                   4696: 
1.234     foxr     4697: sub sub_sql_reply {
1.12      harris41 4698:     my ($cmd)=@_;
                   4699:     my $unixsock="mysqlsock";
                   4700:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   4701:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   4702:                                       Type    => SOCK_STREAM,
                   4703:                                       Timeout => 10)
                   4704:        or return "con_lost";
                   4705:     print $sclient "$cmd\n";
                   4706:     my $answer=<$sclient>;
                   4707:     chomp($answer);
                   4708:     if (!$answer) { $answer="con_lost"; }
                   4709:     return $answer;
                   4710: }
                   4711: 
1.1       albertel 4712: # -------------------------------------------- Return path to profile directory
1.11      www      4713: 
1.1       albertel 4714: sub propath {
                   4715:     my ($udom,$uname)=@_;
                   4716:     $udom=~s/\W//g;
                   4717:     $uname=~s/\W//g;
1.16      www      4718:     my $subdir=$uname.'__';
1.1       albertel 4719:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4720:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                   4721:     return $proname;
                   4722: } 
                   4723: 
                   4724: # --------------------------------------- Is this the home server of an author?
1.11      www      4725: 
1.1       albertel 4726: sub ishome {
                   4727:     my $author=shift;
                   4728:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   4729:     my ($udom,$uname)=split(/\//,$author);
                   4730:     my $proname=propath($udom,$uname);
                   4731:     if (-e $proname) {
                   4732: 	return 'owner';
                   4733:     } else {
                   4734:         return 'not_owner';
                   4735:     }
                   4736: }
                   4737: 
                   4738: # ======================================================= Continue main program
                   4739: # ---------------------------------------------------- Fork once and dissociate
                   4740: 
1.134     albertel 4741: my $fpid=fork;
1.1       albertel 4742: exit if $fpid;
1.29      harris41 4743: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 4744: 
1.29      harris41 4745: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 4746: 
                   4747: # ------------------------------------------------------- Write our PID on disk
                   4748: 
1.134     albertel 4749: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 4750: open (PIDSAVE,">$execdir/logs/lond.pid");
                   4751: print PIDSAVE "$$\n";
                   4752: close(PIDSAVE);
1.190     albertel 4753: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      4754: &status('Starting');
1.1       albertel 4755: 
1.106     foxr     4756: 
1.1       albertel 4757: 
                   4758: # ----------------------------------------------------- Install signal handlers
                   4759: 
1.57      www      4760: 
1.1       albertel 4761: $SIG{CHLD} = \&REAPER;
                   4762: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   4763: $SIG{HUP}  = \&HUPSMAN;
1.57      www      4764: $SIG{USR1} = \&checkchildren;
1.144     foxr     4765: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     4766: 
1.148     foxr     4767: #  Read the host hashes:
                   4768: 
                   4769: ReadHostTable;
1.106     foxr     4770: 
                   4771: # --------------------------------------------------------------
                   4772: #   Accept connections.  When a connection comes in, it is validated
                   4773: #   and if good, a child process is created to process transactions
                   4774: #   along the connection.
                   4775: 
1.1       albertel 4776: while (1) {
1.165     albertel 4777:     &status('Starting accept');
1.106     foxr     4778:     $client = $server->accept() or next;
1.165     albertel 4779:     &status('Accepted '.$client.' off to spawn');
1.106     foxr     4780:     make_new_child($client);
1.165     albertel 4781:     &status('Finished spawning');
1.1       albertel 4782: }
                   4783: 
1.212     foxr     4784: sub make_new_child {
                   4785:     my $pid;
                   4786: #    my $cipher;     # Now global
                   4787:     my $sigset;
1.178     foxr     4788: 
1.212     foxr     4789:     $client = shift;
                   4790:     &status('Starting new child '.$client);
                   4791:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   4792: 	     ")</font>");    
                   4793:     # block signal for fork
                   4794:     $sigset = POSIX::SigSet->new(SIGINT);
                   4795:     sigprocmask(SIG_BLOCK, $sigset)
                   4796:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     4797: 
1.212     foxr     4798:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     4799: 
1.212     foxr     4800:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   4801: 	                               # connection liveness.
1.178     foxr     4802: 
1.212     foxr     4803:     #
                   4804:     #  Figure out who we're talking to so we can record the peer in 
                   4805:     #  the pid hash.
                   4806:     #
                   4807:     my $caller = getpeername($client);
                   4808:     my ($port,$iaddr);
                   4809:     if (defined($caller) && length($caller) > 0) {
                   4810: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   4811:     } else {
                   4812: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   4813:     }
                   4814:     if (defined($iaddr)) {
                   4815: 	$clientip  = inet_ntoa($iaddr);
                   4816: 	Debug("Connected with $clientip");
                   4817:     } else {
                   4818: 	&logthis("Unable to determine clientip");
                   4819: 	$clientip='Unavailable';
                   4820:     }
                   4821:     
                   4822:     if ($pid) {
                   4823:         # Parent records the child's birth and returns.
                   4824:         sigprocmask(SIG_UNBLOCK, $sigset)
                   4825:             or die "Can't unblock SIGINT for fork: $!\n";
                   4826:         $children{$pid} = $clientip;
                   4827:         &status('Started child '.$pid);
                   4828:         return;
                   4829:     } else {
                   4830:         # Child can *not* return from this subroutine.
                   4831:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   4832:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   4833:                                 #don't get intercepted
                   4834:         $SIG{USR1}= \&logstatus;
                   4835:         $SIG{ALRM}= \&timeout;
                   4836:         $lastlog='Forked ';
                   4837:         $status='Forked';
1.178     foxr     4838: 
1.212     foxr     4839:         # unblock signals
                   4840:         sigprocmask(SIG_UNBLOCK, $sigset)
                   4841:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     4842: 
1.212     foxr     4843: #        my $tmpsnum=0;            # Now global
                   4844: #---------------------------------------------------- kerberos 5 initialization
                   4845:         &Authen::Krb5::init_context();
                   4846:         &Authen::Krb5::init_ets();
1.209     albertel 4847: 
1.212     foxr     4848: 	&status('Accepted connection');
                   4849: # =============================================================================
                   4850:             # do something with the connection
                   4851: # -----------------------------------------------------------------------------
                   4852: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     4853: 
1.212     foxr     4854: 	ReadManagerTable;	# May also be a manager!!
                   4855: 	
1.278     albertel 4856: 	my $outsideip=$clientip;
                   4857: 	if ($clientip eq '127.0.0.1') {
                   4858: 	    $outsideip=$hostip{$perlvar{'lonHostID'}};
                   4859: 	}
                   4860: 
                   4861: 	my $clientrec=($hostid{$outsideip}     ne undef);
                   4862: 	my $ismanager=($managers{$outsideip}    ne undef);
1.212     foxr     4863: 	$clientname  = "[unknonwn]";
                   4864: 	if($clientrec) {	# Establish client type.
                   4865: 	    $ConnectionType = "client";
1.278     albertel 4866: 	    $clientname = $hostid{$outsideip};
1.212     foxr     4867: 	    if($ismanager) {
                   4868: 		$ConnectionType = "both";
                   4869: 	    }
                   4870: 	} else {
                   4871: 	    $ConnectionType = "manager";
1.278     albertel 4872: 	    $clientname = $managers{$outsideip};
1.212     foxr     4873: 	}
                   4874: 	my $clientok;
1.178     foxr     4875: 
1.212     foxr     4876: 	if ($clientrec || $ismanager) {
                   4877: 	    &status("Waiting for init from $clientip $clientname");
                   4878: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   4879: 		     $clientip.
                   4880: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   4881: 	    &status("Connecting $clientip  ($clientname))"); 
                   4882: 	    my $remotereq=<$client>;
                   4883: 	    chomp($remotereq);
                   4884: 	    Debug("Got init: $remotereq");
                   4885: 	    my $inikeyword = split(/:/, $remotereq);
                   4886: 	    if ($remotereq =~ /^init/) {
                   4887: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   4888: 		#
                   4889: 		#  If the remote is attempting a local init... give that a try:
                   4890: 		#
                   4891: 		my ($i, $inittype) = split(/:/, $remotereq);
1.209     albertel 4892: 
1.212     foxr     4893: 		# If the connection type is ssl, but I didn't get my
                   4894: 		# certificate files yet, then I'll drop  back to 
                   4895: 		# insecure (if allowed).
                   4896: 		
                   4897: 		if($inittype eq "ssl") {
                   4898: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   4899: 		    my $kfile       = lonssl::KeyFile;
                   4900: 		    if((!$ca)   || 
                   4901: 		       (!$cert) || 
                   4902: 		       (!$kfile)) {
                   4903: 			$inittype = ""; # This forces insecure attempt.
                   4904: 			&logthis("<font color=\"blue\"> Certificates not "
                   4905: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     4906: 		    } else {	# SSL certificates are in place so
1.212     foxr     4907: 		    }		# Leave the inittype alone.
                   4908: 		}
                   4909: 
                   4910: 		if($inittype eq "local") {
                   4911: 		    my $key = LocalConnection($client, $remotereq);
                   4912: 		    if($key) {
                   4913: 			Debug("Got local key $key");
                   4914: 			$clientok     = 1;
                   4915: 			my $cipherkey = pack("H32", $key);
                   4916: 			$cipher       = new IDEA($cipherkey);
                   4917: 			print $client "ok:local\n";
                   4918: 			&logthis('<font color="green"'
                   4919: 				 . "Successful local authentication </font>");
                   4920: 			$keymode = "local"
1.178     foxr     4921: 		    } else {
1.212     foxr     4922: 			Debug("Failed to get local key");
                   4923: 			$clientok = 0;
                   4924: 			shutdown($client, 3);
                   4925: 			close $client;
1.178     foxr     4926: 		    }
1.212     foxr     4927: 		} elsif ($inittype eq "ssl") {
                   4928: 		    my $key = SSLConnection($client);
                   4929: 		    if ($key) {
                   4930: 			$clientok = 1;
                   4931: 			my $cipherkey = pack("H32", $key);
                   4932: 			$cipher       = new IDEA($cipherkey);
                   4933: 			&logthis('<font color="green">'
                   4934: 				 ."Successfull ssl authentication with $clientname </font>");
                   4935: 			$keymode = "ssl";
                   4936: 	     
1.178     foxr     4937: 		    } else {
1.212     foxr     4938: 			$clientok = 0;
                   4939: 			close $client;
1.178     foxr     4940: 		    }
1.212     foxr     4941: 	   
                   4942: 		} else {
                   4943: 		    my $ok = InsecureConnection($client);
                   4944: 		    if($ok) {
                   4945: 			$clientok = 1;
                   4946: 			&logthis('<font color="green">'
                   4947: 				 ."Successful insecure authentication with $clientname </font>");
                   4948: 			print $client "ok\n";
                   4949: 			$keymode = "insecure";
1.178     foxr     4950: 		    } else {
1.212     foxr     4951: 			&logthis('<font color="yellow">'
                   4952: 				  ."Attempted insecure connection disallowed </font>");
                   4953: 			close $client;
                   4954: 			$clientok = 0;
1.178     foxr     4955: 			
                   4956: 		    }
                   4957: 		}
1.212     foxr     4958: 	    } else {
                   4959: 		&logthis(
                   4960: 			 "<font color='blue'>WARNING: "
                   4961: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   4962: 		&status('No init '.$clientip);
                   4963: 	    }
                   4964: 	    
                   4965: 	} else {
                   4966: 	    &logthis(
                   4967: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   4968: 	    &status('Hung up on '.$clientip);
                   4969: 	}
                   4970:  
                   4971: 	if ($clientok) {
                   4972: # ---------------- New known client connecting, could mean machine online again
                   4973: 	    
                   4974: 	    foreach my $id (keys(%hostip)) {
                   4975: 		if ($hostip{$id} ne $clientip ||
                   4976: 		    $hostip{$currenthostid} eq $clientip) {
                   4977: 		    # no need to try to do recon's to myself
                   4978: 		    next;
                   4979: 		}
                   4980: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
                   4981: 	    }
                   4982: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   4983: 	    &status('Will listen to '.$clientname);
                   4984: # ------------------------------------------------------------ Process requests
                   4985: 	    my $keep_going = 1;
                   4986: 	    my $user_input;
                   4987: 	    while(($user_input = get_request) && $keep_going) {
                   4988: 		alarm(120);
                   4989: 		Debug("Main: Got $user_input\n");
                   4990: 		$keep_going = &process_request($user_input);
1.178     foxr     4991: 		alarm(0);
1.212     foxr     4992: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     4993: 	    }
1.212     foxr     4994: 
1.59      www      4995: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     4996: 	}  else {
1.161     foxr     4997: 	    print $client "refused\n";
                   4998: 	    $client->close();
1.190     albertel 4999: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     5000: 		     ."Rejected client $clientip, closing connection</font>");
                   5001: 	}
1.212     foxr     5002:     }            
1.161     foxr     5003:     
1.1       albertel 5004: # =============================================================================
1.161     foxr     5005:     
1.190     albertel 5006:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     5007: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   5008:     
                   5009:     
                   5010:     # this exit is VERY important, otherwise the child will become
                   5011:     # a producer of more and more children, forking yourself into
                   5012:     # process death.
                   5013:     exit;
1.106     foxr     5014:     
1.78      foxr     5015: }
1.261     foxr     5016: #
                   5017: #   Determine if a user is an author for the indicated domain.
                   5018: #
                   5019: # Parameters:
                   5020: #    domain          - domain to check in .
                   5021: #    user            - Name of user to check.
                   5022: #
                   5023: # Return:
                   5024: #     1             - User is an author for domain.
                   5025: #     0             - User is not an author for domain.
                   5026: sub is_author {
                   5027:     my ($domain, $user) = @_;
                   5028: 
                   5029:     &Debug("is_author: $user @ $domain");
                   5030: 
                   5031:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   5032: 				 &GDBM_READER());
                   5033: 
                   5034:     #  Author role should show up as a key /domain/_au
1.78      foxr     5035: 
1.261     foxr     5036:     my $key   = "/$domain/_au";
                   5037:     my $value = $hashref->{$key};
1.78      foxr     5038: 
1.261     foxr     5039:     if(defined($value)) {
                   5040: 	&Debug("$user @ $domain is an author");
                   5041:     }
                   5042: 
                   5043:     return defined($value);
                   5044: }
1.78      foxr     5045: #
                   5046: #   Checks to see if the input roleput request was to set
                   5047: # an author role.  If so, invokes the lchtmldir script to set
                   5048: # up a correct public_html 
                   5049: # Parameters:
                   5050: #    request   - The request sent to the rolesput subchunk.
                   5051: #                We're looking for  /domain/_au
                   5052: #    domain    - The domain in which the user is having roles doctored.
                   5053: #    user      - Name of the user for which the role is being put.
                   5054: #    authtype  - The authentication type associated with the user.
                   5055: #
1.230     foxr     5056: sub manage_permissions
1.78      foxr     5057: {
1.192     foxr     5058: 
1.261     foxr     5059: 
1.192     foxr     5060:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     5061: 
1.261     foxr     5062:     &Debug("manage_permissions: $request $domain $user $authtype");
                   5063: 
1.78      foxr     5064:     # See if the request is of the form /$domain/_au
                   5065:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
                   5066: 	my $execdir = $perlvar{'lonDaemons'};
                   5067: 	my $userhome= "/home/$user" ;
1.134     albertel 5068: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261     foxr     5069: 	&Debug("Setting homedir permissions for $userhome");
1.78      foxr     5070: 	system("$execdir/lchtmldir $userhome $user $authtype");
                   5071:     }
                   5072: }
1.222     foxr     5073: 
                   5074: 
                   5075: #
                   5076: #  Return the full path of a user password file, whether it exists or not.
                   5077: # Parameters:
                   5078: #   domain     - Domain in which the password file lives.
                   5079: #   user       - name of the user.
                   5080: # Returns:
                   5081: #    Full passwd path:
                   5082: #
                   5083: sub password_path {
                   5084:     my ($domain, $user) = @_;
1.264     albertel 5085:     return &propath($domain, $user).'/passwd';
1.222     foxr     5086: }
                   5087: 
                   5088: #   Password Filename
                   5089: #   Returns the path to a passwd file given domain and user... only if
                   5090: #  it exists.
                   5091: # Parameters:
                   5092: #   domain    - Domain in which to search.
                   5093: #   user      - username.
                   5094: # Returns:
                   5095: #   - If the password file exists returns its path.
                   5096: #   - If the password file does not exist, returns undefined.
                   5097: #
                   5098: sub password_filename {
                   5099:     my ($domain, $user) = @_;
                   5100: 
                   5101:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   5102: 
                   5103:     my $path  = &password_path($domain, $user);
                   5104:     Debug("PasswordFilename got path: $path");
                   5105:     if(-e $path) {
                   5106: 	return $path;
                   5107:     } else {
                   5108: 	return undef;
                   5109:     }
                   5110: }
                   5111: 
                   5112: #
                   5113: #   Rewrite the contents of the user's passwd file.
                   5114: #  Parameters:
                   5115: #    domain    - domain of the user.
                   5116: #    name      - User's name.
                   5117: #    contents  - New contents of the file.
                   5118: # Returns:
                   5119: #   0    - Failed.
                   5120: #   1    - Success.
                   5121: #
                   5122: sub rewrite_password_file {
                   5123:     my ($domain, $user, $contents) = @_;
                   5124: 
                   5125:     my $file = &password_filename($domain, $user);
                   5126:     if (defined $file) {
                   5127: 	my $pf = IO::File->new(">$file");
                   5128: 	if($pf) {
                   5129: 	    print $pf "$contents\n";
                   5130: 	    return 1;
                   5131: 	} else {
                   5132: 	    return 0;
                   5133: 	}
                   5134:     } else {
                   5135: 	return 0;
                   5136:     }
                   5137: 
                   5138: }
                   5139: 
1.78      foxr     5140: #
1.222     foxr     5141: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     5142: 
                   5143: #     Returns the authorization type or nouser if there is no such user.
                   5144: #
1.222     foxr     5145: sub get_auth_type 
1.78      foxr     5146: {
1.192     foxr     5147: 
                   5148:     my ($domain, $user)  = @_;
1.78      foxr     5149: 
1.222     foxr     5150:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     5151:     my $proname    = &propath($domain, $user); 
                   5152:     my $passwdfile = "$proname/passwd";
                   5153:     if( -e $passwdfile ) {
                   5154: 	my $pf = IO::File->new($passwdfile);
                   5155: 	my $realpassword = <$pf>;
                   5156: 	chomp($realpassword);
1.79      foxr     5157: 	Debug("Password info = $realpassword\n");
1.78      foxr     5158: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     5159: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  5160: 	return "$authtype:$contentpwd";     
1.224     foxr     5161:     } else {
1.79      foxr     5162: 	Debug("Returning nouser");
1.78      foxr     5163: 	return "nouser";
                   5164:     }
1.1       albertel 5165: }
                   5166: 
1.220     foxr     5167: #
                   5168: #  Validate a user given their domain, name and password.  This utility
                   5169: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   5170: #  to validate the login credentials of a user.
                   5171: # Parameters:
                   5172: #    $domain    - The domain being logged into (this is required due to
                   5173: #                 the capability for multihomed systems.
                   5174: #    $user      - The name of the user being validated.
                   5175: #    $password  - The user's propoposed password.
                   5176: #
                   5177: # Returns:
                   5178: #     1        - The domain,user,pasword triplet corresponds to a valid
                   5179: #                user.
                   5180: #     0        - The domain,user,password triplet is not a valid user.
                   5181: #
                   5182: sub validate_user {
                   5183:     my ($domain, $user, $password) = @_;
                   5184: 
                   5185: 
                   5186:     # Why negative ~pi you may well ask?  Well this function is about
                   5187:     # authentication, and therefore very important to get right.
                   5188:     # I've initialized the flag that determines whether or not I've 
                   5189:     # validated correctly to a value it's not supposed to get.
                   5190:     # At the end of this function. I'll ensure that it's not still that
                   5191:     # value so we don't just wind up returning some accidental value
                   5192:     # as a result of executing an unforseen code path that
1.249     foxr     5193:     # did not set $validated.  At the end of valid execution paths,
                   5194:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     5195: 
                   5196:     my $validated = -3.14159;
                   5197: 
                   5198:     #  How we authenticate is determined by the type of authentication
                   5199:     #  the user has been assigned.  If the authentication type is
                   5200:     #  "nouser", the user does not exist so we will return 0.
                   5201: 
1.222     foxr     5202:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     5203:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   5204: 
                   5205:     my $null = pack("C",0);	# Used by kerberos auth types.
                   5206: 
                   5207:     if ($howpwd ne 'nouser') {
                   5208: 
                   5209: 	if($howpwd eq "internal") { # Encrypted is in local password file.
                   5210: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
                   5211: 	}
                   5212: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   5213: 	    $contentpwd = (getpwnam($user))[1];
                   5214: 	    if($contentpwd) {
                   5215: 		if($contentpwd eq 'x') { # Shadow password file...
                   5216: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   5217: 		    open PWAUTH,  "|$pwauth_path" or
                   5218: 			die "Cannot invoke authentication";
                   5219: 		    print PWAUTH "$user\n$password\n";
                   5220: 		    close PWAUTH;
                   5221: 		    $validated = ! $?;
                   5222: 
                   5223: 		} else { 	         # Passwords in /etc/passwd. 
                   5224: 		    $validated = (crypt($password,
                   5225: 					$contentpwd) eq $contentpwd);
                   5226: 		}
                   5227: 	    } else {
                   5228: 		$validated = 0;
                   5229: 	    }
                   5230: 	}
                   5231: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   5232: 	    if(! ($password =~ /$null/) ) {
                   5233: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   5234: 							   "",
                   5235: 							   $contentpwd,,
                   5236: 							   'krbtgt',
                   5237: 							   $contentpwd,
                   5238: 							   1,
                   5239: 							   $password);
                   5240: 		if(!$k4error) {
                   5241: 		    $validated = 1;
1.224     foxr     5242: 		} else {
1.220     foxr     5243: 		    $validated = 0;
                   5244: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   5245: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   5246: 		}
1.224     foxr     5247: 	    } else {
1.220     foxr     5248: 		$validated = 0; # Password has a match with null.
                   5249: 	    }
1.224     foxr     5250: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220     foxr     5251: 	    if(!($password =~ /$null/)) { # Null password not allowed.
                   5252: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   5253: 							  .$contentpwd);
                   5254: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   5255: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   5256: 		my $credentials= &Authen::Krb5::cc_default();
                   5257: 		$credentials->initialize($krbclient);
1.270     matthew  5258: 		my $krbreturn  = &Authen::Krb5::get_in_tkt_with_password($krbclient,
1.220     foxr     5259: 									 $krbserver,
                   5260: 									 $password,
                   5261: 									 $credentials);
                   5262: 		$validated = ($krbreturn == 1);
1.224     foxr     5263: 	    } else {
1.220     foxr     5264: 		$validated = 0;
                   5265: 	    }
1.224     foxr     5266: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     5267: 	    #  Authenticate via installation specific authentcation method:
                   5268: 	    $validated = &localauth::localauth($user, 
                   5269: 					       $password, 
                   5270: 					       $contentpwd);
1.224     foxr     5271: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     5272: 	    $validated = 0;
                   5273: 	}
                   5274:     } else {
                   5275: 	$validated = 0;
                   5276:     }
                   5277:     #
                   5278:     #  $validated has the correct stat of the authentication:
                   5279:     #
                   5280: 
                   5281:     unless ($validated != -3.14159) {
1.249     foxr     5282: 	#  I >really really< want to know if this happens.
                   5283: 	#  since it indicates that user authentication is badly
                   5284: 	#  broken in some code path.
                   5285:         #
                   5286: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     5287:     }
                   5288:     return $validated;
                   5289: }
                   5290: 
                   5291: 
1.84      albertel 5292: sub addline {
                   5293:     my ($fname,$hostid,$ip,$newline)=@_;
                   5294:     my $contents;
                   5295:     my $found=0;
                   5296:     my $expr='^'.$hostid.':'.$ip.':';
                   5297:     $expr =~ s/\./\\\./g;
1.134     albertel 5298:     my $sh;
1.84      albertel 5299:     if ($sh=IO::File->new("$fname.subscription")) {
                   5300: 	while (my $subline=<$sh>) {
                   5301: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   5302: 	}
                   5303: 	$sh->close();
                   5304:     }
                   5305:     $sh=IO::File->new(">$fname.subscription");
                   5306:     if ($contents) { print $sh $contents; }
                   5307:     if ($newline) { print $sh $newline; }
                   5308:     $sh->close();
                   5309:     return $found;
1.86      www      5310: }
                   5311: 
1.234     foxr     5312: sub get_chat {
1.122     www      5313:     my ($cdom,$cname,$udom,$uname)=@_;
1.87      www      5314:     my %hash;
                   5315:     my $proname=&propath($cdom,$cname);
                   5316:     my @entries=();
1.88      albertel 5317:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   5318: 	    &GDBM_READER(),0640)) {
                   5319: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   5320: 	untie %hash;
1.123     www      5321:     }
1.124     www      5322:     my @participants=();
1.134     albertel 5323:     my $cutoff=time-60;
1.123     www      5324:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124     www      5325: 	    &GDBM_WRCREAT(),0640)) {
                   5326:         $hash{$uname.':'.$udom}=time;
1.123     www      5327:         foreach (sort keys %hash) {
                   5328: 	    if ($hash{$_}>$cutoff) {
1.124     www      5329: 		$participants[$#participants+1]='active_participant:'.$_;
1.123     www      5330:             }
                   5331:         }
                   5332:         untie %hash;
1.86      www      5333:     }
1.124     www      5334:     return (@participants,@entries);
1.86      www      5335: }
                   5336: 
1.234     foxr     5337: sub chat_add {
1.88      albertel 5338:     my ($cdom,$cname,$newchat)=@_;
                   5339:     my %hash;
                   5340:     my $proname=&propath($cdom,$cname);
                   5341:     my @entries=();
1.142     www      5342:     my $time=time;
1.88      albertel 5343:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
                   5344: 	    &GDBM_WRCREAT(),0640)) {
                   5345: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
                   5346: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   5347: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   5348: 	my $newid=$time.'_000000';
                   5349: 	if ($thentime==$time) {
                   5350: 	    $idnum=~s/^0+//;
                   5351: 	    $idnum++;
                   5352: 	    $idnum=substr('000000'.$idnum,-6,6);
                   5353: 	    $newid=$time.'_'.$idnum;
                   5354: 	}
                   5355: 	$hash{$newid}=$newchat;
                   5356: 	my $expired=$time-3600;
                   5357: 	foreach (keys %hash) {
                   5358: 	    my ($thistime)=($_=~/(\d+)\_/);
                   5359: 	    if ($thistime<$expired) {
1.89      www      5360: 		delete $hash{$_};
1.88      albertel 5361: 	    }
                   5362: 	}
                   5363: 	untie %hash;
1.142     www      5364:     }
                   5365:     {
                   5366: 	my $hfh;
                   5367: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
                   5368: 	    print $hfh "$time:".&unescape($newchat)."\n";
                   5369: 	}
1.86      www      5370:     }
1.84      albertel 5371: }
                   5372: 
                   5373: sub unsub {
                   5374:     my ($fname,$clientip)=@_;
                   5375:     my $result;
1.188     foxr     5376:     my $unsubs = 0;		# Number of successful unsubscribes:
                   5377: 
                   5378: 
                   5379:     # An old way subscriptions were handled was to have a 
                   5380:     # subscription marker file:
                   5381: 
                   5382:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     5383:     if (unlink("$fname.$clientname")) {
1.188     foxr     5384: 	$unsubs++;		# Successful unsub via marker file.
                   5385:     } 
                   5386: 
                   5387:     # The more modern way to do it is to have a subscription list
                   5388:     # file:
                   5389: 
1.84      albertel 5390:     if (-e "$fname.subscription") {
1.161     foxr     5391: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     5392: 	if ($found) { 
                   5393: 	    $unsubs++;
                   5394: 	}
                   5395:     } 
                   5396: 
                   5397:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   5398:     #  resource we can return ok:
                   5399: 
                   5400:     if($unsubs) {
                   5401: 	$result = "ok\n";
1.84      albertel 5402:     } else {
1.188     foxr     5403: 	$result = "not_subscribed\n";
1.84      albertel 5404:     }
1.188     foxr     5405: 
1.84      albertel 5406:     return $result;
                   5407: }
                   5408: 
1.101     www      5409: sub currentversion {
                   5410:     my $fname=shift;
                   5411:     my $version=-1;
                   5412:     my $ulsdir='';
                   5413:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   5414:        $ulsdir=$1;
                   5415:     }
1.114     albertel 5416:     my ($fnamere1,$fnamere2);
                   5417:     # remove version if already specified
1.101     www      5418:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 5419:     # get the bits that go before and after the version number
                   5420:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   5421: 	$fnamere1=$1;
                   5422: 	$fnamere2='.'.$2;
                   5423:     }
1.101     www      5424:     if (-e $fname) { $version=1; }
                   5425:     if (-e $ulsdir) {
1.134     albertel 5426: 	if(-d $ulsdir) {
                   5427: 	    if (opendir(LSDIR,$ulsdir)) {
                   5428: 		my $ulsfn;
                   5429: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      5430: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 5431: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   5432: 		    unless (-l $thisfile) {
1.160     www      5433: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 5434: 			    if ($1>$version) { $version=$1; }
                   5435: 			}
                   5436: 		    }
                   5437: 		}
                   5438: 		closedir(LSDIR);
                   5439: 		$version++;
                   5440: 	    }
                   5441: 	}
                   5442:     }
                   5443:     return $version;
1.101     www      5444: }
                   5445: 
                   5446: sub thisversion {
                   5447:     my $fname=shift;
                   5448:     my $version=-1;
                   5449:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   5450: 	$version=$1;
                   5451:     }
                   5452:     return $version;
                   5453: }
                   5454: 
1.84      albertel 5455: sub subscribe {
                   5456:     my ($userinput,$clientip)=@_;
                   5457:     my $result;
                   5458:     my ($cmd,$fname)=split(/:/,$userinput);
                   5459:     my $ownership=&ishome($fname);
                   5460:     if ($ownership eq 'owner') {
1.101     www      5461: # explitly asking for the current version?
                   5462:         unless (-e $fname) {
                   5463:             my $currentversion=&currentversion($fname);
                   5464: 	    if (&thisversion($fname)==$currentversion) {
                   5465:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   5466: 		    my $root=$1;
                   5467:                     my $extension=$2;
                   5468:                     symlink($root.'.'.$extension,
                   5469:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      5470:                     unless ($extension=~/\.meta$/) {
                   5471:                        symlink($root.'.'.$extension.'.meta',
                   5472:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   5473: 		    }
1.101     www      5474:                 }
                   5475:             }
                   5476:         }
1.84      albertel 5477: 	if (-e $fname) {
                   5478: 	    if (-d $fname) {
                   5479: 		$result="directory\n";
                   5480: 	    } else {
1.161     foxr     5481: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 5482: 		my $now=time;
1.161     foxr     5483: 		my $found=&addline($fname,$clientname,$clientip,
                   5484: 				   "$clientname:$clientip:$now\n");
1.84      albertel 5485: 		if ($found) { $result="$fname\n"; }
                   5486: 		# if they were subscribed to only meta data, delete that
                   5487:                 # subscription, when you subscribe to a file you also get
                   5488:                 # the metadata
                   5489: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   5490: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
                   5491: 		$fname="http://$thisserver/".$fname;
                   5492: 		$result="$fname\n";
                   5493: 	    }
                   5494: 	} else {
                   5495: 	    $result="not_found\n";
                   5496: 	}
                   5497:     } else {
                   5498: 	$result="rejected\n";
                   5499:     }
                   5500:     return $result;
                   5501: }
1.91      albertel 5502: 
                   5503: sub make_passwd_file {
1.98      foxr     5504:     my ($uname, $umode,$npass,$passfilename)=@_;
1.91      albertel 5505:     my $result="ok\n";
                   5506:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   5507: 	{
                   5508: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5509: 	    if ($pf) {
                   5510: 		print $pf "$umode:$npass\n";
                   5511: 	    } else {
                   5512: 		$result = "pass_file_failed_error";
                   5513: 	    }
1.91      albertel 5514: 	}
                   5515:     } elsif ($umode eq 'internal') {
                   5516: 	my $salt=time;
                   5517: 	$salt=substr($salt,6,2);
                   5518: 	my $ncpass=crypt($npass,$salt);
                   5519: 	{
                   5520: 	    &Debug("Creating internal auth");
                   5521: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5522: 	    if($pf) {
                   5523: 		print $pf "internal:$ncpass\n"; 
                   5524: 	    } else {
                   5525: 		$result = "pass_file_failed_error";
                   5526: 	    }
1.91      albertel 5527: 	}
                   5528:     } elsif ($umode eq 'localauth') {
                   5529: 	{
                   5530: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     5531: 	    if($pf) {
                   5532: 		print $pf "localauth:$npass\n";
                   5533: 	    } else {
                   5534: 		$result = "pass_file_failed_error";
                   5535: 	    }
1.91      albertel 5536: 	}
                   5537:     } elsif ($umode eq 'unix') {
                   5538: 	{
1.186     foxr     5539: 	    #
                   5540: 	    #  Don't allow the creation of privileged accounts!!! that would
                   5541: 	    #  be real bad!!!
                   5542: 	    #
                   5543: 	    my $uid = getpwnam($uname);
                   5544: 	    if((defined $uid) && ($uid == 0)) {
                   5545: 		&logthis(">>>Attempted to create privilged account blocked");
                   5546: 		return "no_priv_account_error\n";
                   5547: 	    }
                   5548: 
1.223     foxr     5549: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224     foxr     5550: 
                   5551: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
1.91      albertel 5552: 	    {
                   5553: 		&Debug("Executing external: ".$execpath);
1.98      foxr     5554: 		&Debug("user  = ".$uname.", Password =". $npass);
1.132     matthew  5555: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91      albertel 5556: 		print $se "$uname\n";
                   5557: 		print $se "$npass\n";
                   5558: 		print $se "$npass\n";
1.223     foxr     5559: 		print $se "$lc_error_file\n"; # Status -> unique file.
1.97      foxr     5560: 	    }
1.285   ! foxr     5561: 	    if (-r $lc_error_file) {
        !          5562: 		&Debug("Opening error file: $lc_error_file");
        !          5563: 		my $error = IO::File->new("< $lc_error_file");
        !          5564: 		my $useraddok = <$error>;
        !          5565: 		$error->close;
        !          5566: 		unlink($lc_error_file);
        !          5567: 		
        !          5568: 		chomp $useraddok;
        !          5569: 	
        !          5570: 		if($useraddok > 0) {
        !          5571: 		    my $error_text = &lcuseraddstrerror($useraddok);
        !          5572: 		    &logthis("Failed lcuseradd: $error_text");
        !          5573: 		    $result = "lcuseradd_failed:$error_text\n";
        !          5574: 		}  else {
        !          5575: 		    my $pf = IO::File->new(">$passfilename");
        !          5576: 		    if($pf) {
        !          5577: 			print $pf "unix:\n";
        !          5578: 		    } else {
        !          5579: 			$result = "pass_file_failed_error";
        !          5580: 		    }
        !          5581: 		}
1.224     foxr     5582: 	    }  else {
1.285   ! foxr     5583: 		&Debug("Could not locate lcuseradd error: $lc_error_file");
        !          5584: 		$result="bug_lcuseradd_no_output_file";
1.91      albertel 5585: 	    }
                   5586: 	}
                   5587:     } elsif ($umode eq 'none') {
                   5588: 	{
1.223     foxr     5589: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     5590: 	    if($pf) {
                   5591: 		print $pf "none:\n";
                   5592: 	    } else {
                   5593: 		$result = "pass_file_failed_error";
                   5594: 	    }
1.91      albertel 5595: 	}
                   5596:     } else {
                   5597: 	$result="auth_mode_error\n";
                   5598:     }
                   5599:     return $result;
1.121     albertel 5600: }
                   5601: 
1.265     albertel 5602: sub convert_photo {
                   5603:     my ($start,$dest)=@_;
                   5604:     system("convert $start $dest");
                   5605: }
                   5606: 
1.121     albertel 5607: sub sethost {
                   5608:     my ($remotereq) = @_;
                   5609:     my (undef,$hostid)=split(/:/,$remotereq);
                   5610:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
                   5611:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200     matthew  5612: 	$currenthostid  =$hostid;
1.121     albertel 5613: 	$currentdomainid=$hostdom{$hostid};
                   5614: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
                   5615:     } else {
                   5616: 	&logthis("Requested host id $hostid not an alias of ".
                   5617: 		 $perlvar{'lonHostID'}." refusing connection");
                   5618: 	return 'unable_to_set';
                   5619:     }
                   5620:     return 'ok';
                   5621: }
                   5622: 
                   5623: sub version {
                   5624:     my ($userinput)=@_;
                   5625:     $remoteVERSION=(split(/:/,$userinput))[1];
                   5626:     return "version:$VERSION";
1.127     albertel 5627: }
1.178     foxr     5628: 
1.128     albertel 5629: #There is a copy of this in lonnet.pm
1.127     albertel 5630: sub userload {
                   5631:     my $numusers=0;
                   5632:     {
                   5633: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                   5634: 	my $filename;
                   5635: 	my $curtime=time;
                   5636: 	while ($filename=readdir(LONIDS)) {
                   5637: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.138     albertel 5638: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159     albertel 5639: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.127     albertel 5640: 	}
                   5641: 	closedir(LONIDS);
                   5642:     }
                   5643:     my $userloadpercent=0;
                   5644:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                   5645:     if ($maxuserload) {
1.129     albertel 5646: 	$userloadpercent=100*$numusers/$maxuserload;
1.127     albertel 5647:     }
1.130     albertel 5648:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127     albertel 5649:     return $userloadpercent;
1.91      albertel 5650: }
                   5651: 
1.205     raeburn  5652: # Routines for serializing arrays and hashes (copies from lonnet)
                   5653: 
                   5654: sub array2str {
                   5655:   my (@array) = @_;
                   5656:   my $result=&arrayref2str(\@array);
                   5657:   $result=~s/^__ARRAY_REF__//;
                   5658:   $result=~s/__END_ARRAY_REF__$//;
                   5659:   return $result;
                   5660: }
                   5661:                                                                                  
                   5662: sub arrayref2str {
                   5663:   my ($arrayref) = @_;
                   5664:   my $result='__ARRAY_REF__';
                   5665:   foreach my $elem (@$arrayref) {
                   5666:     if(ref($elem) eq 'ARRAY') {
                   5667:       $result.=&arrayref2str($elem).'&';
                   5668:     } elsif(ref($elem) eq 'HASH') {
                   5669:       $result.=&hashref2str($elem).'&';
                   5670:     } elsif(ref($elem)) {
                   5671:       #print("Got a ref of ".(ref($elem))." skipping.");
                   5672:     } else {
                   5673:       $result.=&escape($elem).'&';
                   5674:     }
                   5675:   }
                   5676:   $result=~s/\&$//;
                   5677:   $result .= '__END_ARRAY_REF__';
                   5678:   return $result;
                   5679: }
                   5680:                                                                                  
                   5681: sub hash2str {
                   5682:   my (%hash) = @_;
                   5683:   my $result=&hashref2str(\%hash);
                   5684:   $result=~s/^__HASH_REF__//;
                   5685:   $result=~s/__END_HASH_REF__$//;
                   5686:   return $result;
                   5687: }
                   5688:                                                                                  
                   5689: sub hashref2str {
                   5690:   my ($hashref)=@_;
                   5691:   my $result='__HASH_REF__';
                   5692:   foreach (sort(keys(%$hashref))) {
                   5693:     if (ref($_) eq 'ARRAY') {
                   5694:       $result.=&arrayref2str($_).'=';
                   5695:     } elsif (ref($_) eq 'HASH') {
                   5696:       $result.=&hashref2str($_).'=';
                   5697:     } elsif (ref($_)) {
                   5698:       $result.='=';
                   5699:       #print("Got a ref of ".(ref($_))." skipping.");
                   5700:     } else {
                   5701:         if ($_) {$result.=&escape($_).'=';} else { last; }
                   5702:     }
                   5703: 
                   5704:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   5705:       $result.=&arrayref2str($hashref->{$_}).'&';
                   5706:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   5707:       $result.=&hashref2str($hashref->{$_}).'&';
                   5708:     } elsif(ref($hashref->{$_})) {
                   5709:        $result.='&';
                   5710:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
                   5711:     } else {
                   5712:       $result.=&escape($hashref->{$_}).'&';
                   5713:     }
                   5714:   }
                   5715:   $result=~s/\&$//;
                   5716:   $result .= '__END_HASH_REF__';
                   5717:   return $result;
                   5718: }
1.200     matthew  5719: 
1.61      harris41 5720: # ----------------------------------- POD (plain old documentation, CPAN style)
                   5721: 
                   5722: =head1 NAME
                   5723: 
                   5724: lond - "LON Daemon" Server (port "LOND" 5663)
                   5725: 
                   5726: =head1 SYNOPSIS
                   5727: 
1.74      harris41 5728: Usage: B<lond>
                   5729: 
                   5730: Should only be run as user=www.  This is a command-line script which
                   5731: is invoked by B<loncron>.  There is no expectation that a typical user
                   5732: will manually start B<lond> from the command-line.  (In other words,
                   5733: DO NOT START B<lond> YOURSELF.)
1.61      harris41 5734: 
                   5735: =head1 DESCRIPTION
                   5736: 
1.74      harris41 5737: There are two characteristics associated with the running of B<lond>,
                   5738: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   5739: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   5740: subscriptions, etc).  These are described in two large
                   5741: sections below.
                   5742: 
                   5743: B<PROCESS MANAGEMENT>
                   5744: 
1.61      harris41 5745: Preforker - server who forks first. Runs as a daemon. HUPs.
                   5746: Uses IDEA encryption
                   5747: 
1.74      harris41 5748: B<lond> forks off children processes that correspond to the other servers
                   5749: in the network.  Management of these processes can be done at the
                   5750: parent process level or the child process level.
                   5751: 
                   5752: B<logs/lond.log> is the location of log messages.
                   5753: 
                   5754: The process management is now explained in terms of linux shell commands,
                   5755: subroutines internal to this code, and signal assignments:
                   5756: 
                   5757: =over 4
                   5758: 
                   5759: =item *
                   5760: 
                   5761: PID is stored in B<logs/lond.pid>
                   5762: 
                   5763: This is the process id number of the parent B<lond> process.
                   5764: 
                   5765: =item *
                   5766: 
                   5767: SIGTERM and SIGINT
                   5768: 
                   5769: Parent signal assignment:
                   5770:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   5771: 
                   5772: Child signal assignment:
                   5773:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   5774: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   5775:  to restart a new child.)
                   5776: 
                   5777: Command-line invocations:
                   5778:  B<kill> B<-s> SIGTERM I<PID>
                   5779:  B<kill> B<-s> SIGINT I<PID>
                   5780: 
                   5781: Subroutine B<HUNTSMAN>:
                   5782:  This is only invoked for the B<lond> parent I<PID>.
                   5783: This kills all the children, and then the parent.
                   5784: The B<lonc.pid> file is cleared.
                   5785: 
                   5786: =item *
                   5787: 
                   5788: SIGHUP
                   5789: 
                   5790: Current bug:
                   5791:  This signal can only be processed the first time
                   5792: on the parent process.  Subsequent SIGHUP signals
                   5793: have no effect.
                   5794: 
                   5795: Parent signal assignment:
                   5796:  $SIG{HUP}  = \&HUPSMAN;
                   5797: 
                   5798: Child signal assignment:
                   5799:  none (nothing happens)
                   5800: 
                   5801: Command-line invocations:
                   5802:  B<kill> B<-s> SIGHUP I<PID>
                   5803: 
                   5804: Subroutine B<HUPSMAN>:
                   5805:  This is only invoked for the B<lond> parent I<PID>,
                   5806: This kills all the children, and then the parent.
                   5807: The B<lond.pid> file is cleared.
                   5808: 
                   5809: =item *
                   5810: 
                   5811: SIGUSR1
                   5812: 
                   5813: Parent signal assignment:
                   5814:  $SIG{USR1} = \&USRMAN;
                   5815: 
                   5816: Child signal assignment:
                   5817:  $SIG{USR1}= \&logstatus;
                   5818: 
                   5819: Command-line invocations:
                   5820:  B<kill> B<-s> SIGUSR1 I<PID>
                   5821: 
                   5822: Subroutine B<USRMAN>:
                   5823:  When invoked for the B<lond> parent I<PID>,
                   5824: SIGUSR1 is sent to all the children, and the status of
                   5825: each connection is logged.
1.144     foxr     5826: 
                   5827: =item *
                   5828: 
                   5829: SIGUSR2
                   5830: 
                   5831: Parent Signal assignment:
                   5832:     $SIG{USR2} = \&UpdateHosts
                   5833: 
                   5834: Child signal assignment:
                   5835:     NONE
                   5836: 
1.74      harris41 5837: 
                   5838: =item *
                   5839: 
                   5840: SIGCHLD
                   5841: 
                   5842: Parent signal assignment:
                   5843:  $SIG{CHLD} = \&REAPER;
                   5844: 
                   5845: Child signal assignment:
                   5846:  none
                   5847: 
                   5848: Command-line invocations:
                   5849:  B<kill> B<-s> SIGCHLD I<PID>
                   5850: 
                   5851: Subroutine B<REAPER>:
                   5852:  This is only invoked for the B<lond> parent I<PID>.
                   5853: Information pertaining to the child is removed.
                   5854: The socket port is cleaned up.
                   5855: 
                   5856: =back
                   5857: 
                   5858: B<SERVER-SIDE ACTIVITIES>
                   5859: 
                   5860: Server-side information can be accepted in an encrypted or non-encrypted
                   5861: method.
                   5862: 
                   5863: =over 4
                   5864: 
                   5865: =item ping
                   5866: 
                   5867: Query a client in the hosts.tab table; "Are you there?"
                   5868: 
                   5869: =item pong
                   5870: 
                   5871: Respond to a ping query.
                   5872: 
                   5873: =item ekey
                   5874: 
                   5875: Read in encrypted key, make cipher.  Respond with a buildkey.
                   5876: 
                   5877: =item load
                   5878: 
                   5879: Respond with CPU load based on a computation upon /proc/loadavg.
                   5880: 
                   5881: =item currentauth
                   5882: 
                   5883: Reply with current authentication information (only over an
                   5884: encrypted channel).
                   5885: 
                   5886: =item auth
                   5887: 
                   5888: Only over an encrypted channel, reply as to whether a user's
                   5889: authentication information can be validated.
                   5890: 
                   5891: =item passwd
                   5892: 
                   5893: Allow for a password to be set.
                   5894: 
                   5895: =item makeuser
                   5896: 
                   5897: Make a user.
                   5898: 
                   5899: =item passwd
                   5900: 
                   5901: Allow for authentication mechanism and password to be changed.
                   5902: 
                   5903: =item home
1.61      harris41 5904: 
1.74      harris41 5905: Respond to a question "are you the home for a given user?"
                   5906: 
                   5907: =item update
                   5908: 
                   5909: Update contents of a subscribed resource.
                   5910: 
                   5911: =item unsubscribe
                   5912: 
                   5913: The server is unsubscribing from a resource.
                   5914: 
                   5915: =item subscribe
                   5916: 
                   5917: The server is subscribing to a resource.
                   5918: 
                   5919: =item log
                   5920: 
                   5921: Place in B<logs/lond.log>
                   5922: 
                   5923: =item put
                   5924: 
                   5925: stores hash in namespace
                   5926: 
1.230     foxr     5927: =item rolesputy
1.74      harris41 5928: 
                   5929: put a role into a user's environment
                   5930: 
                   5931: =item get
                   5932: 
                   5933: returns hash with keys from array
                   5934: reference filled in from namespace
                   5935: 
                   5936: =item eget
                   5937: 
                   5938: returns hash with keys from array
                   5939: reference filled in from namesp (encrypts the return communication)
                   5940: 
                   5941: =item rolesget
                   5942: 
                   5943: get a role from a user's environment
                   5944: 
                   5945: =item del
                   5946: 
                   5947: deletes keys out of array from namespace
                   5948: 
                   5949: =item keys
                   5950: 
                   5951: returns namespace keys
                   5952: 
                   5953: =item dump
                   5954: 
                   5955: dumps the complete (or key matching regexp) namespace into a hash
                   5956: 
                   5957: =item store
                   5958: 
                   5959: stores hash permanently
                   5960: for this url; hashref needs to be given and should be a \%hashname; the
                   5961: remaining args aren't required and if they aren't passed or are '' they will
                   5962: be derived from the ENV
                   5963: 
                   5964: =item restore
                   5965: 
                   5966: returns a hash for a given url
                   5967: 
                   5968: =item querysend
                   5969: 
                   5970: Tells client about the lonsql process that has been launched in response
                   5971: to a sent query.
                   5972: 
                   5973: =item queryreply
                   5974: 
                   5975: Accept information from lonsql and make appropriate storage in temporary
                   5976: file space.
                   5977: 
                   5978: =item idput
                   5979: 
                   5980: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   5981: for each student, defined perhaps by the institutional Registrar.)
                   5982: 
                   5983: =item idget
                   5984: 
                   5985: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   5986: for each student, defined perhaps by the institutional Registrar.)
                   5987: 
                   5988: =item tmpput
                   5989: 
                   5990: Accept and store information in temporary space.
                   5991: 
                   5992: =item tmpget
                   5993: 
                   5994: Send along temporarily stored information.
                   5995: 
                   5996: =item ls
                   5997: 
                   5998: List part of a user's directory.
                   5999: 
1.135     foxr     6000: =item pushtable
                   6001: 
                   6002: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   6003: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   6004: must be restored manually in case of a problem with the new table file.
                   6005: pushtable requires that the request be encrypted and validated via
                   6006: ValidateManager.  The form of the command is:
                   6007: enc:pushtable tablename <tablecontents> \n
                   6008: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   6009: cleartext newline.
                   6010: 
1.74      harris41 6011: =item Hanging up (exit or init)
                   6012: 
                   6013: What to do when a client tells the server that they (the client)
                   6014: are leaving the network.
                   6015: 
                   6016: =item unknown command
                   6017: 
                   6018: If B<lond> is sent an unknown command (not in the list above),
                   6019: it replys to the client "unknown_cmd".
1.135     foxr     6020: 
1.74      harris41 6021: 
                   6022: =item UNKNOWN CLIENT
                   6023: 
                   6024: If the anti-spoofing algorithm cannot verify the client,
                   6025: the client is rejected (with a "refused" message sent
                   6026: to the client, and the connection is closed.
                   6027: 
                   6028: =back
1.61      harris41 6029: 
                   6030: =head1 PREREQUISITES
                   6031: 
                   6032: IO::Socket
                   6033: IO::File
                   6034: Apache::File
                   6035: Symbol
                   6036: POSIX
                   6037: Crypt::IDEA
                   6038: LWP::UserAgent()
                   6039: GDBM_File
                   6040: Authen::Krb4
1.91      albertel 6041: Authen::Krb5
1.61      harris41 6042: 
                   6043: =head1 COREQUISITES
                   6044: 
                   6045: =head1 OSNAMES
                   6046: 
                   6047: linux
                   6048: 
                   6049: =head1 SCRIPT CATEGORIES
                   6050: 
                   6051: Server/Process
                   6052: 
                   6053: =cut

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