Annotation of loncom/lond, revision 1.370

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

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