Annotation of loncom/lond, revision 1.237

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

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