Annotation of loncom/lond, revision 1.308

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

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