File:  [LON-CAPA] / loncom / lond
Revision 1.248: download - view: text, annotated - select for diffs
Fri Sep 3 10:13:59 2004 UTC (19 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Incorporated the auto-enroll support into handlerized functions however:
- Need to get Stuart to test this since I don't know how.
- Left the old code in so that if there are huge problems, one
  can just remove the handler registrations and the code should
  work again.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.248 2004/09/03 10:13:59 foxr Exp $
    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
   13: # the Free Software Foundation; either version 2 of the License, or 
   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
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: 
   28: 
   29: # http://www.lon-capa.org/
   30: #
   31: 
   32: use strict;
   33: use lib '/home/httpd/lib/perl/';
   34: use LONCAPA::Configuration;
   35: 
   36: use IO::Socket;
   37: use IO::File;
   38: #use Apache::File;
   39: use Symbol;
   40: use POSIX;
   41: use Crypt::IDEA;
   42: use LWP::UserAgent();
   43: use GDBM_File;
   44: use Authen::Krb4;
   45: use Authen::Krb5;
   46: use lib '/home/httpd/lib/perl/';
   47: use localauth;
   48: use localenroll;
   49: use File::Copy;
   50: use LONCAPA::ConfigFileEdit;
   51: use LONCAPA::lonlocal;
   52: use LONCAPA::lonssl;
   53: use Fcntl qw(:flock);
   54: 
   55: my $DEBUG = 0;		       # Non zero to enable debug log entries.
   56: 
   57: my $status='';
   58: my $lastlog='';
   59: 
   60: my $VERSION='$Revision: 1.248 $'; #' stupid emacs
   61: my $remoteVERSION;
   62: my $currenthostid="default";
   63: my $currentdomainid;
   64: 
   65: my $client;
   66: my $clientip;			# IP address of client.
   67: my $clientdns;			# DNS name of client.
   68: my $clientname;			# LonCAPA name of client.
   69: 
   70: my $server;
   71: my $thisserver;			# DNS of us.
   72: 
   73: my $keymode;
   74: 
   75: my $cipher;			# Cipher key negotiated with client
   76: my $tmpsnum = 0;		# Id of tmpputs.
   77: 
   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: #
   84: 
   85: my $ConnectionType;
   86: 
   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.
   91: 
   92: my %managers;			# Ip -> manager names
   93: 
   94: my %perlvar;			# Will have the apache conf defined perl vars.
   95: 
   96: #
   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: #
  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",
  125: 		   "lcpasswd User already exists", 
  126:                    "lcpasswd Something went wrong with user addition.",
  127: 		    "lcpasswd Password mismatch",
  128: 		    "lcpasswd Error filename is invalid");
  129: 
  130: 
  131: #  The array below are lcuseradd error strings.:
  132: 
  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");
  148: 
  149: 
  150: 
  151: #
  152: #   Statistics that are maintained and dislayed in the status line.
  153: #
  154: my $Transactions = 0;		# Number of attempted transactions.
  155: my $Failures     = 0;		# Number of transcations failed.
  156: 
  157: #   ResetStatistics: 
  158: #      Resets the statistics counters:
  159: #
  160: sub ResetStatistics {
  161:     $Transactions = 0;
  162:     $Failures     = 0;
  163: }
  164: 
  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;
  195:     }  else {
  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;
  326:     } else {
  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: 
  335: #
  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: }
  351: 
  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: }
  364: 
  365: 
  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: 
  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
  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: 	    #
  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:    }
  412: }
  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: 
  424:     return isManager;
  425: }
  426: #
  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 {
  438: 
  439:     my ($oldfile, $newfile) = @_;
  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: }
  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: 
  498:  foreach my $line (split(/\n/,$contents)) {
  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) {
  503:           my $ip = gethostbyname($name);
  504:           my $ipnew = inet_ntoa($ip);
  505:          $ip = $ipnew;
  506: 		#  Reconstruct the host line and append to adjusted:
  507: 		
  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";
  513: 		
  514:       } else {		# Not me, pass unmodified.
  515: 		   $adjusted .= $line."\n";
  516:       }
  517: 	} else {                  # Blank or comment never re-written.
  518: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
  519: 	}
  520:  }
  521:  return $adjusted;
  522: }
  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 {
  539: 
  540:     my ($Filename, $Contents) = @_;
  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: }
  563: 
  564: 
  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;
  588: 
  589: }
  590: #
  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: 
  619: 
  620:     my $tablefile = ConfigFileFromSelector($filename);
  621:     if(! (defined $tablefile)) {
  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/;
  631:     if(!CopyFile($tablefile, $backupfile)) {
  632: 	&logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
  633: 	return "error:$!";
  634:     }
  635:     &logthis('<font color="green"> Pushfile: backed up '
  636: 	    .$tablefile." to $backupfile</font>");
  637:     
  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: 
  648:     #  Install the new file:
  649: 
  650:     if(!InstallFile($tablefile, $contents)) {
  651: 	&logthis('<font color="red"> Pushfile: unable to install '
  652: 	 .$tablefile." $! </font>");
  653: 	return "error:$!";
  654:     } else {
  655: 	&logthis('<font color="green"> Installed new '.$tablefile
  656: 		 ."</font>");
  657: 
  658:     }
  659: 
  660: 
  661:     #  Indicate success:
  662:  
  663:     return "ok";
  664: 
  665: }
  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: 
  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);
  691:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  692:     if($process eq 'lonc') {
  693: 	$processpidfile = $processpidfile."lonc.pid";
  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);
  702:     } elsif ($process eq 'lond') {
  703: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  704: 	&UpdateHosts;			# Lond is us!!
  705:     } else {
  706: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  707: 		 ."</font>");
  708: 	return "error:Invalid process identifier $process";
  709:     }
  710:     return 'ok';
  711: }
  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).
  718: #
  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: 	}
  744:     } elsif ($command eq "replace") {
  745: 	#
  746: 	#   key and newline:
  747: 	#
  748: 	if (($key eq "") || ($newline eq "")) {
  749: 	    return 0;
  750: 	} else {
  751: 	    return 1;
  752: 	}
  753:     } elsif ($command eq "append") {
  754: 	if (($key ne "") && ($newline eq "")) {
  755: 	    return 1;
  756: 	} else {
  757: 	    return 0;
  758: 	}
  759:     } else {
  760: 	return 0;		# Invalid command.
  761:     }
  762:     return 0;			# Should not get here!!!
  763: }
  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 {
  778: 
  779:     my ($directive, $editor) = @_;
  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 {
  863:     
  864:     my ($filename, $editor) = @_;
  865: 
  866:     CopyFile ($filename, $filename.".old");
  867: 
  868:     my $contents  = $editor->Get(); # Get the contents of the file.
  869: 
  870:     InstallFile($filename, $contents);
  871: }
  872: #   
  873: #
  874: #   Called to edit a configuration table  file
  875: #   Parameters:
  876: #      request           - The entire command/request sent by lonc or lonManage
  877: #   Return:
  878: #      The reply to send to the client.
  879: #
  880: sub EditFile {
  881:     my $request = shift;
  882: 
  883:     #  Split the command into it's pieces:  edit:filetype:script
  884: 
  885:     my ($request, $filetype, $script) = split(/:/, $request,3);	# : in script
  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.
  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:     }
  907: 
  908:     #   Execute the edit operation.
  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);
  917: 
  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);
  930: 
  931:     return "ok\n";
  932: }
  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: #
  955: sub tie_domain_hash {
  956:     my ($domain,$namespace,$how,$loghead,$logtail) = @_;
  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)) {
  969: 	if (defined($loghead)) {	# Need to log the operation.
  970: 	    my $logFh = IO::File->new(">>$domain_dir/$namespace.hist");
  971: 	    if($logFh) {
  972: 		my $timestamp = time;
  973: 		print $logFh "$loghead:$timestamp:$logtail\n";
  974: 	    }
  975: 	    $logFh->close;
  976: 	}
  977: 	return \%hash;		# Return the tied hash.
  978:     } else {
  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: #
 1002: sub tie_user_hash {
 1003:     my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
 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)) {
 1014: 	# If this is a namespace for which a history is kept,
 1015: 	# make the history log entry:    
 1016: 	if (($namespace =~/^nohist\_/) && (defined($loghead))) {
 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: 	    }
 1024: 	    $hfh->close;
 1025: 	}
 1026: 	return \%hash;
 1027:     } else {
 1028: 	return undef;
 1029:     }
 1030:     
 1031: }
 1032: 
 1033: #--------------------- Request Handlers --------------------------------------------
 1034: #
 1035: #   By convention each request handler registers itself prior to the sub 
 1036: #   declaration:
 1037: #
 1038: 
 1039: #++
 1040: #
 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: 
 1065: #++
 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: 
 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: 
 1137: 
 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: 
 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.
 1223:     # and call get_auth_type to determine the authentication type.
 1224:    
 1225:     my ($udom,$uname)=split(/:/,$tail);
 1226:     my $result = &get_auth_type($udom, $uname);
 1227:     if($result eq "nouser") {
 1228: 	&Failure( $replyfd, "unknown_user\n", $userinput);
 1229:     } else {
 1230: 	#
 1231: 	# We only want to pass the second field from get_auth_type
 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: 	}
 1239: 	&Reply( $replyfd, "$type:\n", $userinput);
 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:     } 
 1281:     return 1;
 1282: }
 1283: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
 1284: 
 1285: #
 1286: #   du  - list the disk usuage of a directory recursively. 
 1287: #    
 1288: #   note: stolen code from the ls file handler
 1289: #   under construction by Rick Banghart 
 1290: #    .
 1291: # Parameters:
 1292: #    $cmd        - The command that dispatched us (du).
 1293: #    $ududir     - The directory path to list... I'm not sure what this
 1294: #                  is relative as things like ls:. return e.g.
 1295: #                  no_such_dir.
 1296: #    $client     - Socket open on the client.
 1297: # Returns:
 1298: #     1 - indicating that the daemon should not disconnect.
 1299: # Side Effects:
 1300: #   The reply is written to  $client.
 1301: #
 1302: 
 1303: sub du_handler {
 1304:     my ($cmd, $ududir, $client) = @_;
 1305:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
 1306: 	&Failure($client,"refused\n","$cmd:$ududir");
 1307: 	return 1;
 1308:     }
 1309:     my $duout = `du -ks $ududir 2>/dev/null`;
 1310:     $duout=~s/[^\d]//g; #preserve only the numbers
 1311:     &Reply($client,"$duout\n","$cmd:$ududir");
 1312:     return 1;
 1313: }
 1314: &register_handler("du", \&du_handler, 0, 1, 0);
 1315: 
 1316: 
 1317: #
 1318: #   ls  - list the contents of a directory.  For each file in the
 1319: #    selected directory the filename followed by the full output of
 1320: #    the stat function is returned.  The returned info for each
 1321: #    file are separated by ':'.  The stat fields are separated by &'s.
 1322: # Parameters:
 1323: #    $cmd        - The command that dispatched us (ls).
 1324: #    $ulsdir     - The directory path to list... I'm not sure what this
 1325: #                  is relative as things like ls:. return e.g.
 1326: #                  no_such_dir.
 1327: #    $client     - Socket open on the client.
 1328: # Returns:
 1329: #     1 - indicating that the daemon should not disconnect.
 1330: # Side Effects:
 1331: #   The reply is written to  $client.
 1332: #
 1333: sub ls_handler {
 1334:     my ($cmd, $ulsdir, $client) = @_;
 1335: 
 1336:     my $userinput = "$cmd:$ulsdir";
 1337: 
 1338:     my $obs;
 1339:     my $rights;
 1340:     my $ulsout='';
 1341:     my $ulsfn;
 1342:     if (-e $ulsdir) {
 1343: 	if(-d $ulsdir) {
 1344: 	    if (opendir(LSDIR,$ulsdir)) {
 1345: 		while ($ulsfn=readdir(LSDIR)) {
 1346: 		    undef $obs, $rights; 
 1347: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1348: 		    #We do some obsolete checking here
 1349: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
 1350: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
 1351: 			my @obsolete=<FILE>;
 1352: 			foreach my $obsolete (@obsolete) {
 1353: 			    if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; } 
 1354: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
 1355: 			}
 1356: 		    }
 1357: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
 1358: 		    if($obs eq '1') { $ulsout.="&1"; }
 1359: 		    else { $ulsout.="&0"; }
 1360: 		    if($rights eq '1') { $ulsout.="&1:"; }
 1361: 		    else { $ulsout.="&0:"; }
 1362: 		}
 1363: 		closedir(LSDIR);
 1364: 	    }
 1365: 	} else {
 1366: 	    my @ulsstats=stat($ulsdir);
 1367: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1368: 	}
 1369:     } else {
 1370: 	$ulsout='no_such_dir';
 1371:     }
 1372:     if ($ulsout eq '') { $ulsout='empty'; }
 1373:     print $client "$ulsout\n";
 1374:     
 1375:     return 1;
 1376: 
 1377: }
 1378: &register_handler("ls", \&ls_handler, 0, 1, 0);
 1379: 
 1380: 
 1381: 
 1382: 
 1383: #   Process a reinit request.  Reinit requests that either
 1384: #   lonc or lond be reinitialized so that an updated 
 1385: #   host.tab or domain.tab can be processed.
 1386: #
 1387: # Parameters:
 1388: #      $cmd    - the actual keyword that invoked us.
 1389: #      $tail   - the tail of the request that invoked us.
 1390: #      $client - File descriptor connected to the client
 1391: #  Returns:
 1392: #      1       - Ok to continue processing.
 1393: #      0       - Program should exit
 1394: #  Implicit output:
 1395: #     a reply is sent to the client.
 1396: #
 1397: sub reinit_process_handler {
 1398:     my ($cmd, $tail, $client) = @_;
 1399:    
 1400:     my $userinput = "$cmd:$tail";
 1401:    
 1402:     my $cert = &GetCertificate($userinput);
 1403:     if(&ValidManager($cert)) {
 1404: 	chomp($userinput);
 1405: 	my $reply = &ReinitProcess($userinput);
 1406: 	&Reply( $client,  "$reply\n", $userinput);
 1407:     } else {
 1408: 	&Failure( $client, "refused\n", $userinput);
 1409:     }
 1410:     return 1;
 1411: }
 1412: 
 1413: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
 1414: 
 1415: #  Process the editing script for a table edit operation.
 1416: #  the editing operation must be encrypted and requested by
 1417: #  a manager host.
 1418: #
 1419: # Parameters:
 1420: #      $cmd    - the actual keyword that invoked us.
 1421: #      $tail   - the tail of the request that invoked us.
 1422: #      $client - File descriptor connected to the client
 1423: #  Returns:
 1424: #      1       - Ok to continue processing.
 1425: #      0       - Program should exit
 1426: #  Implicit output:
 1427: #     a reply is sent to the client.
 1428: #
 1429: sub edit_table_handler {
 1430:     my ($command, $tail, $client) = @_;
 1431:    
 1432:     my $userinput = "$command:$tail";
 1433: 
 1434:     my $cert = &GetCertificate($userinput);
 1435:     if(&ValidManager($cert)) {
 1436: 	my($filetype, $script) = split(/:/, $tail);
 1437: 	if (($filetype eq "hosts") || 
 1438: 	    ($filetype eq "domain")) {
 1439: 	    if($script ne "") {
 1440: 		&Reply($client,              # BUGBUG - EditFile
 1441: 		      &EditFile($userinput), #   could fail.
 1442: 		      $userinput);
 1443: 	    } else {
 1444: 		&Failure($client,"refused\n",$userinput);
 1445: 	    }
 1446: 	} else {
 1447: 	    &Failure($client,"refused\n",$userinput);
 1448: 	}
 1449:     } else {
 1450: 	&Failure($client,"refused\n",$userinput);
 1451:     }
 1452:     return 1;
 1453: }
 1454: register_handler("edit", \&edit_table_handler, 1, 0, 1);
 1455: 
 1456: 
 1457: #
 1458: #   Authenticate a user against the LonCAPA authentication
 1459: #   database.  Note that there are several authentication
 1460: #   possibilities:
 1461: #   - unix     - The user can be authenticated against the unix
 1462: #                password file.
 1463: #   - internal - The user can be authenticated against a purely 
 1464: #                internal per user password file.
 1465: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
 1466: #                ticket granting authority.
 1467: #   - user     - The person tailoring LonCAPA can supply a user authentication
 1468: #                mechanism that is per system.
 1469: #
 1470: # Parameters:
 1471: #    $cmd      - The command that got us here.
 1472: #    $tail     - Tail of the command (remaining parameters).
 1473: #    $client   - File descriptor connected to client.
 1474: # Returns
 1475: #     0        - Requested to exit, caller should shut down.
 1476: #     1        - Continue processing.
 1477: # Implicit inputs:
 1478: #    The authentication systems describe above have their own forms of implicit
 1479: #    input into the authentication process that are described above.
 1480: #
 1481: sub authenticate_handler {
 1482:     my ($cmd, $tail, $client) = @_;
 1483: 
 1484:     
 1485:     #  Regenerate the full input line 
 1486:     
 1487:     my $userinput  = $cmd.":".$tail;
 1488:     
 1489:     #  udom    - User's domain.
 1490:     #  uname   - Username.
 1491:     #  upass   - User's password.
 1492:     
 1493:     my ($udom,$uname,$upass)=split(/:/,$tail);
 1494:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass");
 1495:     chomp($upass);
 1496:     $upass=&unescape($upass);
 1497: 
 1498:     my $pwdcorrect = &validate_user($udom, $uname, $upass);
 1499:     if($pwdcorrect) {
 1500: 	&Reply( $client, "authorized\n", $userinput);
 1501: 	#
 1502: 	#  Bad credentials: Failed to authorize
 1503: 	#
 1504:     } else {
 1505: 	&Failure( $client, "non_authorized\n", $userinput);
 1506:     }
 1507: 
 1508:     return 1;
 1509: }
 1510: 
 1511: register_handler("auth", \&authenticate_handler, 1, 1, 0);
 1512: 
 1513: #
 1514: #   Change a user's password.  Note that this function is complicated by
 1515: #   the fact that a user may be authenticated in more than one way:
 1516: #   At present, we are not able to change the password for all types of
 1517: #   authentication methods.  Only for:
 1518: #      unix    - unix password or shadow passoword style authentication.
 1519: #      local   - Locally written authentication mechanism.
 1520: #   For now, kerb4 and kerb5 password changes are not supported and result
 1521: #   in an error.
 1522: # FUTURE WORK:
 1523: #    Support kerberos passwd changes?
 1524: # Parameters:
 1525: #    $cmd      - The command that got us here.
 1526: #    $tail     - Tail of the command (remaining parameters).
 1527: #    $client   - File descriptor connected to client.
 1528: # Returns
 1529: #     0        - Requested to exit, caller should shut down.
 1530: #     1        - Continue processing.
 1531: # Implicit inputs:
 1532: #    The authentication systems describe above have their own forms of implicit
 1533: #    input into the authentication process that are described above.
 1534: sub change_password_handler {
 1535:     my ($cmd, $tail, $client) = @_;
 1536: 
 1537:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
 1538: 
 1539:     #
 1540:     #  udom  - user's domain.
 1541:     #  uname - Username.
 1542:     #  upass - Current password.
 1543:     #  npass - New password.
 1544:    
 1545:     my ($udom,$uname,$upass,$npass)=split(/:/,$tail);
 1546: 
 1547:     $upass=&unescape($upass);
 1548:     $npass=&unescape($npass);
 1549:     &Debug("Trying to change password for $uname");
 1550: 
 1551:     # First require that the user can be authenticated with their
 1552:     # old password:
 1553: 
 1554:     my $validated = &validate_user($udom, $uname, $upass);
 1555:     if($validated) {
 1556: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
 1557: 	
 1558: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 1559: 	if ($howpwd eq 'internal') {
 1560: 	    &Debug("internal auth");
 1561: 	    my $salt=time;
 1562: 	    $salt=substr($salt,6,2);
 1563: 	    my $ncpass=crypt($npass,$salt);
 1564: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
 1565: 		&logthis("Result of password change for "
 1566: 			 ."$uname: pwchange_success");
 1567: 		&Reply($client, "ok\n", $userinput);
 1568: 	    } else {
 1569: 		&logthis("Unable to open $uname passwd "               
 1570: 			 ."to change password");
 1571: 		&Failure( $client, "non_authorized\n",$userinput);
 1572: 	    }
 1573: 	} elsif ($howpwd eq 'unix') {
 1574: 	    # Unix means we have to access /etc/password
 1575: 	    &Debug("auth is unix");
 1576: 	    my $execdir=$perlvar{'lonDaemons'};
 1577: 	    &Debug("Opening lcpasswd pipeline");
 1578: 	    my $pf = IO::File->new("|$execdir/lcpasswd > "
 1579: 				   ."$perlvar{'lonDaemons'}"
 1580: 				   ."/logs/lcpasswd.log");
 1581: 	    print $pf "$uname\n$npass\n$npass\n";
 1582: 	    close $pf;
 1583: 	    my $err = $?;
 1584: 	    my $result = ($err>0 ? 'pwchange_failure' : 'ok');
 1585: 	    &logthis("Result of password change for $uname: ".
 1586: 		     &lcpasswdstrerror($?));
 1587: 	    &Reply($client, "$result\n", $userinput);
 1588: 	} else {
 1589: 	    # this just means that the current password mode is not
 1590: 	    # one we know how to change (e.g the kerberos auth modes or
 1591: 	    # locally written auth handler).
 1592: 	    #
 1593: 	    &Failure( $client, "auth_mode_error\n", $userinput);
 1594: 	}  
 1595: 	
 1596:     } else {
 1597: 	&Failure( $client, "non_authorized\n", $userinput);
 1598:     }
 1599: 
 1600:     return 1;
 1601: }
 1602: register_handler("passwd", \&change_password_handler, 1, 1, 0);
 1603: 
 1604: 
 1605: #
 1606: #   Create a new user.  User in this case means a lon-capa user.
 1607: #   The user must either already exist in some authentication realm
 1608: #   like kerberos or the /etc/passwd.  If not, a user completely local to
 1609: #   this loncapa system is created.
 1610: #
 1611: # Parameters:
 1612: #    $cmd      - The command that got us here.
 1613: #    $tail     - Tail of the command (remaining parameters).
 1614: #    $client   - File descriptor connected to client.
 1615: # Returns
 1616: #     0        - Requested to exit, caller should shut down.
 1617: #     1        - Continue processing.
 1618: # Implicit inputs:
 1619: #    The authentication systems describe above have their own forms of implicit
 1620: #    input into the authentication process that are described above.
 1621: sub add_user_handler {
 1622: 
 1623:     my ($cmd, $tail, $client) = @_;
 1624: 
 1625: 
 1626:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 1627:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
 1628: 
 1629:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
 1630: 
 1631: 
 1632:     if($udom eq $currentdomainid) { # Reject new users for other domains...
 1633: 	
 1634: 	my $oldumask=umask(0077);
 1635: 	chomp($npass);
 1636: 	$npass=&unescape($npass);
 1637: 	my $passfilename  = &password_path($udom, $uname);
 1638: 	&Debug("Password file created will be:".$passfilename);
 1639: 	if (-e $passfilename) {
 1640: 	    &Failure( $client, "already_exists\n", $userinput);
 1641: 	} else {
 1642: 	    my @fpparts=split(/\//,$passfilename);
 1643: 	    my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
 1644: 	    my $fperror='';
 1645: 	    for (my $i=3;$i<= ($#fpparts-1);$i++) {
 1646: 		$fpnow.='/'.$fpparts[$i]; 
 1647: 		unless (-e $fpnow) {
 1648: 		    &logthis("mkdir $fpnow");
 1649: 		    unless (mkdir($fpnow,0777)) {
 1650: 			$fperror="error: ".($!+0)." mkdir failed while attempting "
 1651: 			    ."makeuser";
 1652: 		    }
 1653: 		}
 1654: 	    }
 1655: 	    unless ($fperror) {
 1656: 		my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
 1657: 		&Reply($client, $result, $userinput);     #BUGBUG - could be fail
 1658: 	    } else {
 1659: 		&Failure($client, "$fperror\n", $userinput);
 1660: 	    }
 1661: 	}
 1662: 	umask($oldumask);
 1663:     }  else {
 1664: 	&Failure($client, "not_right_domain\n",
 1665: 		$userinput);	# Even if we are multihomed.
 1666:     
 1667:     }
 1668:     return 1;
 1669: 
 1670: }
 1671: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
 1672: 
 1673: #
 1674: #   Change the authentication method of a user.  Note that this may
 1675: #   also implicitly change the user's password if, for example, the user is
 1676: #   joining an existing authentication realm.  Known authentication realms at
 1677: #   this time are:
 1678: #    internal   - Purely internal password file (only loncapa knows this user)
 1679: #    local      - Institutionally written authentication module.
 1680: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
 1681: #    kerb4      - kerberos version 4
 1682: #    kerb5      - kerberos version 5
 1683: #
 1684: # Parameters:
 1685: #    $cmd      - The command that got us here.
 1686: #    $tail     - Tail of the command (remaining parameters).
 1687: #    $client   - File descriptor connected to client.
 1688: # Returns
 1689: #     0        - Requested to exit, caller should shut down.
 1690: #     1        - Continue processing.
 1691: # Implicit inputs:
 1692: #    The authentication systems describe above have their own forms of implicit
 1693: #    input into the authentication process that are described above.
 1694: #
 1695: sub change_authentication_handler {
 1696: 
 1697:     my ($cmd, $tail, $client) = @_;
 1698:    
 1699:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
 1700: 
 1701:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
 1702:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
 1703:     if ($udom ne $currentdomainid) {
 1704: 	&Failure( $client, "not_right_domain\n", $client);
 1705:     } else {
 1706: 	
 1707: 	chomp($npass);
 1708: 	
 1709: 	$npass=&unescape($npass);
 1710: 	my $passfilename = &password_path($udom, $uname);
 1711: 	if ($passfilename) {	# Not allowed to create a new user!!
 1712: 	    my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
 1713: 	    &Reply($client, $result, $userinput);
 1714: 	} else {	       
 1715: 	    &Failure($client, "non_authorized", $userinput); # Fail the user now.
 1716: 	}
 1717:     }
 1718:     return 1;
 1719: }
 1720: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
 1721: 
 1722: #
 1723: #   Determines if this is the home server for a user.  The home server
 1724: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
 1725: #   to do is determine if this file exists.
 1726: #
 1727: # Parameters:
 1728: #    $cmd      - The command that got us here.
 1729: #    $tail     - Tail of the command (remaining parameters).
 1730: #    $client   - File descriptor connected to client.
 1731: # Returns
 1732: #     0        - Requested to exit, caller should shut down.
 1733: #     1        - Continue processing.
 1734: # Implicit inputs:
 1735: #    The authentication systems describe above have their own forms of implicit
 1736: #    input into the authentication process that are described above.
 1737: #
 1738: sub is_home_handler {
 1739:     my ($cmd, $tail, $client) = @_;
 1740:    
 1741:     my $userinput  = "$cmd:$tail";
 1742:    
 1743:     my ($udom,$uname)=split(/:/,$tail);
 1744:     chomp($uname);
 1745:     my $passfile = &password_filename($udom, $uname);
 1746:     if($passfile) {
 1747: 	&Reply( $client, "found\n", $userinput);
 1748:     } else {
 1749: 	&Failure($client, "not_found\n", $userinput);
 1750:     }
 1751:     return 1;
 1752: }
 1753: &register_handler("home", \&is_home_handler, 0,1,0);
 1754: 
 1755: #
 1756: #   Process an update request for a resource?? I think what's going on here is
 1757: #   that a resource has been modified that we hold a subscription to.
 1758: #   If the resource is not local, then we must update, or at least invalidate our
 1759: #   cached copy of the resource. 
 1760: #   FUTURE WORK:
 1761: #      I need to look at this logic carefully.  My druthers would be to follow
 1762: #      typical caching logic, and simple invalidate the cache, drop any subscription
 1763: #      an let the next fetch start the ball rolling again... however that may
 1764: #      actually be more difficult than it looks given the complex web of
 1765: #      proxy servers.
 1766: # Parameters:
 1767: #    $cmd      - The command that got us here.
 1768: #    $tail     - Tail of the command (remaining parameters).
 1769: #    $client   - File descriptor connected to client.
 1770: # Returns
 1771: #     0        - Requested to exit, caller should shut down.
 1772: #     1        - Continue processing.
 1773: # Implicit inputs:
 1774: #    The authentication systems describe above have their own forms of implicit
 1775: #    input into the authentication process that are described above.
 1776: #
 1777: sub update_resource_handler {
 1778: 
 1779:     my ($cmd, $tail, $client) = @_;
 1780:    
 1781:     my $userinput = "$cmd:$tail";
 1782:    
 1783:     my $fname= $tail;		# This allows interactive testing
 1784: 
 1785: 
 1786:     my $ownership=ishome($fname);
 1787:     if ($ownership eq 'not_owner') {
 1788: 	if (-e $fname) {
 1789: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
 1790: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
 1791: 	    my $now=time;
 1792: 	    my $since=$now-$atime;
 1793: 	    if ($since>$perlvar{'lonExpire'}) {
 1794: 		my $reply=&reply("unsub:$fname","$clientname");
 1795: 		unlink("$fname");
 1796: 	    } else {
 1797: 		my $transname="$fname.in.transfer";
 1798: 		my $remoteurl=&reply("sub:$fname","$clientname");
 1799: 		my $response;
 1800: 		alarm(120);
 1801: 		{
 1802: 		    my $ua=new LWP::UserAgent;
 1803: 		    my $request=new HTTP::Request('GET',"$remoteurl");
 1804: 		    $response=$ua->request($request,$transname);
 1805: 		}
 1806: 		alarm(0);
 1807: 		if ($response->is_error()) {
 1808: 		    unlink($transname);
 1809: 		    my $message=$response->status_line;
 1810: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
 1811: 		} else {
 1812: 		    if ($remoteurl!~/\.meta$/) {
 1813: 			alarm(120);
 1814: 			{
 1815: 			    my $ua=new LWP::UserAgent;
 1816: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1817: 			    my $mresponse=$ua->request($mrequest,$fname.'.meta');
 1818: 			    if ($mresponse->is_error()) {
 1819: 				unlink($fname.'.meta');
 1820: 			    }
 1821: 			}
 1822: 			alarm(0);
 1823: 		    }
 1824: 		    rename($transname,$fname);
 1825: 		}
 1826: 	    }
 1827: 	    &Reply( $client, "ok\n", $userinput);
 1828: 	} else {
 1829: 	    &Failure($client, "not_found\n", $userinput);
 1830: 	}
 1831:     } else {
 1832: 	&Failure($client, "rejected\n", $userinput);
 1833:     }
 1834:     return 1;
 1835: }
 1836: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
 1837: 
 1838: #
 1839: #   Fetch a user file from a remote server to the user's home directory
 1840: #   userfiles subdir.
 1841: # Parameters:
 1842: #    $cmd      - The command that got us here.
 1843: #    $tail     - Tail of the command (remaining parameters).
 1844: #    $client   - File descriptor connected to client.
 1845: # Returns
 1846: #     0        - Requested to exit, caller should shut down.
 1847: #     1        - Continue processing.
 1848: #
 1849: sub fetch_user_file_handler {
 1850: 
 1851:     my ($cmd, $tail, $client) = @_;
 1852: 
 1853:     my $userinput = "$cmd:$tail";
 1854:     my $fname           = $tail;
 1855:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 1856:     my $udir=&propath($udom,$uname).'/userfiles';
 1857:     unless (-e $udir) {
 1858: 	mkdir($udir,0770); 
 1859:     }
 1860:     Debug("fetch user file for $fname");
 1861:     if (-e $udir) {
 1862: 	$ufile=~s/^[\.\~]+//;
 1863: 
 1864: 	# IF necessary, create the path right down to the file.
 1865: 	# Note that any regular files in the way of this path are
 1866: 	# wiped out to deal with some earlier folly of mine.
 1867: 
 1868: 	my $path = $udir;
 1869: 	if ($ufile =~m|(.+)/([^/]+)$|) {
 1870: 	    my @parts=split('/',$1);
 1871: 	    foreach my $part (@parts) {
 1872: 		$path .= '/'.$part;
 1873: 		if( -f $path) {
 1874: 		    unlink($path);
 1875: 		}
 1876: 		if ((-e $path)!=1) {
 1877: 		    mkdir($path,0770);
 1878: 		}
 1879: 	    }
 1880: 	}
 1881: 
 1882: 
 1883: 	my $destname=$udir.'/'.$ufile;
 1884: 	my $transname=$udir.'/'.$ufile.'.in.transit';
 1885: 	my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
 1886: 	my $response;
 1887: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
 1888: 	alarm(120);
 1889: 	{
 1890: 	    my $ua=new LWP::UserAgent;
 1891: 	    my $request=new HTTP::Request('GET',"$remoteurl");
 1892: 	    $response=$ua->request($request,$transname);
 1893: 	}
 1894: 	alarm(0);
 1895: 	if ($response->is_error()) {
 1896: 	    unlink($transname);
 1897: 	    my $message=$response->status_line;
 1898: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
 1899: 	    &Failure($client, "failed\n", $userinput);
 1900: 	} else {
 1901: 	    Debug("Renaming $transname to $destname");
 1902: 	    if (!rename($transname,$destname)) {
 1903: 		&logthis("Unable to move $transname to $destname");
 1904: 		unlink($transname);
 1905: 		&Failure($client, "failed\n", $userinput);
 1906: 	    } else {
 1907: 		&Reply($client, "ok\n", $userinput);
 1908: 	    }
 1909: 	}   
 1910:     } else {
 1911: 	&Failure($client, "not_home\n", $userinput);
 1912:     }
 1913:     return 1;
 1914: }
 1915: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
 1916: 
 1917: #
 1918: #   Remove a file from a user's home directory userfiles subdirectory.
 1919: # Parameters:
 1920: #    cmd   - the Lond request keyword that got us here.
 1921: #    tail  - the part of the command past the keyword.
 1922: #    client- File descriptor connected with the client.
 1923: #
 1924: # Returns:
 1925: #    1    - Continue processing.
 1926: 
 1927: sub remove_user_file_handler {
 1928:     my ($cmd, $tail, $client) = @_;
 1929: 
 1930:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 1931: 
 1932:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
 1933:     if ($ufile =~m|/\.\./|) {
 1934: 	# any files paths with /../ in them refuse 
 1935: 	# to deal with
 1936: 	&Failure($client, "refused\n", "$cmd:$tail");
 1937:     } else {
 1938: 	my $udir = &propath($udom,$uname);
 1939: 	if (-e $udir) {
 1940: 	    my $file=$udir.'/userfiles/'.$ufile;
 1941: 	    if (-e $file) {
 1942: 	        if (-f $file){
 1943: 		    unlink($file);
 1944: 		} elsif(-d $file) {
 1945: 		    rmdir($file);
 1946: 		}
 1947: 		if (-e $file) {
 1948: 		    &Failure($client, "failed\n", "$cmd:$tail");
 1949: 		} else {
 1950: 		    &Reply($client, "ok\n", "$cmd:$tail");
 1951: 		}
 1952: 	    } else {
 1953: 		&Failure($client, "not_found\n", "$cmd:$tail");
 1954: 	    }
 1955: 	} else {
 1956: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 1957: 	}
 1958:     }
 1959:     return 1;
 1960: }
 1961: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
 1962: 
 1963: #
 1964: #   make a directory in a user's home directory userfiles subdirectory.
 1965: # Parameters:
 1966: #    cmd   - the Lond request keyword that got us here.
 1967: #    tail  - the part of the command past the keyword.
 1968: #    client- File descriptor connected with the client.
 1969: #
 1970: # Returns:
 1971: #    1    - Continue processing.
 1972: 
 1973: sub mkdir_user_file_handler {
 1974:     my ($cmd, $tail, $client) = @_;
 1975: 
 1976:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
 1977:     $dir=&unescape($dir);
 1978:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
 1979:     if ($ufile =~m|/\.\./|) {
 1980: 	# any files paths with /../ in them refuse 
 1981: 	# to deal with
 1982: 	&Failure($client, "refused\n", "$cmd:$tail");
 1983:     } else {
 1984: 	my $udir = &propath($udom,$uname);
 1985: 	if (-e $udir) {
 1986: 	    my $newdir=$udir.'/userfiles/'.$ufile;
 1987: 	    if (!-e $newdir) {
 1988: 		mkdir($newdir);
 1989: 		if (!-e $newdir) {
 1990: 		    &Failure($client, "failed\n", "$cmd:$tail");
 1991: 		} else {
 1992: 		    &Reply($client, "ok\n", "$cmd:$tail");
 1993: 		}
 1994: 	    } else {
 1995: 		&Failure($client, "not_found\n", "$cmd:$tail");
 1996: 	    }
 1997: 	} else {
 1998: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 1999: 	}
 2000:     }
 2001:     return 1;
 2002: }
 2003: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
 2004: 
 2005: #
 2006: #   rename a file in a user's home directory userfiles subdirectory.
 2007: # Parameters:
 2008: #    cmd   - the Lond request keyword that got us here.
 2009: #    tail  - the part of the command past the keyword.
 2010: #    client- File descriptor connected with the client.
 2011: #
 2012: # Returns:
 2013: #    1    - Continue processing.
 2014: 
 2015: sub rename_user_file_handler {
 2016:     my ($cmd, $tail, $client) = @_;
 2017: 
 2018:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
 2019:     $old=&unescape($old);
 2020:     $new=&unescape($new);
 2021:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
 2022: 	# any files paths with /../ in them refuse to deal with
 2023: 	&Failure($client, "refused\n", "$cmd:$tail");
 2024:     } else {
 2025: 	my $udir = &propath($udom,$uname);
 2026: 	if (-e $udir) {
 2027: 	    my $oldfile=$udir.'/userfiles/'.$old;
 2028: 	    my $newfile=$udir.'/userfiles/'.$new;
 2029: 	    if (-e $newfile) {
 2030: 		&Failure($client, "exists\n", "$cmd:$tail");
 2031: 	    } elsif (! -e $oldfile) {
 2032: 		&Failure($client, "not_found\n", "$cmd:$tail");
 2033: 	    } else {
 2034: 		if (!rename($oldfile,$newfile)) {
 2035: 		    &Failure($client, "failed\n", "$cmd:$tail");
 2036: 		} else {
 2037: 		    &Reply($client, "ok\n", "$cmd:$tail");
 2038: 		}
 2039: 	    }
 2040: 	} else {
 2041: 	    &Failure($client, "not_home\n", "$cmd:$tail");
 2042: 	}
 2043:     }
 2044:     return 1;
 2045: }
 2046: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
 2047: 
 2048: 
 2049: #
 2050: #  Authenticate access to a user file by checking the user's 
 2051: #  session token(?)
 2052: #
 2053: # Parameters:
 2054: #   cmd      - The request keyword that dispatched to tus.
 2055: #   tail     - The tail of the request (colon separated parameters).
 2056: #   client   - Filehandle open on the client.
 2057: # Return:
 2058: #    1.
 2059: 
 2060: sub token_auth_user_file_handler {
 2061:     my ($cmd, $tail, $client) = @_;
 2062: 
 2063:     my ($fname, $session) = split(/:/, $tail);
 2064:     
 2065:     chomp($session);
 2066:     my $reply='non_auth';
 2067:     if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
 2068: 	     $session.'.id')) {
 2069: 	while (my $line=<ENVIN>) {
 2070: 	    if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply='ok'; }
 2071: 	}
 2072: 	close(ENVIN);
 2073: 	&Reply($client, $reply);
 2074:     } else {
 2075: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
 2076:     }
 2077:     return 1;
 2078: 
 2079: }
 2080: 
 2081: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
 2082: 
 2083: 
 2084: #
 2085: #   Unsubscribe from a resource.
 2086: #
 2087: # Parameters:
 2088: #    $cmd      - The command that got us here.
 2089: #    $tail     - Tail of the command (remaining parameters).
 2090: #    $client   - File descriptor connected to client.
 2091: # Returns
 2092: #     0        - Requested to exit, caller should shut down.
 2093: #     1        - Continue processing.
 2094: #
 2095: sub unsubscribe_handler {
 2096:     my ($cmd, $tail, $client) = @_;
 2097: 
 2098:     my $userinput= "$cmd:$tail";
 2099:     
 2100:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
 2101: 
 2102:     &Debug("Unsubscribing $fname");
 2103:     if (-e $fname) {
 2104: 	&Debug("Exists");
 2105: 	&Reply($client, &unsub($fname,$clientip), $userinput);
 2106:     } else {
 2107: 	&Failure($client, "not_found\n", $userinput);
 2108:     }
 2109:     return 1;
 2110: }
 2111: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
 2112: #   Subscribe to a resource
 2113: #
 2114: # Parameters:
 2115: #    $cmd      - The command that got us here.
 2116: #    $tail     - Tail of the command (remaining parameters).
 2117: #    $client   - File descriptor connected to client.
 2118: # Returns
 2119: #     0        - Requested to exit, caller should shut down.
 2120: #     1        - Continue processing.
 2121: #
 2122: sub subscribe_handler {
 2123:     my ($cmd, $tail, $client)= @_;
 2124: 
 2125:     my $userinput  = "$cmd:$tail";
 2126: 
 2127:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
 2128: 
 2129:     return 1;
 2130: }
 2131: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
 2132: 
 2133: #
 2134: #   Determine the version of a resource (?) Or is it return
 2135: #   the top version of the resource?  Not yet clear from the
 2136: #   code in currentversion.
 2137: #
 2138: # Parameters:
 2139: #    $cmd      - The command that got us here.
 2140: #    $tail     - Tail of the command (remaining parameters).
 2141: #    $client   - File descriptor connected to client.
 2142: # Returns
 2143: #     0        - Requested to exit, caller should shut down.
 2144: #     1        - Continue processing.
 2145: #
 2146: sub current_version_handler {
 2147:     my ($cmd, $tail, $client) = @_;
 2148: 
 2149:     my $userinput= "$cmd:$tail";
 2150:    
 2151:     my $fname   = $tail;
 2152:     &Reply( $client, &currentversion($fname)."\n", $userinput);
 2153:     return 1;
 2154: 
 2155: }
 2156: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
 2157: 
 2158: #  Make an entry in a user's activity log.
 2159: #
 2160: # Parameters:
 2161: #    $cmd      - The command that got us here.
 2162: #    $tail     - Tail of the command (remaining parameters).
 2163: #    $client   - File descriptor connected to client.
 2164: # Returns
 2165: #     0        - Requested to exit, caller should shut down.
 2166: #     1        - Continue processing.
 2167: #
 2168: sub activity_log_handler {
 2169:     my ($cmd, $tail, $client) = @_;
 2170: 
 2171: 
 2172:     my $userinput= "$cmd:$tail";
 2173: 
 2174:     my ($udom,$uname,$what)=split(/:/,$tail);
 2175:     chomp($what);
 2176:     my $proname=&propath($udom,$uname);
 2177:     my $now=time;
 2178:     my $hfh;
 2179:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 2180: 	print $hfh "$now:$clientname:$what\n";
 2181: 	&Reply( $client, "ok\n", $userinput); 
 2182:     } else {
 2183: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
 2184: 		 ."while attempting log\n", 
 2185: 		 $userinput);
 2186:     }
 2187: 
 2188:     return 1;
 2189: }
 2190: register_handler("log", \&activity_log_handler, 0, 1, 0);
 2191: 
 2192: #
 2193: #   Put a namespace entry in a user profile hash.
 2194: #   My druthers would be for this to be an encrypted interaction too.
 2195: #   anything that might be an inadvertent covert channel about either
 2196: #   user authentication or user personal information....
 2197: #
 2198: # Parameters:
 2199: #    $cmd      - The command that got us here.
 2200: #    $tail     - Tail of the command (remaining parameters).
 2201: #    $client   - File descriptor connected to client.
 2202: # Returns
 2203: #     0        - Requested to exit, caller should shut down.
 2204: #     1        - Continue processing.
 2205: #
 2206: sub put_user_profile_entry {
 2207:     my ($cmd, $tail, $client)  = @_;
 2208: 
 2209:     my $userinput = "$cmd:$tail";
 2210:     
 2211:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
 2212:     if ($namespace ne 'roles') {
 2213: 	chomp($what);
 2214: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2215: 				  &GDBM_WRCREAT(),"P",$what);
 2216: 	if($hashref) {
 2217: 	    my @pairs=split(/\&/,$what);
 2218: 	    foreach my $pair (@pairs) {
 2219: 		my ($key,$value)=split(/=/,$pair);
 2220: 		$hashref->{$key}=$value;
 2221: 	    }
 2222: 	    if (untie(%$hashref)) {
 2223: 		&Reply( $client, "ok\n", $userinput);
 2224: 	    } else {
 2225: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2226: 			"while attempting put\n", 
 2227: 			$userinput);
 2228: 	    }
 2229: 	} else {
 2230: 	    &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
 2231: 		     "while attempting put\n", $userinput);
 2232: 	}
 2233:     } else {
 2234:         &Failure( $client, "refused\n", $userinput);
 2235:     }
 2236:     
 2237:     return 1;
 2238: }
 2239: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
 2240: 
 2241: # 
 2242: #   Increment a profile entry in the user history file.
 2243: #   The history contains keyword value pairs.  In this case,
 2244: #   The value itself is a pair of numbers.  The first, the current value
 2245: #   the second an increment that this function applies to the current
 2246: #   value.
 2247: #
 2248: # Parameters:
 2249: #    $cmd      - The command that got us here.
 2250: #    $tail     - Tail of the command (remaining parameters).
 2251: #    $client   - File descriptor connected to client.
 2252: # Returns
 2253: #     0        - Requested to exit, caller should shut down.
 2254: #     1        - Continue processing.
 2255: #
 2256: sub increment_user_value_handler {
 2257:     my ($cmd, $tail, $client) = @_;
 2258:     
 2259:     my $userinput   = "$cmd:$tail";
 2260:     
 2261:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
 2262:     if ($namespace ne 'roles') {
 2263:         chomp($what);
 2264: 	my $hashref = &tie_user_hash($udom, $uname,
 2265: 				     $namespace, &GDBM_WRCREAT(),
 2266: 				     "P",$what);
 2267: 	if ($hashref) {
 2268: 	    my @pairs=split(/\&/,$what);
 2269: 	    foreach my $pair (@pairs) {
 2270: 		my ($key,$value)=split(/=/,$pair);
 2271: 		# We could check that we have a number...
 2272: 		if (! defined($value) || $value eq '') {
 2273: 		    $value = 1;
 2274: 		}
 2275: 		$hashref->{$key}+=$value;
 2276: 	    }
 2277: 	    if (untie(%$hashref)) {
 2278: 		&Reply( $client, "ok\n", $userinput);
 2279: 	    } else {
 2280: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
 2281: 			 "while attempting inc\n", $userinput);
 2282: 	    }
 2283: 	} else {
 2284: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2285: 		     "while attempting inc\n", $userinput);
 2286: 	}
 2287:     } else {
 2288: 	&Failure($client, "refused\n", $userinput);
 2289:     }
 2290:     
 2291:     return 1;
 2292: }
 2293: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
 2294: 
 2295: 
 2296: #
 2297: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
 2298: #   Each 'role' a user has implies a set of permissions.  Adding a new role
 2299: #   for a person grants the permissions packaged with that role
 2300: #   to that user when the role is selected.
 2301: #
 2302: # Parameters:
 2303: #    $cmd       - The command string (rolesput).
 2304: #    $tail      - The remainder of the request line.  For rolesput this
 2305: #                 consists of a colon separated list that contains:
 2306: #                 The domain and user that is granting the role (logged).
 2307: #                 The domain and user that is getting the role.
 2308: #                 The roles being granted as a set of & separated pairs.
 2309: #                 each pair a key value pair.
 2310: #    $client    - File descriptor connected to the client.
 2311: # Returns:
 2312: #     0         - If the daemon should exit
 2313: #     1         - To continue processing.
 2314: #
 2315: #
 2316: sub roles_put_handler {
 2317:     my ($cmd, $tail, $client) = @_;
 2318: 
 2319:     my $userinput  = "$cmd:$tail";
 2320: 
 2321:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
 2322:     
 2323: 
 2324:     my $namespace='roles';
 2325:     chomp($what);
 2326:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2327: 				 &GDBM_WRCREAT(), "P",
 2328: 				 "$exedom:$exeuser:$what");
 2329:     #
 2330:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
 2331:     #  handle is open for the minimal amount of time.  Since the flush
 2332:     #  is done on close this improves the chances the log will be an un-
 2333:     #  corrupted ordered thing.
 2334:     if ($hashref) {
 2335: 	my @pairs=split(/\&/,$what);
 2336: 	foreach my $pair (@pairs) {
 2337: 	    my ($key,$value)=split(/=/,$pair);
 2338: 	    &manage_permissions($key, $udom, $uname,
 2339: 			       &get_auth_type( $udom, $uname));
 2340: 	    $hashref->{$key}=$value;
 2341: 	}
 2342: 	if (untie($hashref)) {
 2343: 	    &Reply($client, "ok\n", $userinput);
 2344: 	} else {
 2345: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2346: 		     "while attempting rolesput\n", $userinput);
 2347: 	}
 2348:     } else {
 2349: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2350: 		 "while attempting rolesput\n", $userinput);
 2351:     }
 2352:     return 1;
 2353: }
 2354: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
 2355: 
 2356: #
 2357: #   Deletes (removes) a role for a user.   This is equivalent to removing
 2358: #  a permissions package associated with the role from the user's profile.
 2359: #
 2360: # Parameters:
 2361: #     $cmd                 - The command (rolesdel)
 2362: #     $tail                - The remainder of the request line. This consists
 2363: #                             of:
 2364: #                             The domain and user requesting the change (logged)
 2365: #                             The domain and user being changed.
 2366: #                             The roles being revoked.  These are shipped to us
 2367: #                             as a bunch of & separated role name keywords.
 2368: #     $client              - The file handle open on the client.
 2369: # Returns:
 2370: #     1                    - Continue processing
 2371: #     0                    - Exit.
 2372: #
 2373: sub roles_delete_handler {
 2374:     my ($cmd, $tail, $client)  = @_;
 2375: 
 2376:     my $userinput    = "$cmd:$tail";
 2377:    
 2378:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
 2379:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
 2380: 	   "what = ".$what);
 2381:     my $namespace='roles';
 2382:     chomp($what);
 2383:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2384: 				 &GDBM_WRCREAT(), "D",
 2385: 				 "$exedom:$exeuser:$what");
 2386:     
 2387:     if ($hashref) {
 2388: 	my @rolekeys=split(/\&/,$what);
 2389: 	
 2390: 	foreach my $key (@rolekeys) {
 2391: 	    delete $hashref->{$key};
 2392: 	}
 2393: 	if (untie(%$hashref)) {
 2394: 	    &Reply($client, "ok\n", $userinput);
 2395: 	} else {
 2396: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2397: 		     "while attempting rolesdel\n", $userinput);
 2398: 	}
 2399:     } else {
 2400:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2401: 		 "while attempting rolesdel\n", $userinput);
 2402:     }
 2403:     
 2404:     return 1;
 2405: }
 2406: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
 2407: 
 2408: # Unencrypted get from a user's profile database.  See 
 2409: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
 2410: # This function retrieves a keyed item from a specific named database in the
 2411: # user's directory.
 2412: #
 2413: # Parameters:
 2414: #   $cmd             - Command request keyword (get).
 2415: #   $tail            - Tail of the command.  This is a colon separated list
 2416: #                      consisting of the domain and username that uniquely
 2417: #                      identifies the profile,
 2418: #                      The 'namespace' which selects the gdbm file to 
 2419: #                      do the lookup in, 
 2420: #                      & separated list of keys to lookup.  Note that
 2421: #                      the values are returned as an & separated list too.
 2422: #   $client          - File descriptor open on the client.
 2423: # Returns:
 2424: #   1       - Continue processing.
 2425: #   0       - Exit.
 2426: #
 2427: sub get_profile_entry {
 2428:     my ($cmd, $tail, $client) = @_;
 2429: 
 2430:     my $userinput= "$cmd:$tail";
 2431:    
 2432:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 2433:     chomp($what);
 2434:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2435: 				 &GDBM_READER());
 2436:     if ($hashref) {
 2437:         my @queries=split(/\&/,$what);
 2438:         my $qresult='';
 2439: 	
 2440: 	for (my $i=0;$i<=$#queries;$i++) {
 2441: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
 2442: 	}
 2443: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
 2444: 	if (untie(%$hashref)) {
 2445: 	    &Reply($client, "$qresult\n", $userinput);
 2446: 	} else {
 2447: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2448: 		    "while attempting get\n", $userinput);
 2449: 	}
 2450:     } else {
 2451: 	if ($!+0 == 2) {               # +0 coerces errno -> number 2 is ENOENT
 2452: 	    &Failure($client, "error:No such file or ".
 2453: 		    "GDBM reported bad block error\n", $userinput);
 2454: 	} else {                        # Some other undifferentiated err.
 2455: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2456: 		    "while attempting get\n", $userinput);
 2457: 	}
 2458:     }
 2459:     return 1;
 2460: }
 2461: &register_handler("get", \&get_profile_entry, 0,1,0);
 2462: 
 2463: #
 2464: #  Process the encrypted get request.  Note that the request is sent
 2465: #  in clear, but the reply is encrypted.  This is a small covert channel:
 2466: #  information about the sensitive keys is given to the snooper.  Just not
 2467: #  information about the values of the sensitive key.  Hmm if I wanted to
 2468: #  know these I'd snoop for the egets. Get the profile item names from them
 2469: #  and then issue a get for them since there's no enforcement of the
 2470: #  requirement of an encrypted get for particular profile items.  If I
 2471: #  were re-doing this, I'd force the request to be encrypted as well as the
 2472: #  reply.  I'd also just enforce encrypted transactions for all gets since
 2473: #  that would prevent any covert channel snooping.
 2474: #
 2475: #  Parameters:
 2476: #     $cmd               - Command keyword of request (eget).
 2477: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
 2478: #     $client            - File open on the client.
 2479: #  Returns:
 2480: #     1      - Continue processing
 2481: #     0      - server should exit.
 2482: sub get_profile_entry_encrypted {
 2483:     my ($cmd, $tail, $client) = @_;
 2484: 
 2485:     my $userinput = "$cmd:$tail";
 2486:    
 2487:     my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
 2488:     chomp($what);
 2489:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2490: 				 &GDBM_READER());
 2491:     if ($hashref) {
 2492:         my @queries=split(/\&/,$what);
 2493:         my $qresult='';
 2494: 	for (my $i=0;$i<=$#queries;$i++) {
 2495: 	    $qresult.="$hashref->{$queries[$i]}&";
 2496: 	}
 2497: 	if (untie(%$hashref)) {
 2498: 	    $qresult=~s/\&$//;
 2499: 	    if ($cipher) {
 2500: 		my $cmdlength=length($qresult);
 2501: 		$qresult.="         ";
 2502: 		my $encqresult='';
 2503: 		for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 2504: 		    $encqresult.= unpack("H16", 
 2505: 					 $cipher->encrypt(substr($qresult,
 2506: 								 $encidx,
 2507: 								 8)));
 2508: 		}
 2509: 		&Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
 2510: 	    } else {
 2511: 		&Failure( $client, "error:no_key\n", $userinput);
 2512: 	    }
 2513: 	} else {
 2514: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2515: 		    "while attempting eget\n", $userinput);
 2516: 	}
 2517:     } else {
 2518: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2519: 		"while attempting eget\n", $userinput);
 2520:     }
 2521:     
 2522:     return 1;
 2523: }
 2524: &register_handler("eget", \&GetProfileEntryEncrypted, 0, 1, 0);
 2525: #
 2526: #   Deletes a key in a user profile database.
 2527: #   
 2528: #   Parameters:
 2529: #       $cmd                  - Command keyword (del).
 2530: #       $tail                 - Command tail.  IN this case a colon
 2531: #                               separated list containing:
 2532: #                               The domain and user that identifies uniquely
 2533: #                               the identity of the user.
 2534: #                               The profile namespace (name of the profile
 2535: #                               database file).
 2536: #                               & separated list of keywords to delete.
 2537: #       $client              - File open on client socket.
 2538: # Returns:
 2539: #     1   - Continue processing
 2540: #     0   - Exit server.
 2541: #
 2542: #
 2543: 
 2544: sub delete_profile_entry {
 2545:     my ($cmd, $tail, $client) = @_;
 2546: 
 2547:     my $userinput = "cmd:$tail";
 2548: 
 2549:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
 2550:     chomp($what);
 2551:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2552: 				 &GDBM_WRCREAT(),
 2553: 				 "D",$what);
 2554:     if ($hashref) {
 2555:         my @keys=split(/\&/,$what);
 2556: 	foreach my $key (@keys) {
 2557: 	    delete($hashref->{$key});
 2558: 	}
 2559: 	if (untie(%$hashref)) {
 2560: 	    &Reply($client, "ok\n", $userinput);
 2561: 	} else {
 2562: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2563: 		    "while attempting del\n", $userinput);
 2564: 	}
 2565:     } else {
 2566: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2567: 		 "while attempting del\n", $userinput);
 2568:     }
 2569:     return 1;
 2570: }
 2571: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
 2572: #
 2573: #  List the set of keys that are defined in a profile database file.
 2574: #  A successful reply from this will contain an & separated list of
 2575: #  the keys. 
 2576: # Parameters:
 2577: #     $cmd              - Command request (keys).
 2578: #     $tail             - Remainder of the request, a colon separated
 2579: #                         list containing domain/user that identifies the
 2580: #                         user being queried, and the database namespace
 2581: #                         (database filename essentially).
 2582: #     $client           - File open on the client.
 2583: #  Returns:
 2584: #    1    - Continue processing.
 2585: #    0    - Exit the server.
 2586: #
 2587: sub get_profile_keys {
 2588:     my ($cmd, $tail, $client) = @_;
 2589: 
 2590:     my $userinput = "$cmd:$tail";
 2591: 
 2592:     my ($udom,$uname,$namespace)=split(/:/,$tail);
 2593:     my $qresult='';
 2594:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2595: 				  &GDBM_READER());
 2596:     if ($hashref) {
 2597: 	foreach my $key (keys %$hashref) {
 2598: 	    $qresult.="$key&";
 2599: 	}
 2600: 	if (untie(%$hashref)) {
 2601: 	    $qresult=~s/\&$//;
 2602: 	    &Reply($client, "$qresult\n", $userinput);
 2603: 	} else {
 2604: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2605: 		    "while attempting keys\n", $userinput);
 2606: 	}
 2607:     } else {
 2608: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2609: 		 "while attempting keys\n", $userinput);
 2610:     }
 2611:    
 2612:     return 1;
 2613: }
 2614: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
 2615: 
 2616: #
 2617: #   Dump the contents of a user profile database.
 2618: #   Note that this constitutes a very large covert channel too since
 2619: #   the dump will return sensitive information that is not encrypted.
 2620: #   The naive security assumption is that the session negotiation ensures
 2621: #   our client is trusted and I don't believe that's assured at present.
 2622: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
 2623: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
 2624: # 
 2625: #  Parameters:
 2626: #     $cmd           - The command request keyword (currentdump).
 2627: #     $tail          - Remainder of the request, consisting of a colon
 2628: #                      separated list that has the domain/username and
 2629: #                      the namespace to dump (database file).
 2630: #     $client        - file open on the remote client.
 2631: # Returns:
 2632: #     1    - Continue processing.
 2633: #     0    - Exit the server.
 2634: #
 2635: sub dump_profile_database {
 2636:     my ($cmd, $tail, $client) = @_;
 2637: 
 2638:     my $userinput = "$cmd:$tail";
 2639:    
 2640:     my ($udom,$uname,$namespace) = split(/:/,$tail);
 2641:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2642: 				 &GDBM_READER());
 2643:     if ($hashref) {
 2644: 	# Structure of %data:
 2645: 	# $data{$symb}->{$parameter}=$value;
 2646: 	# $data{$symb}->{'v.'.$parameter}=$version;
 2647: 	# since $parameter will be unescaped, we do not
 2648:  	# have to worry about silly parameter names...
 2649: 	
 2650:         my $qresult='';
 2651: 	my %data = ();                     # A hash of anonymous hashes..
 2652: 	while (my ($key,$value) = each(%$hashref)) {
 2653: 	    my ($v,$symb,$param) = split(/:/,$key);
 2654: 	    next if ($v eq 'version' || $symb eq 'keys');
 2655: 	    next if (exists($data{$symb}) && 
 2656: 		     exists($data{$symb}->{$param}) &&
 2657: 		     $data{$symb}->{'v.'.$param} > $v);
 2658: 	    $data{$symb}->{$param}=$value;
 2659: 	    $data{$symb}->{'v.'.$param}=$v;
 2660: 	}
 2661: 	if (untie(%$hashref)) {
 2662: 	    while (my ($symb,$param_hash) = each(%data)) {
 2663: 		while(my ($param,$value) = each (%$param_hash)){
 2664: 		    next if ($param =~ /^v\./);       # Ignore versions...
 2665: 		    #
 2666: 		    #   Just dump the symb=value pairs separated by &
 2667: 		    #
 2668: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
 2669: 		}
 2670: 	    }
 2671: 	    chop($qresult);
 2672: 	    &Reply($client , "$qresult\n", $userinput);
 2673: 	} else {
 2674: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2675: 		     "while attempting currentdump\n", $userinput);
 2676: 	}
 2677:     } else {
 2678: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2679: 		"while attempting currentdump\n", $userinput);
 2680:     }
 2681: 
 2682:     return 1;
 2683: }
 2684: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
 2685: 
 2686: #
 2687: #   Dump a profile database with an optional regular expression
 2688: #   to match against the keys.  In this dump, no effort is made
 2689: #   to separate symb from version information. Presumably the
 2690: #   databases that are dumped by this command are of a different
 2691: #   structure.  Need to look at this and improve the documentation of
 2692: #   both this and the currentdump handler.
 2693: # Parameters:
 2694: #    $cmd                     - The command keyword.
 2695: #    $tail                    - All of the characters after the $cmd:
 2696: #                               These are expected to be a colon
 2697: #                               separated list containing:
 2698: #                               domain/user - identifying the user.
 2699: #                               namespace   - identifying the database.
 2700: #                               regexp      - optional regular expression
 2701: #                                             that is matched against
 2702: #                                             database keywords to do
 2703: #                                             selective dumps.
 2704: #   $client                   - Channel open on the client.
 2705: # Returns:
 2706: #    1    - Continue processing.
 2707: # Side effects:
 2708: #    response is written to $client.
 2709: #
 2710: sub dump_with_regexp {
 2711:     my ($cmd, $tail, $client) = @_;
 2712: 
 2713: 
 2714:     my $userinput = "$cmd:$tail";
 2715: 
 2716:     my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);
 2717:     if (defined($regexp)) {
 2718: 	$regexp=&unescape($regexp);
 2719:     } else {
 2720: 	$regexp='.';
 2721:     }
 2722:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
 2723: 				 &GDBM_READER());
 2724:     if ($hashref) {
 2725:         my $qresult='';
 2726: 	while (my ($key,$value) = each(%$hashref)) {
 2727: 	    if ($regexp eq '.') {
 2728: 		$qresult.=$key.'='.$value.'&';
 2729: 	    } else {
 2730: 		my $unescapeKey = &unescape($key);
 2731: 		if (eval('$unescapeKey=~/$regexp/')) {
 2732: 		    $qresult.="$key=$value&";
 2733: 		}
 2734: 	    }
 2735: 	}
 2736: 	if (untie(%$hashref)) {
 2737: 	    chop($qresult);
 2738: 	    &Reply($client, "$qresult\n", $userinput);
 2739: 	} else {
 2740: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 2741: 		     "while attempting dump\n", $userinput);
 2742: 	}
 2743:     } else {
 2744: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2745: 		"while attempting dump\n", $userinput);
 2746:     }
 2747: 
 2748:     return 1;
 2749: }
 2750: 
 2751: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
 2752: 
 2753: #  Store a set of key=value pairs associated with a versioned name.
 2754: #
 2755: #  Parameters:
 2756: #    $cmd                - Request command keyword.
 2757: #    $tail               - Tail of the request.  This is a colon
 2758: #                          separated list containing:
 2759: #                          domain/user - User and authentication domain.
 2760: #                          namespace   - Name of the database being modified
 2761: #                          rid         - Resource keyword to modify.
 2762: #                          what        - new value associated with rid.
 2763: #
 2764: #    $client             - Socket open on the client.
 2765: #
 2766: #
 2767: #  Returns:
 2768: #      1 (keep on processing).
 2769: #  Side-Effects:
 2770: #    Writes to the client
 2771: sub store_handler {
 2772:     my ($cmd, $tail, $client) = @_;
 2773:  
 2774:     my $userinput = "$cmd:$tail";
 2775: 
 2776:     my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
 2777:     if ($namespace ne 'roles') {
 2778: 
 2779: 	chomp($what);
 2780: 	my @pairs=split(/\&/,$what);
 2781: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
 2782: 				       &GDBM_WRCREAT(), "P",
 2783: 				       "$rid:$what");
 2784: 	if ($hashref) {
 2785: 	    my $now = time;
 2786: 	    my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
 2787: 	    my $key;
 2788: 	    $hashref->{"version:$rid"}++;
 2789: 	    my $version=$hashref->{"version:$rid"};
 2790: 	    my $allkeys=''; 
 2791: 	    foreach my $pair (@pairs) {
 2792: 		my ($key,$value)=split(/=/,$pair);
 2793: 		$allkeys.=$key.':';
 2794: 		$hashref->{"$version:$rid:$key"}=$value;
 2795: 	    }
 2796: 	    $hashref->{"$version:$rid:timestamp"}=$now;
 2797: 	    $allkeys.='timestamp';
 2798: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
 2799: 	    if (untie($hashref)) {
 2800: 		&Reply($client, "ok\n", $userinput);
 2801: 	    } else {
 2802: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2803: 			"while attempting store\n", $userinput);
 2804: 	    }
 2805: 	} else {
 2806: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 2807: 		     "while attempting store\n", $userinput);
 2808: 	}
 2809:     } else {
 2810: 	&Failure($client, "refused\n", $userinput);
 2811:     }
 2812: 
 2813:     return 1;
 2814: }
 2815: &register_handler("store", \&store_handler, 0, 1, 0);
 2816: #
 2817: #  Dump out all versions of a resource that has key=value pairs associated
 2818: # with it for each version.  These resources are built up via the store
 2819: # command.
 2820: #
 2821: #  Parameters:
 2822: #     $cmd               - Command keyword.
 2823: #     $tail              - Remainder of the request which consists of:
 2824: #                          domain/user   - User and auth. domain.
 2825: #                          namespace     - name of resource database.
 2826: #                          rid           - Resource id.
 2827: #    $client             - socket open on the client.
 2828: #
 2829: # Returns:
 2830: #      1  indicating the caller should not yet exit.
 2831: # Side-effects:
 2832: #   Writes a reply to the client.
 2833: #   The reply is a string of the following shape:
 2834: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
 2835: #    Where the 1 above represents version 1.
 2836: #    this continues for all pairs of keys in all versions.
 2837: #
 2838: #
 2839: #    
 2840: #
 2841: sub restore_handler {
 2842:     my ($cmd, $tail, $client) = @_;
 2843: 
 2844:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
 2845: 
 2846:     my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
 2847:     $namespace=~s/\//\_/g;
 2848:     $namespace=~s/\W//g;
 2849:     chomp($rid);
 2850:     my $proname=&propath($udom,$uname);
 2851:     my $qresult='';
 2852:     my %hash;
 2853:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
 2854: 	    &GDBM_READER(),0640)) {
 2855: 	my $version=$hash{"version:$rid"};
 2856: 	$qresult.="version=$version&";
 2857: 	my $scope;
 2858: 	for ($scope=1;$scope<=$version;$scope++) {
 2859: 	    my $vkeys=$hash{"$scope:keys:$rid"};
 2860: 	    my @keys=split(/:/,$vkeys);
 2861: 	    my $key;
 2862: 	    $qresult.="$scope:keys=$vkeys&";
 2863: 	    foreach $key (@keys) {
 2864: 		$qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 2865: 	    }                                  
 2866: 	}
 2867: 	if (untie(%hash)) {
 2868: 	    $qresult=~s/\&$//;
 2869: 	    &Reply( $client, "$qresult\n", $userinput);
 2870: 	} else {
 2871: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 2872: 		    "while attempting restore\n", $userinput);
 2873: 	}
 2874:     } else {
 2875: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 2876: 		"while attempting restore\n", $userinput);
 2877:     }
 2878:   
 2879:     return 1;
 2880: 
 2881: 
 2882: }
 2883: &register_handler("restore", \&restore_handler, 0,1,0);
 2884: 
 2885: #
 2886: #   Add a chat message to to a discussion board.
 2887: #
 2888: # Parameters:
 2889: #    $cmd                - Request keyword.
 2890: #    $tail               - Tail of the command. A colon separated list
 2891: #                          containing:
 2892: #                          cdom    - Domain on which the chat board lives
 2893: #                          cnum    - Identifier of the discussion group.
 2894: #                          post    - Body of the posting.
 2895: #   $client              - Socket open on the client.
 2896: # Returns:
 2897: #   1    - Indicating caller should keep on processing.
 2898: #
 2899: # Side-effects:
 2900: #   writes a reply to the client.
 2901: #
 2902: #
 2903: sub send_chat_handler {
 2904:     my ($cmd, $tail, $client) = @_;
 2905: 
 2906:     
 2907:     my $userinput = "$cmd:$tail";
 2908: 
 2909:     my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
 2910:     &chat_add($cdom,$cnum,$newpost);
 2911:     &Reply($client, "ok\n", $userinput);
 2912: 
 2913:     return 1;
 2914: }
 2915: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
 2916: #
 2917: #   Retrieve the set of chat messagss from a discussion board.
 2918: #
 2919: #  Parameters:
 2920: #    $cmd             - Command keyword that initiated the request.
 2921: #    $tail            - Remainder of the request after the command
 2922: #                       keyword.  In this case a colon separated list of
 2923: #                       chat domain    - Which discussion board.
 2924: #                       chat id        - Discussion thread(?)
 2925: #                       domain/user    - Authentication domain and username
 2926: #                                        of the requesting person.
 2927: #   $client           - Socket open on the client program.
 2928: # Returns:
 2929: #    1     - continue processing
 2930: # Side effects:
 2931: #    Response is written to the client.
 2932: #
 2933: sub retrieve_chat_handler {
 2934:     my ($cmd, $tail, $client) = @_;
 2935: 
 2936: 
 2937:     my $userinput = "$cmd:$tail";
 2938: 
 2939:     my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
 2940:     my $reply='';
 2941:     foreach (&get_chat($cdom,$cnum,$udom,$uname)) {
 2942: 	$reply.=&escape($_).':';
 2943:     }
 2944:     $reply=~s/\:$//;
 2945:     &Reply($client, $reply."\n", $userinput);
 2946: 
 2947: 
 2948:     return 1;
 2949: }
 2950: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
 2951: 
 2952: #
 2953: #  Initiate a query of an sql database.  SQL query repsonses get put in
 2954: #  a file for later retrieval.  This prevents sql query results from
 2955: #  bottlenecking the system.  Note that with loncnew, perhaps this is
 2956: #  less of an issue since multiple outstanding requests can be concurrently
 2957: #  serviced.
 2958: #
 2959: #  Parameters:
 2960: #     $cmd       - COmmand keyword that initiated the request.
 2961: #     $tail      - Remainder of the command after the keyword.
 2962: #                  For this function, this consists of a query and
 2963: #                  3 arguments that are self-documentingly labelled
 2964: #                  in the original arg1, arg2, arg3.
 2965: #     $client    - Socket open on the client.
 2966: # Return:
 2967: #    1   - Indicating processing should continue.
 2968: # Side-effects:
 2969: #    a reply is written to $client.
 2970: #
 2971: sub send_query_handler {
 2972:     my ($cmd, $tail, $client) = @_;
 2973: 
 2974: 
 2975:     my $userinput = "$cmd:$tail";
 2976: 
 2977:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
 2978:     $query=~s/\n*$//g;
 2979:     &Reply($client, "". &sql_reply("$clientname\&$query".
 2980: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
 2981: 	  $userinput);
 2982:     
 2983:     return 1;
 2984: }
 2985: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
 2986: 
 2987: #
 2988: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
 2989: #   The query is submitted via a "querysend" transaction.
 2990: #   There it is passed on to the lonsql daemon, queued and issued to
 2991: #   mysql.
 2992: #     This transaction is invoked when the sql transaction is complete
 2993: #   it stores the query results in flie and indicates query completion.
 2994: #   presumably local software then fetches this response... I'm guessing
 2995: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
 2996: #   lonsql on completion of the query interacts with the lond of our
 2997: #   client to do a query reply storing two files:
 2998: #    - id     - The results of the query.
 2999: #    - id.end - Indicating the transaction completed. 
 3000: #    NOTE: id is a unique id assigned to the query and querysend time.
 3001: # Parameters:
 3002: #    $cmd        - Command keyword that initiated this request.
 3003: #    $tail       - Remainder of the tail.  In this case that's a colon
 3004: #                  separated list containing the query Id and the 
 3005: #                  results of the query.
 3006: #    $client     - Socket open on the client.
 3007: # Return:
 3008: #    1           - Indicating that we should continue processing.
 3009: # Side effects:
 3010: #    ok written to the client.
 3011: #
 3012: sub reply_query_handler {
 3013:     my ($cmd, $tail, $client) = @_;
 3014: 
 3015: 
 3016:     my $userinput = "$cmd:$tail";
 3017: 
 3018:     my ($cmd,$id,$reply)=split(/:/,$userinput); 
 3019:     my $store;
 3020:     my $execdir=$perlvar{'lonDaemons'};
 3021:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
 3022: 	$reply=~s/\&/\n/g;
 3023: 	print $store $reply;
 3024: 	close $store;
 3025: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
 3026: 	print $store2 "done\n";
 3027: 	close $store2;
 3028: 	&Reply($client, "ok\n", $userinput);
 3029:     } else {
 3030: 	&Failure($client, "error: ".($!+0)
 3031: 		." IO::File->new Failed ".
 3032: 		"while attempting queryreply\n", $userinput);
 3033:     }
 3034:  
 3035: 
 3036:     return 1;
 3037: }
 3038: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
 3039: 
 3040: #
 3041: #  Process the courseidput request.  Not quite sure what this means
 3042: #  at the system level sense.  It appears a gdbm file in the 
 3043: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
 3044: #  a set of entries made in that database.
 3045: #
 3046: # Parameters:
 3047: #   $cmd      - The command keyword that initiated this request.
 3048: #   $tail     - Tail of the command.  In this case consists of a colon
 3049: #               separated list contaning the domain to apply this to and
 3050: #               an ampersand separated list of keyword=value pairs.
 3051: #   $client   - Socket open on the client.
 3052: # Returns:
 3053: #   1    - indicating that processing should continue
 3054: #
 3055: # Side effects:
 3056: #   reply is written to the client.
 3057: #
 3058: sub put_course_id_handler {
 3059:     my ($cmd, $tail, $client) = @_;
 3060: 
 3061: 
 3062:     my $userinput = "$cmd:$tail";
 3063: 
 3064:     my ($udom, $what) = split(/:/, $tail);
 3065:     chomp($what);
 3066:     my $now=time;
 3067:     my @pairs=split(/\&/,$what);
 3068: 
 3069:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3070:     if ($hashref) {
 3071: 	foreach my $pair (@pairs) {
 3072: 	    my ($key,$value)=split(/=/,$pair);
 3073: 	    $hashref->{$key}=$value.':'.$now;
 3074: 	}
 3075: 	if (untie(%$hashref)) {
 3076: 	    &Reply($client, "ok\n", $userinput);
 3077: 	} else {
 3078: 	    &Failure( $client, "error: ".($!+0)
 3079: 		     ." untie(GDBM) Failed ".
 3080: 		     "while attempting courseidput\n", $userinput);
 3081: 	}
 3082:     } else {
 3083: 	&Failure( $client, "error: ".($!+0)
 3084: 		 ." tie(GDBM) Failed ".
 3085: 		 "while attempting courseidput\n", $userinput);
 3086:     }
 3087: 
 3088:     return 1;
 3089: }
 3090: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
 3091: 
 3092: #  Retrieves the value of a course id resource keyword pattern
 3093: #  defined since a starting date.  Both the starting date and the
 3094: #  keyword pattern are optional.  If the starting date is not supplied it
 3095: #  is treated as the beginning of time.  If the pattern is not found,
 3096: #  it is treatred as "." matching everything.
 3097: #
 3098: #  Parameters:
 3099: #     $cmd     - Command keyword that resulted in us being dispatched.
 3100: #     $tail    - The remainder of the command that, in this case, consists
 3101: #                of a colon separated list of:
 3102: #                 domain   - The domain in which the course database is 
 3103: #                            defined.
 3104: #                 since    - Optional parameter describing the minimum
 3105: #                            time of definition(?) of the resources that
 3106: #                            will match the dump.
 3107: #                 description - regular expression that is used to filter
 3108: #                            the dump.  Only keywords matching this regexp
 3109: #                            will be used.
 3110: #     $client  - The socket open on the client.
 3111: # Returns:
 3112: #    1     - Continue processing.
 3113: # Side Effects:
 3114: #   a reply is written to $client.
 3115: sub dump_course_id_handler {
 3116:     my ($cmd, $tail, $client) = @_;
 3117: 
 3118:     my $userinput = "$cmd:$tail";
 3119: 
 3120:     my ($udom,$since,$description) =split(/:/,$tail);
 3121:     if (defined($description)) {
 3122: 	$description=&unescape($description);
 3123:     } else {
 3124: 	$description='.';
 3125:     }
 3126:     unless (defined($since)) { $since=0; }
 3127:     my $qresult='';
 3128:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
 3129:     if ($hashref) {
 3130: 	while (my ($key,$value) = each(%$hashref)) {
 3131: 	    my ($descr,$lasttime,$inst_code);
 3132: 	    if ($value =~ m/^([^\:]*):([^\:]*):(\d+)$/) {
 3133: 		($descr,$inst_code,$lasttime)=($1,$2,$3);
 3134: 	    } else {
 3135: 		($descr,$lasttime) = split(/\:/,$value);
 3136: 	    }
 3137: 	    if ($lasttime<$since) { next; }
 3138: 	    if ($description eq '.') {
 3139: 		$qresult.=$key.'='.$descr.':'.$inst_code.'&';
 3140: 	    } else {
 3141: 		my $unescapeVal = &unescape($descr);
 3142: 		if (eval('$unescapeVal=~/\Q$description\E/i')) {
 3143: 		    $qresult.=$key.'='.$descr.':'.$inst_code.'&';
 3144: 		}
 3145: 	    }
 3146: 	}
 3147: 	if (untie(%$hashref)) {
 3148: 	    chop($qresult);
 3149: 	    &Reply($client, "$qresult\n", $userinput);
 3150: 	} else {
 3151: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3152: 		    "while attempting courseiddump\n", $userinput);
 3153: 	}
 3154:     } else {
 3155: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3156: 		"while attempting courseiddump\n", $userinput);
 3157:     }
 3158: 
 3159: 
 3160:     return 1;
 3161: }
 3162: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
 3163: 
 3164: #
 3165: #  Puts an id to a domains id database. 
 3166: #
 3167: #  Parameters:
 3168: #   $cmd     - The command that triggered us.
 3169: #   $tail    - Remainder of the request other than the command. This is a 
 3170: #              colon separated list containing:
 3171: #              $domain  - The domain for which we are writing the id.
 3172: #              $pairs  - The id info to write... this is and & separated list
 3173: #                        of keyword=value.
 3174: #   $client  - Socket open on the client.
 3175: #  Returns:
 3176: #    1   - Continue processing.
 3177: #  Side effects:
 3178: #     reply is written to $client.
 3179: #
 3180: sub put_id_handler {
 3181:     my ($cmd,$tail,$client) = @_;
 3182: 
 3183: 
 3184:     my $userinput = "$cmd:$tail";
 3185: 
 3186:     my ($udom,$what)=split(/:/,$tail);
 3187:     chomp($what);
 3188:     my @pairs=split(/\&/,$what);
 3189:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
 3190: 				   "P", $what);
 3191:     if ($hashref) {
 3192: 	foreach my $pair (@pairs) {
 3193: 	    my ($key,$value)=split(/=/,$pair);
 3194: 	    $hashref->{$key}=$value;
 3195: 	}
 3196: 	if (untie(%$hashref)) {
 3197: 	    &Reply($client, "ok\n", $userinput);
 3198: 	} else {
 3199: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
 3200: 		     "while attempting idput\n", $userinput);
 3201: 	}
 3202:     } else {
 3203: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
 3204: 		  "while attempting idput\n", $userinput);
 3205:     }
 3206: 
 3207:     return 1;
 3208: }
 3209: 
 3210: &register_handler("idput", \&put_id_handler, 0, 1, 0);
 3211: #
 3212: #  Retrieves a set of id values from the id database.
 3213: #  Returns an & separated list of results, one for each requested id to the
 3214: #  client.
 3215: #
 3216: # Parameters:
 3217: #   $cmd       - Command keyword that caused us to be dispatched.
 3218: #   $tail      - Tail of the command.  Consists of a colon separated:
 3219: #               domain - the domain whose id table we dump
 3220: #               ids      Consists of an & separated list of
 3221: #                        id keywords whose values will be fetched.
 3222: #                        nonexisting keywords will have an empty value.
 3223: #   $client    - Socket open on the client.
 3224: #
 3225: # Returns:
 3226: #    1 - indicating processing should continue.
 3227: # Side effects:
 3228: #   An & separated list of results is written to $client.
 3229: #
 3230: sub get_id_handler {
 3231:     my ($cmd, $tail, $client) = @_;
 3232: 
 3233:     
 3234:     my $userinput = "$client:$tail";
 3235:     
 3236:     my ($udom,$what)=split(/:/,$tail);
 3237:     chomp($what);
 3238:     my @queries=split(/\&/,$what);
 3239:     my $qresult='';
 3240:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
 3241:     if ($hashref) {
 3242: 	for (my $i=0;$i<=$#queries;$i++) {
 3243: 	    $qresult.="$hashref->{$queries[$i]}&";
 3244: 	}
 3245: 	if (untie(%$hashref)) {
 3246: 	    $qresult=~s/\&$//;
 3247: 	    &Reply($client, "$qresult\n", $userinput);
 3248: 	} else {
 3249: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
 3250: 		      "while attempting idget\n",$userinput);
 3251: 	}
 3252:     } else {
 3253: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
 3254: 		 "while attempting idget\n",$userinput);
 3255:     }
 3256:     
 3257:     return 1;
 3258: }
 3259: 
 3260: register_handler("idget", \&get_id_handler, 0, 1, 0);
 3261: 
 3262: #
 3263: #  Process the tmpput command I'm not sure what this does.. Seems to
 3264: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
 3265: # where Id is the client's ip concatenated with a sequence number.
 3266: # The file will contain some value that is passed in.  Is this e.g.
 3267: # a login token?
 3268: #
 3269: # Parameters:
 3270: #    $cmd     - The command that got us dispatched.
 3271: #    $tail    - The remainder of the request following $cmd:
 3272: #               In this case this will be the contents of the file.
 3273: #    $client  - Socket connected to the client.
 3274: # Returns:
 3275: #    1 indicating processing can continue.
 3276: # Side effects:
 3277: #   A file is created in the local filesystem.
 3278: #   A reply is sent to the client.
 3279: sub tmp_put_handler {
 3280:     my ($cmd, $what, $client) = @_;
 3281: 
 3282:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
 3283: 
 3284: 
 3285:     my $store;
 3286:     $tmpsnum++;
 3287:     my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 3288:     $id=~s/\W/\_/g;
 3289:     $what=~s/\n//g;
 3290:     my $execdir=$perlvar{'lonDaemons'};
 3291:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 3292: 	print $store $what;
 3293: 	close $store;
 3294: 	&Reply($client, "$id\n", $userinput);
 3295:     } else {
 3296: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 3297: 		  "while attempting tmpput\n", $userinput);
 3298:     }
 3299:     return 1;
 3300:   
 3301: }
 3302: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
 3303: #   Processes the tmpget command.  This command returns the contents
 3304: #  of a temporary resource file(?) created via tmpput.
 3305: #
 3306: # Paramters:
 3307: #    $cmd      - Command that got us dispatched.
 3308: #    $id       - Tail of the command, contain the id of the resource
 3309: #                we want to fetch.
 3310: #    $client   - socket open on the client.
 3311: # Return:
 3312: #    1         - Inidcating processing can continue.
 3313: # Side effects:
 3314: #   A reply is sent to the client.
 3315: 
 3316: #
 3317: sub tmp_get_handler {
 3318:     my ($cmd, $id, $client) = @_;
 3319: 
 3320:     my $userinput = "$cmd:$id"; 
 3321:     
 3322: 
 3323:     $id=~s/\W/\_/g;
 3324:     my $store;
 3325:     my $execdir=$perlvar{'lonDaemons'};
 3326:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 3327: 	my $reply=<$store>;
 3328: 	&Reply( $client, "$reply\n", $userinput);
 3329: 	close $store;
 3330:     } else {
 3331: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
 3332: 		  "while attempting tmpget\n", $userinput);
 3333:     }
 3334: 
 3335:     return 1;
 3336: }
 3337: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
 3338: #
 3339: #  Process the tmpdel command.  This command deletes a temp resource
 3340: #  created by the tmpput command.
 3341: #
 3342: # Parameters:
 3343: #   $cmd      - Command that got us here.
 3344: #   $id       - Id of the temporary resource created.
 3345: #   $client   - socket open on the client process.
 3346: #
 3347: # Returns:
 3348: #   1     - Indicating processing should continue.
 3349: # Side Effects:
 3350: #   A file is deleted
 3351: #   A reply is sent to the client.
 3352: sub tmp_del_handler {
 3353:     my ($cmd, $id, $client) = @_;
 3354:     
 3355:     my $userinput= "$cmd:$id";
 3356:     
 3357:     chomp($id);
 3358:     $id=~s/\W/\_/g;
 3359:     my $execdir=$perlvar{'lonDaemons'};
 3360:     if (unlink("$execdir/tmp/$id.tmp")) {
 3361: 	&Reply($client, "ok\n", $userinput);
 3362:     } else {
 3363: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
 3364: 		  "while attempting tmpdel\n", $userinput);
 3365:     }
 3366:     
 3367:     return 1;
 3368: 
 3369: }
 3370: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
 3371: #
 3372: #   Processes the setannounce command.  This command
 3373: #   creates a file named announce.txt in the top directory of
 3374: #   the documentn root and sets its contents.  The announce.txt file is
 3375: #   printed in its entirety at the LonCAPA login page.  Note:
 3376: #   once the announcement.txt fileis created it cannot be deleted.
 3377: #   However, setting the contents of the file to empty removes the
 3378: #   announcement from the login page of loncapa so who cares.
 3379: #
 3380: # Parameters:
 3381: #    $cmd          - The command that got us dispatched.
 3382: #    $announcement - The text of the announcement.
 3383: #    $client       - Socket open on the client process.
 3384: # Retunrns:
 3385: #   1             - Indicating request processing should continue
 3386: # Side Effects:
 3387: #   The file {DocRoot}/announcement.txt is created.
 3388: #   A reply is sent to $client.
 3389: #
 3390: sub set_announce_handler {
 3391:     my ($cmd, $announcement, $client) = @_;
 3392:   
 3393:     my $userinput    = "$cmd:$announcement";
 3394: 
 3395:     chomp($announcement);
 3396:     $announcement=&unescape($announcement);
 3397:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 3398: 				'/announcement.txt')) {
 3399: 	print $store $announcement;
 3400: 	close $store;
 3401: 	&Reply($client, "ok\n", $userinput);
 3402:     } else {
 3403: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
 3404:     }
 3405: 
 3406:     return 1;
 3407: }
 3408: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
 3409: #
 3410: #  Return the version of the daemon.  This can be used to determine
 3411: #  the compatibility of cross version installations or, alternatively to
 3412: #  simply know who's out of date and who isn't.  Note that the version
 3413: #  is returned concatenated with the tail.
 3414: # Parameters:
 3415: #   $cmd        - the request that dispatched to us.
 3416: #   $tail       - Tail of the request (client's version?).
 3417: #   $client     - Socket open on the client.
 3418: #Returns:
 3419: #   1 - continue processing requests.
 3420: # Side Effects:
 3421: #   Replies with version to $client.
 3422: sub get_version_handler {
 3423:     my ($cmd, $tail, $client) = @_;
 3424: 
 3425:     my $userinput  = $cmd.$tail;
 3426:     
 3427:     &Reply($client, &version($userinput)."\n", $userinput);
 3428: 
 3429: 
 3430:     return 1;
 3431: }
 3432: &register_handler("version", \&get_version_handler, 0, 1, 0);
 3433: #  Set the current host and domain.  This is used to support
 3434: #  multihomed systems.  Each IP of the system, or even separate daemons
 3435: #  on the same IP can be treated as handling a separate lonCAPA virtual
 3436: #  machine.  This command selects the virtual lonCAPA.  The client always
 3437: #  knows the right one since it is lonc and it is selecting the domain/system
 3438: #  from the hosts.tab file.
 3439: # Parameters:
 3440: #    $cmd      - Command that dispatched us.
 3441: #    $tail     - Tail of the command (domain/host requested).
 3442: #    $socket   - Socket open on the client.
 3443: #
 3444: # Returns:
 3445: #     1   - Indicates the program should continue to process requests.
 3446: # Side-effects:
 3447: #     The default domain/system context is modified for this daemon.
 3448: #     a reply is sent to the client.
 3449: #
 3450: sub set_virtual_host_handler {
 3451:     my ($cmd, $tail, $socket) = @_;
 3452:   
 3453:     my $userinput  ="$cmd:$tail";
 3454: 
 3455:     &Reply($client, &sethost($userinput)."\n", $userinput);
 3456: 
 3457: 
 3458:     return 1;
 3459: }
 3460: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
 3461: 
 3462: #  Process a request to exit:
 3463: #   - "bye" is sent to the client.
 3464: #   - The client socket is shutdown and closed.
 3465: #   - We indicate to the caller that we should exit.
 3466: # Formal Parameters:
 3467: #   $cmd                - The command that got us here.
 3468: #   $tail               - Tail of the command (empty).
 3469: #   $client             - Socket open on the tail.
 3470: # Returns:
 3471: #   0      - Indicating the program should exit!!
 3472: #
 3473: sub exit_handler {
 3474:     my ($cmd, $tail, $client) = @_;
 3475: 
 3476:     my $userinput = "$cmd:$tail";
 3477: 
 3478:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
 3479:     &Reply($client, "bye\n", $userinput);
 3480:     $client->shutdown(2);        # shutdown the socket forcibly.
 3481:     $client->close();
 3482: 
 3483:     return 0;
 3484: }
 3485: &register_handler("exit", \&exit_handler, 0,1,1);
 3486: &register_handler("init", \&exit_handler, 0,1,1);
 3487: &register_handler("quit", \&exit_handler, 0,1,1);
 3488: 
 3489: #  Determine if auto-enrollment is enabled.
 3490: #  Note that the original had what I believe to be a defect.
 3491: #  The original returned 0 if the requestor was not a registerd client.
 3492: #  It should return "refused".
 3493: # Formal Parameters:
 3494: #   $cmd       - The command that invoked us.
 3495: #   $tail      - The tail of the command (Extra command parameters.
 3496: #   $client    - The socket open on the client that issued the request.
 3497: # Returns:
 3498: #    1         - Indicating processing should continue.
 3499: #
 3500: sub enrollment_enabled_handler {
 3501:     my ($cmd, $tail, $client) = @_;
 3502:     my $userinput = $cmd.":".$tail; # For logging purposes.
 3503: 
 3504:     
 3505:     my $cdom = split(/:/, $tail);   # Domain we're asking about.
 3506:     my $outcome  = &localenroll::run($cdom);
 3507:     &Reply($client, "$outcome\n", $userinput);
 3508: 
 3509:     return 1;
 3510: }
 3511: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
 3512: 
 3513: #   Get the official sections for which auto-enrollment is possible.
 3514: #   Since the admin people won't know about 'unofficial sections' 
 3515: #   we cannot auto-enroll on them.
 3516: # Formal Parameters:
 3517: #    $cmd     - The command request that got us dispatched here.
 3518: #    $tail    - The remainder of the request.  In our case this
 3519: #               will be split into:
 3520: #               $coursecode   - The course name from the admin point of view.
 3521: #               $cdom         - The course's domain(?).
 3522: #    $client  - Socket open on the client.
 3523: # Returns:
 3524: #    1    - Indiciting processing should continue.
 3525: #
 3526: sub get_sections_handler {
 3527:     my ($cmd, $tail, $client) = @_;
 3528:     my $userinput = "$cmd:$tail";
 3529: 
 3530:     my ($coursecode, $cdom) = split(/:/, $tail);
 3531:     my @secs = &localenroll::get_sections($coursecode,$cdom);
 3532:     my $seclist = &escape(join(':',@secs));
 3533: 
 3534:     &Reply($client, "$seclist\n", $userinput);
 3535:     
 3536: 
 3537:     return 1;
 3538: }
 3539: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
 3540: 
 3541: #   Validate the owner of a new course section.  
 3542: #
 3543: # Formal Parameters:
 3544: #   $cmd      - Command that got us dispatched.
 3545: #   $tail     - the remainder of the command.  For us this consists of a
 3546: #               colon separated string containing:
 3547: #                  $inst    - Course Id from the institutions point of view.
 3548: #                  $owner   - Proposed owner of the course.
 3549: #                  $cdom    - Domain of the course (from the institutions
 3550: #                             point of view?)..
 3551: #   $client   - Socket open on the client.
 3552: #
 3553: # Returns:
 3554: #   1        - Processing should continue.
 3555: #
 3556: sub validate_course_owner_handler {
 3557:     my ($cmd, $tail, $client)  = @_;
 3558:     my $userinput = "$cmd:$tail";
 3559:     my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
 3560: 
 3561:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
 3562:     &Reply($client, "$outcome\n", $userinput);
 3563: 
 3564: 
 3565: 
 3566:     return 1;
 3567: }
 3568: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
 3569: #
 3570: #   Validate a course section in the official schedule of classes
 3571: #   from the institutions point of view (part of autoenrollment).
 3572: #
 3573: # Formal Parameters:
 3574: #   $cmd          - The command request that got us dispatched.
 3575: #   $tail         - The tail of the command.  In this case,
 3576: #                   this is a colon separated set of words that will be split
 3577: #                   into:
 3578: #                        $inst_course_id - The course/section id from the
 3579: #                                          institutions point of view.
 3580: #                        $cdom           - The domain from the institutions
 3581: #                                          point of view.
 3582: #   $client       - Socket open on the client.
 3583: # Returns:
 3584: #    1           - Indicating processing should continue.
 3585: #
 3586: sub validate_course_section_handler {
 3587:     my ($cmd, $tail, $client) = @_;
 3588:     my $userinput = "$cmd:$tail";
 3589:     my ($inst_course_id, $cdom) = split(/:/, $tail);
 3590: 
 3591:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 3592:     &Reply($client, "$outcome\n", $userinput);
 3593: 
 3594: 
 3595:     return 1;
 3596: }
 3597: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
 3598: 
 3599: #
 3600: #   Create a password for a new auto-enrollment user.
 3601: #   I think/guess, this password allows access to the institutions 
 3602: #   AIS class list server/services.  Stuart can correct this comment
 3603: #   when he finds out how wrong I am.
 3604: #
 3605: # Formal Parameters:
 3606: #    $cmd     - The command request that got us dispatched.
 3607: #    $tail    - The tail of the command.   In this case this is a colon separated
 3608: #               set of words that will be split into:
 3609: #               $authparam - An authentication parameter (username??).
 3610: #               $cdom      - The domain of the course from the institution's
 3611: #                            point of view.
 3612: #    $client  - The socket open on the client.
 3613: # Returns:
 3614: #    1 - continue processing.
 3615: #
 3616: sub create_auto_enroll_password_handler {
 3617:     my ($cmd, $tail, $client) = @_;
 3618:     my $userinput = "$cmd:$tail";
 3619: 
 3620:     my ($authparam, $cdom) = split(/:/, $userinput);
 3621: 
 3622:     my ($create_passwd,$authchk);
 3623:     ($authparam,
 3624:      $create_passwd,
 3625:      $authchk) = &localenroll::create_password($authparam,$cdom);
 3626: 
 3627:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
 3628: 	   $userinput);
 3629: 
 3630: 
 3631:     return 1;
 3632: }
 3633: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
 3634: 		  0, 1, 0);
 3635: 
 3636: #   Retrieve and remove temporary files created by/during autoenrollment.
 3637: #
 3638: # Formal Parameters:
 3639: #    $cmd      - The command that got us dispatched.
 3640: #    $tail     - The tail of the command.  In our case this is a colon 
 3641: #                separated list that will be split into:
 3642: #                $filename - The name of the file to remove.
 3643: #                            The filename is given as a path relative to
 3644: #                            the LonCAPA temp file directory.
 3645: #    $client   - Socket open on the client.
 3646: #
 3647: # Returns:
 3648: #   1     - Continue processing.
 3649: 
 3650: sub retrieve_auto_file_handler {
 3651:     my ($cmd, $tail, $client)    = @_;
 3652:     my $userinput                = "cmd:$tail";
 3653: 
 3654:     my ($filename)   = split(/:/, $tail);
 3655: 
 3656:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 3657:     if ( (-e $source) && ($filename ne '') ) {
 3658: 	my $reply = '';
 3659: 	if (open(my $fh,$source)) {
 3660: 	    while (<$fh>) {
 3661: 		chomp($_);
 3662: 		$_ =~ s/^\s+//g;
 3663: 		$_ =~ s/\s+$//g;
 3664: 		$reply .= $_;
 3665: 	    }
 3666: 	    close($fh);
 3667: 	    &Reply($client, &escape($reply)."\n", $userinput);
 3668: 
 3669: #   Does this have to be uncommented??!?  (RF).
 3670: #
 3671: #                                unlink($source);
 3672: 	} else {
 3673: 	    &Failure($client, "error\n", $userinput);
 3674: 	}
 3675:     } else {
 3676: 	&Failure($client, "error\n", $userinput);
 3677:     }
 3678:     
 3679: 
 3680:     return 1;
 3681: }
 3682: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
 3683: 
 3684: #
 3685: #   Read and retrieve institutional code format (for support form).
 3686: # Formal Parameters:
 3687: #    $cmd        - Command that dispatched us.
 3688: #    $tail       - Tail of the command.  In this case it conatins 
 3689: #                  the course domain and the coursename.
 3690: #    $client     - Socket open on the client.
 3691: # Returns:
 3692: #    1     - Continue processing.
 3693: #
 3694: sub get_institutional_code_format_handler {
 3695:     my ($cmd, $tail, $client)   = @_;
 3696:     my $userinput               = "$cmd:$tail";
 3697: 
 3698:     my $reply;
 3699:     my($cdom,$course) = split(/:/,$tail);
 3700:     my @pairs = split/\&/,$course;
 3701:     my %instcodes = ();
 3702:     my %codes = ();
 3703:     my @codetitles = ();
 3704:     my %cat_titles = ();
 3705:     my %cat_order = ();
 3706:     foreach (@pairs) {
 3707: 	my ($key,$value) = split/=/,$_;
 3708: 	$instcodes{&unescape($key)} = &unescape($value);
 3709:     }
 3710:     my $formatreply = &localenroll::instcode_format($cdom,
 3711: 						    \%instcodes,
 3712: 						    \%codes,
 3713: 						    \@codetitles,
 3714: 						    \%cat_titles,
 3715: 						    \%cat_order);
 3716:     if ($formatreply eq 'ok') {
 3717: 	my $codes_str = &hash2str(%codes);
 3718: 	my $codetitles_str = &array2str(@codetitles);
 3719: 	my $cat_titles_str = &hash2str(%cat_titles);
 3720: 	my $cat_order_str = &hash2str(%cat_order);
 3721: 	&Reply($client,
 3722: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
 3723: 	       .$cat_order_str."\n",
 3724: 	       $userinput);
 3725:     } else {
 3726: 	# this else branch added by RF since if not ok, lonc will
 3727: 	# hang waiting on reply until timeout.
 3728: 	#
 3729: 	&Reply($client, "format_error\n", $userinput);
 3730:     }
 3731:     
 3732:     return 1;
 3733: }
 3734: 
 3735: &register_handler("autoinstcodeformat", \&get_institutional_code_format_handler,
 3736: 		  0,1,0);
 3737: 
 3738: #
 3739: #
 3740: #
 3741: #
 3742: #
 3743: #---------------------------------------------------------------
 3744: #
 3745: #   Getting, decoding and dispatching requests:
 3746: #
 3747: 
 3748: #
 3749: #   Get a Request:
 3750: #   Gets a Request message from the client.  The transaction
 3751: #   is defined as a 'line' of text.  We remove the new line
 3752: #   from the text line.  
 3753: #
 3754: sub get_request {
 3755:     my $input = <$client>;
 3756:     chomp($input);
 3757: 
 3758:     &Debug("get_request: Request = $input\n");
 3759: 
 3760:     &status('Processing '.$clientname.':'.$input);
 3761: 
 3762:     return $input;
 3763: }
 3764: #---------------------------------------------------------------
 3765: #
 3766: #  Process a request.  This sub should shrink as each action
 3767: #  gets farmed out into a separat sub that is registered 
 3768: #  with the dispatch hash.  
 3769: #
 3770: # Parameters:
 3771: #    user_input   - The request received from the client (lonc).
 3772: # Returns:
 3773: #    true to keep processing, false if caller should exit.
 3774: #
 3775: sub process_request {
 3776:     my ($userinput) = @_;      # Easier for now to break style than to
 3777:                                 # fix all the userinput -> user_input.
 3778:     my $wasenc    = 0;		# True if request was encrypted.
 3779: # ------------------------------------------------------------ See if encrypted
 3780:     if ($userinput =~ /^enc/) {
 3781: 	$userinput = decipher($userinput);
 3782: 	$wasenc=1;
 3783: 	if(!$userinput) {	# Cipher not defined.
 3784: 	    &Failure($client, "error: Encrypted data without negotated key");
 3785: 	    return 0;
 3786: 	}
 3787:     }
 3788:     Debug("process_request: $userinput\n");
 3789:     
 3790:     #  
 3791:     #   The 'correct way' to add a command to lond is now to
 3792:     #   write a sub to execute it and Add it to the command dispatch
 3793:     #   hash via a call to register_handler..  The comments to that
 3794:     #   sub should give you enough to go on to show how to do this
 3795:     #   along with the examples that are building up as this code
 3796:     #   is getting refactored.   Until all branches of the
 3797:     #   if/elseif monster below have been factored out into
 3798:     #   separate procesor subs, if the dispatch hash is missing
 3799:     #   the command keyword, we will fall through to the remainder
 3800:     #   of the if/else chain below in order to keep this thing in 
 3801:     #   working order throughout the transmogrification.
 3802: 
 3803:     my ($command, $tail) = split(/:/, $userinput, 2);
 3804:     chomp($command);
 3805:     chomp($tail);
 3806:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
 3807:     $command =~ s/(\r)//;	# And this too for parameterless commands.
 3808:     if(!$tail) {
 3809: 	$tail ="";		# defined but blank.
 3810:     }
 3811: 
 3812:     &Debug("Command received: $command, encoded = $wasenc");
 3813: 
 3814:     if(defined $Dispatcher{$command}) {
 3815: 
 3816: 	my $dispatch_info = $Dispatcher{$command};
 3817: 	my $handler       = $$dispatch_info[0];
 3818: 	my $need_encode   = $$dispatch_info[1];
 3819: 	my $client_types  = $$dispatch_info[2];
 3820: 	Debug("Matched dispatch hash: mustencode: $need_encode "
 3821: 	      ."ClientType $client_types");
 3822:       
 3823: 	#  Validate the request:
 3824:       
 3825: 	my $ok = 1;
 3826: 	my $requesterprivs = 0;
 3827: 	if(&isClient()) {
 3828: 	    $requesterprivs |= $CLIENT_OK;
 3829: 	}
 3830: 	if(&isManager()) {
 3831: 	    $requesterprivs |= $MANAGER_OK;
 3832: 	}
 3833: 	if($need_encode && (!$wasenc)) {
 3834: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
 3835: 	    $ok = 0;
 3836: 	}
 3837: 	if(($client_types & $requesterprivs) == 0) {
 3838: 	    Debug("Client not privileged to do this operation");
 3839: 	    $ok = 0;
 3840: 	}
 3841: 
 3842: 	if($ok) {
 3843: 	    Debug("Dispatching to handler $command $tail");
 3844: 	    my $keep_going = &$handler($command, $tail, $client);
 3845: 	    return $keep_going;
 3846: 	} else {
 3847: 	    Debug("Refusing to dispatch because client did not match requirements");
 3848: 	    Failure($client, "refused\n", $userinput);
 3849: 	    return 1;
 3850: 	}
 3851: 
 3852:     }    
 3853: 
 3854: #------------------- Commands not yet in spearate handlers. --------------
 3855: 
 3856: #------------------------------- is auto-enrollment enabled?
 3857:     if ($userinput =~/^autorun/) {
 3858: 	if (isClient) {
 3859: 	    my ($cmd,$cdom) = split(/:/,$userinput);
 3860: 	    my $outcome = &localenroll::run($cdom);
 3861: 	    print $client "$outcome\n";
 3862: 	} else {
 3863: 	    print $client "0\n";
 3864: 	}
 3865: #------------------------------- get official sections (for auto-enrollment).
 3866:     } elsif ($userinput =~/^autogetsections/) {
 3867: 	if (isClient) {
 3868: 	    my ($cmd,$coursecode,$cdom)=split(/:/,$userinput);
 3869: 	    my @secs = &localenroll::get_sections($coursecode,$cdom);
 3870: 	    my $seclist = &escape(join(':',@secs));
 3871: 	    print $client "$seclist\n";
 3872: 	} else {
 3873: 	    print $client "refused\n";
 3874: 	}
 3875: #----------------------- validate owner of new course section (for auto-enrollment).
 3876:     } elsif ($userinput =~/^autonewcourse/) {
 3877: 	if (isClient) {
 3878: 	    my ($cmd,$inst_course_id,$owner,$cdom)=split(/:/,$userinput);
 3879: 	    my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
 3880: 	    print $client "$outcome\n";
 3881: 	} else {
 3882: 	    print $client "refused\n";
 3883: 	}
 3884: #-------------- validate course section in schedule of classes (for auto-enrollment).
 3885:     } elsif ($userinput =~/^autovalidatecourse/) {
 3886: 	if (isClient) {
 3887: 	    my ($cmd,$inst_course_id,$cdom)=split(/:/,$userinput);
 3888: 	    my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
 3889: 	    print $client "$outcome\n";
 3890: 	} else {
 3891: 	    print $client "refused\n";
 3892: 	}
 3893: #--------------------------- create password for new user (for auto-enrollment).
 3894:     } elsif ($userinput =~/^autocreatepassword/) {
 3895: 	if (isClient) {
 3896: 	    my ($cmd,$authparam,$cdom)=split(/:/,$userinput);
 3897: 	    my ($create_passwd,$authchk);
 3898: 	    ($authparam,$create_passwd,$authchk) = &localenroll::create_password($authparam,$cdom);
 3899: 	    print $client &escape($authparam.':'.$create_passwd.':'.$authchk)."\n";
 3900: 	} else {
 3901: 	    print $client "refused\n";
 3902: 	}
 3903: #---------------------------  read and remove temporary files (for auto-enrollment).
 3904:     } elsif ($userinput =~/^autoretrieve/) {
 3905: 	if (isClient) {
 3906: 	    my ($cmd,$filename) = split(/:/,$userinput);
 3907: 	    my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
 3908: 	    if ( (-e $source) && ($filename ne '') ) {
 3909: 		my $reply = '';
 3910: 		if (open(my $fh,$source)) {
 3911: 		    while (<$fh>) {
 3912: 			chomp($_);
 3913: 			$_ =~ s/^\s+//g;
 3914: 			$_ =~ s/\s+$//g;
 3915: 			$reply .= $_;
 3916: 		    }
 3917: 		    close($fh);
 3918: 		    print $client &escape($reply)."\n";
 3919: #                                unlink($source);
 3920: 		} else {
 3921: 		    print $client "error\n";
 3922: 		}
 3923: 	    } else {
 3924: 		print $client "error\n";
 3925: 	    }
 3926: 	} else {
 3927: 	    print $client "refused\n";
 3928: 	}
 3929: #---------------------  read and retrieve institutional code format 
 3930: #                          (for support form).
 3931:     } elsif ($userinput =~/^autoinstcodeformat/) {
 3932: 	if (isClient) {
 3933: 	    my $reply;
 3934: 	    my($cmd,$cdom,$course) = split(/:/,$userinput);
 3935: 	    my @pairs = split/\&/,$course;
 3936: 	    my %instcodes = ();
 3937: 	    my %codes = ();
 3938: 	    my @codetitles = ();
 3939: 	    my %cat_titles = ();
 3940: 	    my %cat_order = ();
 3941: 	    foreach (@pairs) {
 3942: 		my ($key,$value) = split/=/,$_;
 3943: 		$instcodes{&unescape($key)} = &unescape($value);
 3944: 	    }
 3945: 	    my $formatreply = &localenroll::instcode_format($cdom,\%instcodes,\%codes,\@codetitles,\%cat_titles,\%cat_order);
 3946: 	    if ($formatreply eq 'ok') {
 3947: 		my $codes_str = &hash2str(%codes);
 3948: 		my $codetitles_str = &array2str(@codetitles);
 3949: 		my $cat_titles_str = &hash2str(%cat_titles);
 3950: 		my $cat_order_str = &hash2str(%cat_order);
 3951: 		print $client $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'.$cat_order_str."\n";
 3952: 	    }
 3953: 	} else {
 3954: 	    print $client "refused\n";
 3955: 	}
 3956: # ------------------------------------------------------------- unknown command
 3957: 	
 3958:     } else {
 3959: 	# unknown command
 3960: 	print $client "unknown_cmd\n";
 3961:     }
 3962: # -------------------------------------------------------------------- complete
 3963:     Debug("process_request - returning 1");
 3964:     return 1;
 3965: }
 3966: #
 3967: #   Decipher encoded traffic
 3968: #  Parameters:
 3969: #     input      - Encoded data.
 3970: #  Returns:
 3971: #     Decoded data or undef if encryption key was not yet negotiated.
 3972: #  Implicit input:
 3973: #     cipher  - This global holds the negotiated encryption key.
 3974: #
 3975: sub decipher {
 3976:     my ($input)  = @_;
 3977:     my $output = '';
 3978:     
 3979:     
 3980:     if($cipher) {
 3981: 	my($enc, $enclength, $encinput) = split(/:/, $input);
 3982: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
 3983: 	    $output .= 
 3984: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
 3985: 	}
 3986: 	return substr($output, 0, $enclength);
 3987:     } else {
 3988: 	return undef;
 3989:     }
 3990: }
 3991: 
 3992: #
 3993: #   Register a command processor.  This function is invoked to register a sub
 3994: #   to process a request.  Once registered, the ProcessRequest sub can automatically
 3995: #   dispatch requests to an appropriate sub, and do the top level validity checking
 3996: #   as well:
 3997: #    - Is the keyword recognized.
 3998: #    - Is the proper client type attempting the request.
 3999: #    - Is the request encrypted if it has to be.
 4000: #   Parameters:
 4001: #    $request_name         - Name of the request being registered.
 4002: #                           This is the command request that will match
 4003: #                           against the hash keywords to lookup the information
 4004: #                           associated with the dispatch information.
 4005: #    $procedure           - Reference to a sub to call to process the request.
 4006: #                           All subs get called as follows:
 4007: #                             Procedure($cmd, $tail, $replyfd, $key)
 4008: #                             $cmd    - the actual keyword that invoked us.
 4009: #                             $tail   - the tail of the request that invoked us.
 4010: #                             $replyfd- File descriptor connected to the client
 4011: #    $must_encode          - True if the request must be encoded to be good.
 4012: #    $client_ok            - True if it's ok for a client to request this.
 4013: #    $manager_ok           - True if it's ok for a manager to request this.
 4014: # Side effects:
 4015: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
 4016: #      - On failure, the program will die as it's a bad internal bug to try to 
 4017: #        register a duplicate command handler.
 4018: #
 4019: sub register_handler {
 4020:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
 4021: 
 4022:     #  Don't allow duplication#
 4023:    
 4024:     if (defined $Dispatcher{$request_name}) {
 4025: 	die "Attempting to define a duplicate request handler for $request_name\n";
 4026:     }
 4027:     #   Build the client type mask:
 4028:     
 4029:     my $client_type_mask = 0;
 4030:     if($client_ok) {
 4031: 	$client_type_mask  |= $CLIENT_OK;
 4032:     }
 4033:     if($manager_ok) {
 4034: 	$client_type_mask  |= $MANAGER_OK;
 4035:     }
 4036:    
 4037:     #  Enter the hash:
 4038:       
 4039:     my @entry = ($procedure, $must_encode, $client_type_mask);
 4040:    
 4041:     $Dispatcher{$request_name} = \@entry;
 4042:    
 4043: }
 4044: 
 4045: 
 4046: #------------------------------------------------------------------
 4047: 
 4048: 
 4049: 
 4050: 
 4051: #
 4052: #  Convert an error return code from lcpasswd to a string value.
 4053: #
 4054: sub lcpasswdstrerror {
 4055:     my $ErrorCode = shift;
 4056:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
 4057: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
 4058:     } else {
 4059: 	return $passwderrors[$ErrorCode];
 4060:     }
 4061: }
 4062: 
 4063: #
 4064: # Convert an error return code from lcuseradd to a string value:
 4065: #
 4066: sub lcuseraddstrerror {
 4067:     my $ErrorCode = shift;
 4068:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
 4069: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
 4070:     } else {
 4071: 	return $adderrors[$ErrorCode];
 4072:     }
 4073: }
 4074: 
 4075: # grabs exception and records it to log before exiting
 4076: sub catchexception {
 4077:     my ($error)=@_;
 4078:     $SIG{'QUIT'}='DEFAULT';
 4079:     $SIG{__DIE__}='DEFAULT';
 4080:     &status("Catching exception");
 4081:     &logthis("<font color='red'>CRITICAL: "
 4082:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
 4083:      ."a crash with this error msg->[$error]</font>");
 4084:     &logthis('Famous last words: '.$status.' - '.$lastlog);
 4085:     if ($client) { print $client "error: $error\n"; }
 4086:     $server->close();
 4087:     die($error);
 4088: }
 4089: sub timeout {
 4090:     &status("Handling Timeout");
 4091:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
 4092:     &catchexception('Timeout');
 4093: }
 4094: # -------------------------------- Set signal handlers to record abnormal exits
 4095: 
 4096: 
 4097: $SIG{'QUIT'}=\&catchexception;
 4098: $SIG{__DIE__}=\&catchexception;
 4099: 
 4100: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
 4101: &status("Read loncapa.conf and loncapa_apache.conf");
 4102: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 4103: %perlvar=%{$perlvarref};
 4104: undef $perlvarref;
 4105: 
 4106: # ----------------------------- Make sure this process is running from user=www
 4107: my $wwwid=getpwnam('www');
 4108: if ($wwwid!=$<) {
 4109:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 4110:    my $subj="LON: $currenthostid User ID mismatch";
 4111:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
 4112:  mailto $emailto -s '$subj' > /dev/null");
 4113:    exit 1;
 4114: }
 4115: 
 4116: # --------------------------------------------- Check if other instance running
 4117: 
 4118: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
 4119: 
 4120: if (-e $pidfile) {
 4121:    my $lfh=IO::File->new("$pidfile");
 4122:    my $pide=<$lfh>;
 4123:    chomp($pide);
 4124:    if (kill 0 => $pide) { die "already running"; }
 4125: }
 4126: 
 4127: # ------------------------------------------------------------- Read hosts file
 4128: 
 4129: 
 4130: 
 4131: # establish SERVER socket, bind and listen.
 4132: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
 4133:                                 Type      => SOCK_STREAM,
 4134:                                 Proto     => 'tcp',
 4135:                                 Reuse     => 1,
 4136:                                 Listen    => 10 )
 4137:   or die "making socket: $@\n";
 4138: 
 4139: # --------------------------------------------------------- Do global variables
 4140: 
 4141: # global variables
 4142: 
 4143: my %children               = ();       # keys are current child process IDs
 4144: 
 4145: sub REAPER {                        # takes care of dead children
 4146:     $SIG{CHLD} = \&REAPER;
 4147:     &status("Handling child death");
 4148:     my $pid;
 4149:     do {
 4150: 	$pid = waitpid(-1,&WNOHANG());
 4151: 	if (defined($children{$pid})) {
 4152: 	    &logthis("Child $pid died");
 4153: 	    delete($children{$pid});
 4154: 	} elsif ($pid > 0) {
 4155: 	    &logthis("Unknown Child $pid died");
 4156: 	}
 4157:     } while ( $pid > 0 );
 4158:     foreach my $child (keys(%children)) {
 4159: 	$pid = waitpid($child,&WNOHANG());
 4160: 	if ($pid > 0) {
 4161: 	    &logthis("Child $child - $pid looks like we missed it's death");
 4162: 	    delete($children{$pid});
 4163: 	}
 4164:     }
 4165:     &status("Finished Handling child death");
 4166: }
 4167: 
 4168: sub HUNTSMAN {                      # signal handler for SIGINT
 4169:     &status("Killing children (INT)");
 4170:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
 4171:     kill 'INT' => keys %children;
 4172:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 4173:     my $execdir=$perlvar{'lonDaemons'};
 4174:     unlink("$execdir/logs/lond.pid");
 4175:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
 4176:     &status("Done killing children");
 4177:     exit;                           # clean up with dignity
 4178: }
 4179: 
 4180: sub HUPSMAN {                      # signal handler for SIGHUP
 4181:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
 4182:     &status("Killing children for restart (HUP)");
 4183:     kill 'INT' => keys %children;
 4184:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
 4185:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
 4186:     my $execdir=$perlvar{'lonDaemons'};
 4187:     unlink("$execdir/logs/lond.pid");
 4188:     &status("Restarting self (HUP)");
 4189:     exec("$execdir/lond");         # here we go again
 4190: }
 4191: 
 4192: #
 4193: #    Kill off hashes that describe the host table prior to re-reading it.
 4194: #    Hashes affected are:
 4195: #       %hostid, %hostdom %hostip %hostdns.
 4196: #
 4197: sub KillHostHashes {
 4198:     foreach my $key (keys %hostid) {
 4199: 	delete $hostid{$key};
 4200:     }
 4201:     foreach my $key (keys %hostdom) {
 4202: 	delete $hostdom{$key};
 4203:     }
 4204:     foreach my $key (keys %hostip) {
 4205: 	delete $hostip{$key};
 4206:     }
 4207:     foreach my $key (keys %hostdns) {
 4208: 	delete $hostdns{$key};
 4209:     }
 4210: }
 4211: #
 4212: #   Read in the host table from file and distribute it into the various hashes:
 4213: #
 4214: #    - %hostid  -  Indexed by IP, the loncapa hostname.
 4215: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
 4216: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
 4217: sub ReadHostTable {
 4218: 
 4219:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
 4220:     my $myloncapaname = $perlvar{'lonHostID'};
 4221:     Debug("My loncapa name is : $myloncapaname");
 4222:     while (my $configline=<CONFIG>) {
 4223: 	if (!($configline =~ /^\s*\#/)) {
 4224: 	    my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
 4225: 	    chomp($ip); $ip=~s/\D+$//;
 4226: 	    $hostid{$ip}=$id;         # LonCAPA name of host by IP.
 4227: 	    $hostdom{$id}=$domain;    # LonCAPA domain name of host. 
 4228: 	    $hostip{$id}=$ip;	      # IP address of host.
 4229: 	    $hostdns{$name} = $id;    # LonCAPA name of host by DNS.
 4230: 
 4231: 	    if ($id eq $perlvar{'lonHostID'}) { 
 4232: 		Debug("Found me in the host table: $name");
 4233: 		$thisserver=$name; 
 4234: 	    }
 4235: 	}
 4236:     }
 4237:     close(CONFIG);
 4238: }
 4239: #
 4240: #  Reload the Apache daemon's state.
 4241: #  This is done by invoking /home/httpd/perl/apachereload
 4242: #  a setuid perl script that can be root for us to do this job.
 4243: #
 4244: sub ReloadApache {
 4245:     my $execdir = $perlvar{'lonDaemons'};
 4246:     my $script  = $execdir."/apachereload";
 4247:     system($script);
 4248: }
 4249: 
 4250: #
 4251: #   Called in response to a USR2 signal.
 4252: #   - Reread hosts.tab
 4253: #   - All children connected to hosts that were removed from hosts.tab
 4254: #     are killed via SIGINT
 4255: #   - All children connected to previously existing hosts are sent SIGUSR1
 4256: #   - Our internal hosts hash is updated to reflect the new contents of
 4257: #     hosts.tab causing connections from hosts added to hosts.tab to
 4258: #     now be honored.
 4259: #
 4260: sub UpdateHosts {
 4261:     &status("Reload hosts.tab");
 4262:     logthis('<font color="blue"> Updating connections </font>');
 4263:     #
 4264:     #  The %children hash has the set of IP's we currently have children
 4265:     #  on.  These need to be matched against records in the hosts.tab
 4266:     #  Any ip's no longer in the table get killed off they correspond to
 4267:     #  either dropped or changed hosts.  Note that the re-read of the table
 4268:     #  will take care of new and changed hosts as connections come into being.
 4269: 
 4270: 
 4271:     KillHostHashes;
 4272:     ReadHostTable;
 4273: 
 4274:     foreach my $child (keys %children) {
 4275: 	my $childip = $children{$child};
 4276: 	if(!$hostid{$childip}) {
 4277: 	    logthis('<font color="blue"> UpdateHosts killing child '
 4278: 		    ." $child for ip $childip </font>");
 4279: 	    kill('INT', $child);
 4280: 	} else {
 4281: 	    logthis('<font color="green"> keeping child for ip '
 4282: 		    ." $childip (pid=$child) </font>");
 4283: 	}
 4284:     }
 4285:     ReloadApache;
 4286:     &status("Finished reloading hosts.tab");
 4287: }
 4288: 
 4289: 
 4290: sub checkchildren {
 4291:     &status("Checking on the children (sending signals)");
 4292:     &initnewstatus();
 4293:     &logstatus();
 4294:     &logthis('Going to check on the children');
 4295:     my $docdir=$perlvar{'lonDocRoot'};
 4296:     foreach (sort keys %children) {
 4297: 	#sleep 1;
 4298:         unless (kill 'USR1' => $_) {
 4299: 	    &logthis ('Child '.$_.' is dead');
 4300:             &logstatus($$.' is dead');
 4301: 	    delete($children{$_});
 4302:         } 
 4303:     }
 4304:     sleep 5;
 4305:     $SIG{ALRM} = sub { Debug("timeout"); 
 4306: 		       die "timeout";  };
 4307:     $SIG{__DIE__} = 'DEFAULT';
 4308:     &status("Checking on the children (waiting for reports)");
 4309:     foreach (sort keys %children) {
 4310:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
 4311:           eval {
 4312:             alarm(300);
 4313: 	    &logthis('Child '.$_.' did not respond');
 4314: 	    kill 9 => $_;
 4315: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
 4316: 	    #$subj="LON: $currenthostid killed lond process $_";
 4317: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
 4318: 	    #$execdir=$perlvar{'lonDaemons'};
 4319: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
 4320: 	    delete($children{$_});
 4321: 	    alarm(0);
 4322: 	  }
 4323:         }
 4324:     }
 4325:     $SIG{ALRM} = 'DEFAULT';
 4326:     $SIG{__DIE__} = \&catchexception;
 4327:     &status("Finished checking children");
 4328:     &logthis('Finished Checking children');
 4329: }
 4330: 
 4331: # --------------------------------------------------------------------- Logging
 4332: 
 4333: sub logthis {
 4334:     my $message=shift;
 4335:     my $execdir=$perlvar{'lonDaemons'};
 4336:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
 4337:     my $now=time;
 4338:     my $local=localtime($now);
 4339:     $lastlog=$local.': '.$message;
 4340:     print $fh "$local ($$): $message\n";
 4341: }
 4342: 
 4343: # ------------------------- Conditional log if $DEBUG true.
 4344: sub Debug {
 4345:     my $message = shift;
 4346:     if($DEBUG) {
 4347: 	&logthis($message);
 4348:     }
 4349: }
 4350: 
 4351: #
 4352: #   Sub to do replies to client.. this gives a hook for some
 4353: #   debug tracing too:
 4354: #  Parameters:
 4355: #     fd      - File open on client.
 4356: #     reply   - Text to send to client.
 4357: #     request - Original request from client.
 4358: #
 4359: sub Reply {
 4360:     my ($fd, $reply, $request) = @_;
 4361:     print $fd $reply;
 4362:     Debug("Request was $request  Reply was $reply");
 4363: 
 4364:     $Transactions++;
 4365: 
 4366: 
 4367: }
 4368: 
 4369: 
 4370: #
 4371: #    Sub to report a failure.
 4372: #    This function:
 4373: #     -   Increments the failure statistic counters.
 4374: #     -   Invokes Reply to send the error message to the client.
 4375: # Parameters:
 4376: #    fd       - File descriptor open on the client
 4377: #    reply    - Reply text to emit.
 4378: #    request  - The original request message (used by Reply
 4379: #               to debug if that's enabled.
 4380: # Implicit outputs:
 4381: #    $Failures- The number of failures is incremented.
 4382: #    Reply (invoked here) sends a message to the 
 4383: #    client:
 4384: #
 4385: sub Failure {
 4386:     my $fd      = shift;
 4387:     my $reply   = shift;
 4388:     my $request = shift;
 4389:    
 4390:     $Failures++;
 4391:     Reply($fd, $reply, $request);      # That's simple eh?
 4392: }
 4393: # ------------------------------------------------------------------ Log status
 4394: 
 4395: sub logstatus {
 4396:     &status("Doing logging");
 4397:     my $docdir=$perlvar{'lonDocRoot'};
 4398:     {
 4399: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
 4400:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
 4401:         $fh->close();
 4402:     }
 4403:     &status("Finished $$.txt");
 4404:     {
 4405: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
 4406: 	flock(LOG,LOCK_EX);
 4407: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
 4408: 	    .$status."\t".$lastlog."\t $keymode\n";
 4409: 	flock(DB,LOCK_UN);
 4410: 	close(LOG);
 4411:     }
 4412:     &status("Finished logging");
 4413: }
 4414: 
 4415: sub initnewstatus {
 4416:     my $docdir=$perlvar{'lonDocRoot'};
 4417:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
 4418:     my $now=time;
 4419:     my $local=localtime($now);
 4420:     print $fh "LOND status $local - parent $$\n\n";
 4421:     opendir(DIR,"$docdir/lon-status/londchld");
 4422:     while (my $filename=readdir(DIR)) {
 4423:         unlink("$docdir/lon-status/londchld/$filename");
 4424:     }
 4425:     closedir(DIR);
 4426: }
 4427: 
 4428: # -------------------------------------------------------------- Status setting
 4429: 
 4430: sub status {
 4431:     my $what=shift;
 4432:     my $now=time;
 4433:     my $local=localtime($now);
 4434:     $status=$local.': '.$what;
 4435:     $0='lond: '.$what.' '.$local;
 4436: }
 4437: 
 4438: # -------------------------------------------------------- Escape Special Chars
 4439: 
 4440: sub escape {
 4441:     my $str=shift;
 4442:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 4443:     return $str;
 4444: }
 4445: 
 4446: # ----------------------------------------------------- Un-Escape Special Chars
 4447: 
 4448: sub unescape {
 4449:     my $str=shift;
 4450:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 4451:     return $str;
 4452: }
 4453: 
 4454: # ----------------------------------------------------------- Send USR1 to lonc
 4455: 
 4456: sub reconlonc {
 4457:     my $peerfile=shift;
 4458:     &logthis("Trying to reconnect for $peerfile");
 4459:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
 4460:     if (my $fh=IO::File->new("$loncfile")) {
 4461: 	my $loncpid=<$fh>;
 4462:         chomp($loncpid);
 4463:         if (kill 0 => $loncpid) {
 4464: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
 4465:             kill USR1 => $loncpid;
 4466:         } else {
 4467: 	    &logthis(
 4468:               "<font color='red'>CRITICAL: "
 4469:              ."lonc at pid $loncpid not responding, giving up</font>");
 4470:         }
 4471:     } else {
 4472:       &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
 4473:     }
 4474: }
 4475: 
 4476: # -------------------------------------------------- Non-critical communication
 4477: 
 4478: sub subreply {
 4479:     my ($cmd,$server)=@_;
 4480:     my $peerfile="$perlvar{'lonSockDir'}/$server";
 4481:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 4482:                                       Type    => SOCK_STREAM,
 4483:                                       Timeout => 10)
 4484:        or return "con_lost";
 4485:     print $sclient "$cmd\n";
 4486:     my $answer=<$sclient>;
 4487:     chomp($answer);
 4488:     if (!$answer) { $answer="con_lost"; }
 4489:     return $answer;
 4490: }
 4491: 
 4492: sub reply {
 4493:   my ($cmd,$server)=@_;
 4494:   my $answer;
 4495:   if ($server ne $currenthostid) { 
 4496:     $answer=subreply($cmd,$server);
 4497:     if ($answer eq 'con_lost') {
 4498: 	$answer=subreply("ping",$server);
 4499:         if ($answer ne $server) {
 4500: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
 4501:            &reconlonc("$perlvar{'lonSockDir'}/$server");
 4502:         }
 4503:         $answer=subreply($cmd,$server);
 4504:     }
 4505:   } else {
 4506:     $answer='self_reply';
 4507:   } 
 4508:   return $answer;
 4509: }
 4510: 
 4511: # -------------------------------------------------------------- Talk to lonsql
 4512: 
 4513: sub sql_reply {
 4514:     my ($cmd)=@_;
 4515:     my $answer=&sub_sql_reply($cmd);
 4516:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
 4517:     return $answer;
 4518: }
 4519: 
 4520: sub sub_sql_reply {
 4521:     my ($cmd)=@_;
 4522:     my $unixsock="mysqlsock";
 4523:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
 4524:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
 4525:                                       Type    => SOCK_STREAM,
 4526:                                       Timeout => 10)
 4527:        or return "con_lost";
 4528:     print $sclient "$cmd\n";
 4529:     my $answer=<$sclient>;
 4530:     chomp($answer);
 4531:     if (!$answer) { $answer="con_lost"; }
 4532:     return $answer;
 4533: }
 4534: 
 4535: # -------------------------------------------- Return path to profile directory
 4536: 
 4537: sub propath {
 4538:     my ($udom,$uname)=@_;
 4539:     $udom=~s/\W//g;
 4540:     $uname=~s/\W//g;
 4541:     my $subdir=$uname.'__';
 4542:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 4543:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
 4544:     return $proname;
 4545: } 
 4546: 
 4547: # --------------------------------------- Is this the home server of an author?
 4548: 
 4549: sub ishome {
 4550:     my $author=shift;
 4551:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 4552:     my ($udom,$uname)=split(/\//,$author);
 4553:     my $proname=propath($udom,$uname);
 4554:     if (-e $proname) {
 4555: 	return 'owner';
 4556:     } else {
 4557:         return 'not_owner';
 4558:     }
 4559: }
 4560: 
 4561: # ======================================================= Continue main program
 4562: # ---------------------------------------------------- Fork once and dissociate
 4563: 
 4564: my $fpid=fork;
 4565: exit if $fpid;
 4566: die "Couldn't fork: $!" unless defined ($fpid);
 4567: 
 4568: POSIX::setsid() or die "Can't start new session: $!";
 4569: 
 4570: # ------------------------------------------------------- Write our PID on disk
 4571: 
 4572: my $execdir=$perlvar{'lonDaemons'};
 4573: open (PIDSAVE,">$execdir/logs/lond.pid");
 4574: print PIDSAVE "$$\n";
 4575: close(PIDSAVE);
 4576: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
 4577: &status('Starting');
 4578: 
 4579: 
 4580: 
 4581: # ----------------------------------------------------- Install signal handlers
 4582: 
 4583: 
 4584: $SIG{CHLD} = \&REAPER;
 4585: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 4586: $SIG{HUP}  = \&HUPSMAN;
 4587: $SIG{USR1} = \&checkchildren;
 4588: $SIG{USR2} = \&UpdateHosts;
 4589: 
 4590: #  Read the host hashes:
 4591: 
 4592: ReadHostTable;
 4593: 
 4594: # --------------------------------------------------------------
 4595: #   Accept connections.  When a connection comes in, it is validated
 4596: #   and if good, a child process is created to process transactions
 4597: #   along the connection.
 4598: 
 4599: while (1) {
 4600:     &status('Starting accept');
 4601:     $client = $server->accept() or next;
 4602:     &status('Accepted '.$client.' off to spawn');
 4603:     make_new_child($client);
 4604:     &status('Finished spawning');
 4605: }
 4606: 
 4607: sub make_new_child {
 4608:     my $pid;
 4609: #    my $cipher;     # Now global
 4610:     my $sigset;
 4611: 
 4612:     $client = shift;
 4613:     &status('Starting new child '.$client);
 4614:     &logthis('<font color="green"> Attempting to start child ('.$client.
 4615: 	     ")</font>");    
 4616:     # block signal for fork
 4617:     $sigset = POSIX::SigSet->new(SIGINT);
 4618:     sigprocmask(SIG_BLOCK, $sigset)
 4619:         or die "Can't block SIGINT for fork: $!\n";
 4620: 
 4621:     die "fork: $!" unless defined ($pid = fork);
 4622: 
 4623:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 4624: 	                               # connection liveness.
 4625: 
 4626:     #
 4627:     #  Figure out who we're talking to so we can record the peer in 
 4628:     #  the pid hash.
 4629:     #
 4630:     my $caller = getpeername($client);
 4631:     my ($port,$iaddr);
 4632:     if (defined($caller) && length($caller) > 0) {
 4633: 	($port,$iaddr)=unpack_sockaddr_in($caller);
 4634:     } else {
 4635: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
 4636:     }
 4637:     if (defined($iaddr)) {
 4638: 	$clientip  = inet_ntoa($iaddr);
 4639: 	Debug("Connected with $clientip");
 4640: 	$clientdns = gethostbyaddr($iaddr, AF_INET);
 4641: 	Debug("Connected with $clientdns by name");
 4642:     } else {
 4643: 	&logthis("Unable to determine clientip");
 4644: 	$clientip='Unavailable';
 4645:     }
 4646:     
 4647:     if ($pid) {
 4648:         # Parent records the child's birth and returns.
 4649:         sigprocmask(SIG_UNBLOCK, $sigset)
 4650:             or die "Can't unblock SIGINT for fork: $!\n";
 4651:         $children{$pid} = $clientip;
 4652:         &status('Started child '.$pid);
 4653:         return;
 4654:     } else {
 4655:         # Child can *not* return from this subroutine.
 4656:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 4657:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 4658:                                 #don't get intercepted
 4659:         $SIG{USR1}= \&logstatus;
 4660:         $SIG{ALRM}= \&timeout;
 4661:         $lastlog='Forked ';
 4662:         $status='Forked';
 4663: 
 4664:         # unblock signals
 4665:         sigprocmask(SIG_UNBLOCK, $sigset)
 4666:             or die "Can't unblock SIGINT for fork: $!\n";
 4667: 
 4668: #        my $tmpsnum=0;            # Now global
 4669: #---------------------------------------------------- kerberos 5 initialization
 4670:         &Authen::Krb5::init_context();
 4671:         &Authen::Krb5::init_ets();
 4672: 
 4673: 	&status('Accepted connection');
 4674: # =============================================================================
 4675:             # do something with the connection
 4676: # -----------------------------------------------------------------------------
 4677: 	# see if we know client and 'check' for spoof IP by ineffective challenge
 4678: 
 4679: 	ReadManagerTable;	# May also be a manager!!
 4680: 	
 4681: 	my $clientrec=($hostid{$clientip}     ne undef);
 4682: 	my $ismanager=($managers{$clientip}    ne undef);
 4683: 	$clientname  = "[unknonwn]";
 4684: 	if($clientrec) {	# Establish client type.
 4685: 	    $ConnectionType = "client";
 4686: 	    $clientname = $hostid{$clientip};
 4687: 	    if($ismanager) {
 4688: 		$ConnectionType = "both";
 4689: 	    }
 4690: 	} else {
 4691: 	    $ConnectionType = "manager";
 4692: 	    $clientname = $managers{$clientip};
 4693: 	}
 4694: 	my $clientok;
 4695: 
 4696: 	if ($clientrec || $ismanager) {
 4697: 	    &status("Waiting for init from $clientip $clientname");
 4698: 	    &logthis('<font color="yellow">INFO: Connection, '.
 4699: 		     $clientip.
 4700: 		  " ($clientname) connection type = $ConnectionType </font>" );
 4701: 	    &status("Connecting $clientip  ($clientname))"); 
 4702: 	    my $remotereq=<$client>;
 4703: 	    chomp($remotereq);
 4704: 	    Debug("Got init: $remotereq");
 4705: 	    my $inikeyword = split(/:/, $remotereq);
 4706: 	    if ($remotereq =~ /^init/) {
 4707: 		&sethost("sethost:$perlvar{'lonHostID'}");
 4708: 		#
 4709: 		#  If the remote is attempting a local init... give that a try:
 4710: 		#
 4711: 		my ($i, $inittype) = split(/:/, $remotereq);
 4712: 
 4713: 		# If the connection type is ssl, but I didn't get my
 4714: 		# certificate files yet, then I'll drop  back to 
 4715: 		# insecure (if allowed).
 4716: 		
 4717: 		if($inittype eq "ssl") {
 4718: 		    my ($ca, $cert) = lonssl::CertificateFile;
 4719: 		    my $kfile       = lonssl::KeyFile;
 4720: 		    if((!$ca)   || 
 4721: 		       (!$cert) || 
 4722: 		       (!$kfile)) {
 4723: 			$inittype = ""; # This forces insecure attempt.
 4724: 			&logthis("<font color=\"blue\"> Certificates not "
 4725: 				 ."installed -- trying insecure auth</font>");
 4726: 		    } else {	# SSL certificates are in place so
 4727: 		    }		# Leave the inittype alone.
 4728: 		}
 4729: 
 4730: 		if($inittype eq "local") {
 4731: 		    my $key = LocalConnection($client, $remotereq);
 4732: 		    if($key) {
 4733: 			Debug("Got local key $key");
 4734: 			$clientok     = 1;
 4735: 			my $cipherkey = pack("H32", $key);
 4736: 			$cipher       = new IDEA($cipherkey);
 4737: 			print $client "ok:local\n";
 4738: 			&logthis('<font color="green"'
 4739: 				 . "Successful local authentication </font>");
 4740: 			$keymode = "local"
 4741: 		    } else {
 4742: 			Debug("Failed to get local key");
 4743: 			$clientok = 0;
 4744: 			shutdown($client, 3);
 4745: 			close $client;
 4746: 		    }
 4747: 		} elsif ($inittype eq "ssl") {
 4748: 		    my $key = SSLConnection($client);
 4749: 		    if ($key) {
 4750: 			$clientok = 1;
 4751: 			my $cipherkey = pack("H32", $key);
 4752: 			$cipher       = new IDEA($cipherkey);
 4753: 			&logthis('<font color="green">'
 4754: 				 ."Successfull ssl authentication with $clientname </font>");
 4755: 			$keymode = "ssl";
 4756: 	     
 4757: 		    } else {
 4758: 			$clientok = 0;
 4759: 			close $client;
 4760: 		    }
 4761: 	   
 4762: 		} else {
 4763: 		    my $ok = InsecureConnection($client);
 4764: 		    if($ok) {
 4765: 			$clientok = 1;
 4766: 			&logthis('<font color="green">'
 4767: 				 ."Successful insecure authentication with $clientname </font>");
 4768: 			print $client "ok\n";
 4769: 			$keymode = "insecure";
 4770: 		    } else {
 4771: 			&logthis('<font color="yellow">'
 4772: 				  ."Attempted insecure connection disallowed </font>");
 4773: 			close $client;
 4774: 			$clientok = 0;
 4775: 			
 4776: 		    }
 4777: 		}
 4778: 	    } else {
 4779: 		&logthis(
 4780: 			 "<font color='blue'>WARNING: "
 4781: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 4782: 		&status('No init '.$clientip);
 4783: 	    }
 4784: 	    
 4785: 	} else {
 4786: 	    &logthis(
 4787: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
 4788: 	    &status('Hung up on '.$clientip);
 4789: 	}
 4790:  
 4791: 	if ($clientok) {
 4792: # ---------------- New known client connecting, could mean machine online again
 4793: 	    
 4794: 	    foreach my $id (keys(%hostip)) {
 4795: 		if ($hostip{$id} ne $clientip ||
 4796: 		    $hostip{$currenthostid} eq $clientip) {
 4797: 		    # no need to try to do recon's to myself
 4798: 		    next;
 4799: 		}
 4800: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
 4801: 	    }
 4802: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
 4803: 	    &status('Will listen to '.$clientname);
 4804: # ------------------------------------------------------------ Process requests
 4805: 	    my $keep_going = 1;
 4806: 	    my $user_input;
 4807: 	    while(($user_input = get_request) && $keep_going) {
 4808: 		alarm(120);
 4809: 		Debug("Main: Got $user_input\n");
 4810: 		$keep_going = &process_request($user_input);
 4811: 		alarm(0);
 4812: 		&status('Listening to '.$clientname." ($keymode)");	   
 4813: 	    }
 4814: 
 4815: # --------------------------------------------- client unknown or fishy, refuse
 4816: 	}  else {
 4817: 	    print $client "refused\n";
 4818: 	    $client->close();
 4819: 	    &logthis("<font color='blue'>WARNING: "
 4820: 		     ."Rejected client $clientip, closing connection</font>");
 4821: 	}
 4822:     }            
 4823:     
 4824: # =============================================================================
 4825:     
 4826:     &logthis("<font color='red'>CRITICAL: "
 4827: 	     ."Disconnect from $clientip ($clientname)</font>");    
 4828:     
 4829:     
 4830:     # this exit is VERY important, otherwise the child will become
 4831:     # a producer of more and more children, forking yourself into
 4832:     # process death.
 4833:     exit;
 4834:     
 4835: }
 4836: 
 4837: 
 4838: #
 4839: #   Checks to see if the input roleput request was to set
 4840: # an author role.  If so, invokes the lchtmldir script to set
 4841: # up a correct public_html 
 4842: # Parameters:
 4843: #    request   - The request sent to the rolesput subchunk.
 4844: #                We're looking for  /domain/_au
 4845: #    domain    - The domain in which the user is having roles doctored.
 4846: #    user      - Name of the user for which the role is being put.
 4847: #    authtype  - The authentication type associated with the user.
 4848: #
 4849: sub manage_permissions
 4850: {
 4851: 
 4852:     my ($request, $domain, $user, $authtype) = @_;
 4853: 
 4854:     # See if the request is of the form /$domain/_au
 4855:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
 4856: 	my $execdir = $perlvar{'lonDaemons'};
 4857: 	my $userhome= "/home/$user" ;
 4858: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
 4859: 	system("$execdir/lchtmldir $userhome $user $authtype");
 4860:     }
 4861: }
 4862: 
 4863: 
 4864: #
 4865: #  Return the full path of a user password file, whether it exists or not.
 4866: # Parameters:
 4867: #   domain     - Domain in which the password file lives.
 4868: #   user       - name of the user.
 4869: # Returns:
 4870: #    Full passwd path:
 4871: #
 4872: sub password_path {
 4873:     my ($domain, $user) = @_;
 4874: 
 4875: 
 4876:     my $path   = &propath($domain, $user);
 4877:     $path  .= "/passwd";
 4878: 
 4879:     return $path;
 4880: }
 4881: 
 4882: #   Password Filename
 4883: #   Returns the path to a passwd file given domain and user... only if
 4884: #  it exists.
 4885: # Parameters:
 4886: #   domain    - Domain in which to search.
 4887: #   user      - username.
 4888: # Returns:
 4889: #   - If the password file exists returns its path.
 4890: #   - If the password file does not exist, returns undefined.
 4891: #
 4892: sub password_filename {
 4893:     my ($domain, $user) = @_;
 4894: 
 4895:     Debug ("PasswordFilename called: dom = $domain user = $user");
 4896: 
 4897:     my $path  = &password_path($domain, $user);
 4898:     Debug("PasswordFilename got path: $path");
 4899:     if(-e $path) {
 4900: 	return $path;
 4901:     } else {
 4902: 	return undef;
 4903:     }
 4904: }
 4905: 
 4906: #
 4907: #   Rewrite the contents of the user's passwd file.
 4908: #  Parameters:
 4909: #    domain    - domain of the user.
 4910: #    name      - User's name.
 4911: #    contents  - New contents of the file.
 4912: # Returns:
 4913: #   0    - Failed.
 4914: #   1    - Success.
 4915: #
 4916: sub rewrite_password_file {
 4917:     my ($domain, $user, $contents) = @_;
 4918: 
 4919:     my $file = &password_filename($domain, $user);
 4920:     if (defined $file) {
 4921: 	my $pf = IO::File->new(">$file");
 4922: 	if($pf) {
 4923: 	    print $pf "$contents\n";
 4924: 	    return 1;
 4925: 	} else {
 4926: 	    return 0;
 4927: 	}
 4928:     } else {
 4929: 	return 0;
 4930:     }
 4931: 
 4932: }
 4933: 
 4934: #
 4935: #   get_auth_type - Determines the authorization type of a user in a domain.
 4936: 
 4937: #     Returns the authorization type or nouser if there is no such user.
 4938: #
 4939: sub get_auth_type 
 4940: {
 4941: 
 4942:     my ($domain, $user)  = @_;
 4943: 
 4944:     Debug("get_auth_type( $domain, $user ) \n");
 4945:     my $proname    = &propath($domain, $user); 
 4946:     my $passwdfile = "$proname/passwd";
 4947:     if( -e $passwdfile ) {
 4948: 	my $pf = IO::File->new($passwdfile);
 4949: 	my $realpassword = <$pf>;
 4950: 	chomp($realpassword);
 4951: 	Debug("Password info = $realpassword\n");
 4952: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 4953: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 4954: 	my $availinfo = '';
 4955: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
 4956: 	    $availinfo = $contentpwd;
 4957: 	}
 4958: 
 4959: 	return "$authtype:$availinfo";
 4960:     } else {
 4961: 	Debug("Returning nouser");
 4962: 	return "nouser";
 4963:     }
 4964: }
 4965: 
 4966: #
 4967: #  Validate a user given their domain, name and password.  This utility
 4968: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
 4969: #  to validate the login credentials of a user.
 4970: # Parameters:
 4971: #    $domain    - The domain being logged into (this is required due to
 4972: #                 the capability for multihomed systems.
 4973: #    $user      - The name of the user being validated.
 4974: #    $password  - The user's propoposed password.
 4975: #
 4976: # Returns:
 4977: #     1        - The domain,user,pasword triplet corresponds to a valid
 4978: #                user.
 4979: #     0        - The domain,user,password triplet is not a valid user.
 4980: #
 4981: sub validate_user {
 4982:     my ($domain, $user, $password) = @_;
 4983: 
 4984: 
 4985:     # Why negative ~pi you may well ask?  Well this function is about
 4986:     # authentication, and therefore very important to get right.
 4987:     # I've initialized the flag that determines whether or not I've 
 4988:     # validated correctly to a value it's not supposed to get.
 4989:     # At the end of this function. I'll ensure that it's not still that
 4990:     # value so we don't just wind up returning some accidental value
 4991:     # as a result of executing an unforseen code path that
 4992:     # did not set $validated.
 4993: 
 4994:     my $validated = -3.14159;
 4995: 
 4996:     #  How we authenticate is determined by the type of authentication
 4997:     #  the user has been assigned.  If the authentication type is
 4998:     #  "nouser", the user does not exist so we will return 0.
 4999: 
 5000:     my $contents = &get_auth_type($domain, $user);
 5001:     my ($howpwd, $contentpwd) = split(/:/, $contents);
 5002: 
 5003:     my $null = pack("C",0);	# Used by kerberos auth types.
 5004: 
 5005:     if ($howpwd ne 'nouser') {
 5006: 
 5007: 	if($howpwd eq "internal") { # Encrypted is in local password file.
 5008: 	    $validated = (crypt($password, $contentpwd) eq $contentpwd);
 5009: 	}
 5010: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
 5011: 	    $contentpwd = (getpwnam($user))[1];
 5012: 	    if($contentpwd) {
 5013: 		if($contentpwd eq 'x') { # Shadow password file...
 5014: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
 5015: 		    open PWAUTH,  "|$pwauth_path" or
 5016: 			die "Cannot invoke authentication";
 5017: 		    print PWAUTH "$user\n$password\n";
 5018: 		    close PWAUTH;
 5019: 		    $validated = ! $?;
 5020: 
 5021: 		} else { 	         # Passwords in /etc/passwd. 
 5022: 		    $validated = (crypt($password,
 5023: 					$contentpwd) eq $contentpwd);
 5024: 		}
 5025: 	    } else {
 5026: 		$validated = 0;
 5027: 	    }
 5028: 	}
 5029: 	elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
 5030: 	    if(! ($password =~ /$null/) ) {
 5031: 		my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
 5032: 							   "",
 5033: 							   $contentpwd,,
 5034: 							   'krbtgt',
 5035: 							   $contentpwd,
 5036: 							   1,
 5037: 							   $password);
 5038: 		if(!$k4error) {
 5039: 		    $validated = 1;
 5040: 		} else {
 5041: 		    $validated = 0;
 5042: 		    &logthis('krb4: '.$user.', '.$contentpwd.', '.
 5043: 			     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 5044: 		}
 5045: 	    } else {
 5046: 		$validated = 0; # Password has a match with null.
 5047: 	    }
 5048: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
 5049: 	    if(!($password =~ /$null/)) { # Null password not allowed.
 5050: 		my $krbclient = &Authen::Krb5::parse_name($user.'@'
 5051: 							  .$contentpwd);
 5052: 		my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
 5053: 		my $krbserver  = &Authen::Krb5::parse_name($krbservice);
 5054: 		my $credentials= &Authen::Krb5::cc_default();
 5055: 		$credentials->initialize($krbclient);
 5056: 		my $krbreturn  = &Authen::KRb5::get_in_tkt_with_password($krbclient,
 5057: 									 $krbserver,
 5058: 									 $password,
 5059: 									 $credentials);
 5060: 		$validated = ($krbreturn == 1);
 5061: 	    } else {
 5062: 		$validated = 0;
 5063: 	    }
 5064: 	} elsif ($howpwd eq "localauth") { 
 5065: 	    #  Authenticate via installation specific authentcation method:
 5066: 	    $validated = &localauth::localauth($user, 
 5067: 					       $password, 
 5068: 					       $contentpwd);
 5069: 	} else {			# Unrecognized auth is also bad.
 5070: 	    $validated = 0;
 5071: 	}
 5072:     } else {
 5073: 	$validated = 0;
 5074:     }
 5075:     #
 5076:     #  $validated has the correct stat of the authentication:
 5077:     #
 5078: 
 5079:     unless ($validated != -3.14159) {
 5080: 	die "ValidateUser - failed to set the value of validated";
 5081:     }
 5082:     return $validated;
 5083: }
 5084: 
 5085: 
 5086: sub addline {
 5087:     my ($fname,$hostid,$ip,$newline)=@_;
 5088:     my $contents;
 5089:     my $found=0;
 5090:     my $expr='^'.$hostid.':'.$ip.':';
 5091:     $expr =~ s/\./\\\./g;
 5092:     my $sh;
 5093:     if ($sh=IO::File->new("$fname.subscription")) {
 5094: 	while (my $subline=<$sh>) {
 5095: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 5096: 	}
 5097: 	$sh->close();
 5098:     }
 5099:     $sh=IO::File->new(">$fname.subscription");
 5100:     if ($contents) { print $sh $contents; }
 5101:     if ($newline) { print $sh $newline; }
 5102:     $sh->close();
 5103:     return $found;
 5104: }
 5105: 
 5106: sub get_chat {
 5107:     my ($cdom,$cname,$udom,$uname)=@_;
 5108:     my %hash;
 5109:     my $proname=&propath($cdom,$cname);
 5110:     my @entries=();
 5111:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 5112: 	    &GDBM_READER(),0640)) {
 5113: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 5114: 	untie %hash;
 5115:     }
 5116:     my @participants=();
 5117:     my $cutoff=time-60;
 5118:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
 5119: 	    &GDBM_WRCREAT(),0640)) {
 5120:         $hash{$uname.':'.$udom}=time;
 5121:         foreach (sort keys %hash) {
 5122: 	    if ($hash{$_}>$cutoff) {
 5123: 		$participants[$#participants+1]='active_participant:'.$_;
 5124:             }
 5125:         }
 5126:         untie %hash;
 5127:     }
 5128:     return (@participants,@entries);
 5129: }
 5130: 
 5131: sub chat_add {
 5132:     my ($cdom,$cname,$newchat)=@_;
 5133:     my %hash;
 5134:     my $proname=&propath($cdom,$cname);
 5135:     my @entries=();
 5136:     my $time=time;
 5137:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 5138: 	    &GDBM_WRCREAT(),0640)) {
 5139: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 5140: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 5141: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 5142: 	my $newid=$time.'_000000';
 5143: 	if ($thentime==$time) {
 5144: 	    $idnum=~s/^0+//;
 5145: 	    $idnum++;
 5146: 	    $idnum=substr('000000'.$idnum,-6,6);
 5147: 	    $newid=$time.'_'.$idnum;
 5148: 	}
 5149: 	$hash{$newid}=$newchat;
 5150: 	my $expired=$time-3600;
 5151: 	foreach (keys %hash) {
 5152: 	    my ($thistime)=($_=~/(\d+)\_/);
 5153: 	    if ($thistime<$expired) {
 5154: 		delete $hash{$_};
 5155: 	    }
 5156: 	}
 5157: 	untie %hash;
 5158:     }
 5159:     {
 5160: 	my $hfh;
 5161: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
 5162: 	    print $hfh "$time:".&unescape($newchat)."\n";
 5163: 	}
 5164:     }
 5165: }
 5166: 
 5167: sub unsub {
 5168:     my ($fname,$clientip)=@_;
 5169:     my $result;
 5170:     my $unsubs = 0;		# Number of successful unsubscribes:
 5171: 
 5172: 
 5173:     # An old way subscriptions were handled was to have a 
 5174:     # subscription marker file:
 5175: 
 5176:     Debug("Attempting unlink of $fname.$clientname");
 5177:     if (unlink("$fname.$clientname")) {
 5178: 	$unsubs++;		# Successful unsub via marker file.
 5179:     } 
 5180: 
 5181:     # The more modern way to do it is to have a subscription list
 5182:     # file:
 5183: 
 5184:     if (-e "$fname.subscription") {
 5185: 	my $found=&addline($fname,$clientname,$clientip,'');
 5186: 	if ($found) { 
 5187: 	    $unsubs++;
 5188: 	}
 5189:     } 
 5190: 
 5191:     #  If either or both of these mechanisms succeeded in unsubscribing a 
 5192:     #  resource we can return ok:
 5193: 
 5194:     if($unsubs) {
 5195: 	$result = "ok\n";
 5196:     } else {
 5197: 	$result = "not_subscribed\n";
 5198:     }
 5199: 
 5200:     return $result;
 5201: }
 5202: 
 5203: sub currentversion {
 5204:     my $fname=shift;
 5205:     my $version=-1;
 5206:     my $ulsdir='';
 5207:     if ($fname=~/^(.+)\/[^\/]+$/) {
 5208:        $ulsdir=$1;
 5209:     }
 5210:     my ($fnamere1,$fnamere2);
 5211:     # remove version if already specified
 5212:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 5213:     # get the bits that go before and after the version number
 5214:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 5215: 	$fnamere1=$1;
 5216: 	$fnamere2='.'.$2;
 5217:     }
 5218:     if (-e $fname) { $version=1; }
 5219:     if (-e $ulsdir) {
 5220: 	if(-d $ulsdir) {
 5221: 	    if (opendir(LSDIR,$ulsdir)) {
 5222: 		my $ulsfn;
 5223: 		while ($ulsfn=readdir(LSDIR)) {
 5224: # see if this is a regular file (ignore links produced earlier)
 5225: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 5226: 		    unless (-l $thisfile) {
 5227: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 5228: 			    if ($1>$version) { $version=$1; }
 5229: 			}
 5230: 		    }
 5231: 		}
 5232: 		closedir(LSDIR);
 5233: 		$version++;
 5234: 	    }
 5235: 	}
 5236:     }
 5237:     return $version;
 5238: }
 5239: 
 5240: sub thisversion {
 5241:     my $fname=shift;
 5242:     my $version=-1;
 5243:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 5244: 	$version=$1;
 5245:     }
 5246:     return $version;
 5247: }
 5248: 
 5249: sub subscribe {
 5250:     my ($userinput,$clientip)=@_;
 5251:     my $result;
 5252:     my ($cmd,$fname)=split(/:/,$userinput);
 5253:     my $ownership=&ishome($fname);
 5254:     if ($ownership eq 'owner') {
 5255: # explitly asking for the current version?
 5256:         unless (-e $fname) {
 5257:             my $currentversion=&currentversion($fname);
 5258: 	    if (&thisversion($fname)==$currentversion) {
 5259:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 5260: 		    my $root=$1;
 5261:                     my $extension=$2;
 5262:                     symlink($root.'.'.$extension,
 5263:                             $root.'.'.$currentversion.'.'.$extension);
 5264:                     unless ($extension=~/\.meta$/) {
 5265:                        symlink($root.'.'.$extension.'.meta',
 5266:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 5267: 		    }
 5268:                 }
 5269:             }
 5270:         }
 5271: 	if (-e $fname) {
 5272: 	    if (-d $fname) {
 5273: 		$result="directory\n";
 5274: 	    } else {
 5275: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 5276: 		my $now=time;
 5277: 		my $found=&addline($fname,$clientname,$clientip,
 5278: 				   "$clientname:$clientip:$now\n");
 5279: 		if ($found) { $result="$fname\n"; }
 5280: 		# if they were subscribed to only meta data, delete that
 5281:                 # subscription, when you subscribe to a file you also get
 5282:                 # the metadata
 5283: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 5284: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 5285: 		$fname="http://$thisserver/".$fname;
 5286: 		$result="$fname\n";
 5287: 	    }
 5288: 	} else {
 5289: 	    $result="not_found\n";
 5290: 	}
 5291:     } else {
 5292: 	$result="rejected\n";
 5293:     }
 5294:     return $result;
 5295: }
 5296: 
 5297: sub make_passwd_file {
 5298:     my ($uname, $umode,$npass,$passfilename)=@_;
 5299:     my $result="ok\n";
 5300:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 5301: 	{
 5302: 	    my $pf = IO::File->new(">$passfilename");
 5303: 	    print $pf "$umode:$npass\n";
 5304: 	}
 5305:     } elsif ($umode eq 'internal') {
 5306: 	my $salt=time;
 5307: 	$salt=substr($salt,6,2);
 5308: 	my $ncpass=crypt($npass,$salt);
 5309: 	{
 5310: 	    &Debug("Creating internal auth");
 5311: 	    my $pf = IO::File->new(">$passfilename");
 5312: 	    print $pf "internal:$ncpass\n"; 
 5313: 	}
 5314:     } elsif ($umode eq 'localauth') {
 5315: 	{
 5316: 	    my $pf = IO::File->new(">$passfilename");
 5317: 	    print $pf "localauth:$npass\n";
 5318: 	}
 5319:     } elsif ($umode eq 'unix') {
 5320: 	{
 5321: 	    #
 5322: 	    #  Don't allow the creation of privileged accounts!!! that would
 5323: 	    #  be real bad!!!
 5324: 	    #
 5325: 	    my $uid = getpwnam($uname);
 5326: 	    if((defined $uid) && ($uid == 0)) {
 5327: 		&logthis(">>>Attempted to create privilged account blocked");
 5328: 		return "no_priv_account_error\n";
 5329: 	    }
 5330: 
 5331: 	    my $execpath       ="$perlvar{'lonDaemons'}/"."lcuseradd";
 5332: 
 5333: 	    my $lc_error_file  = $execdir."/tmp/lcuseradd".$$.".status";
 5334: 	    {
 5335: 		&Debug("Executing external: ".$execpath);
 5336: 		&Debug("user  = ".$uname.", Password =". $npass);
 5337: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
 5338: 		print $se "$uname\n";
 5339: 		print $se "$npass\n";
 5340: 		print $se "$npass\n";
 5341: 		print $se "$lc_error_file\n"; # Status -> unique file.
 5342: 	    }
 5343: 	    my $error = IO::File->new("< $lc_error_file");
 5344: 	    my $useraddok = <$error>;
 5345: 	    $error->close;
 5346: 	    unlink($lc_error_file);
 5347: 
 5348: 	    chomp $useraddok;
 5349: 
 5350: 	    if($useraddok > 0) {
 5351: 		my $error_text = &lcuseraddstrerror($useraddok);
 5352: 		&logthis("Failed lcuseradd: $error_text");
 5353: 		$result = "lcuseradd_failed:$error_text\n";
 5354: 	    }  else {
 5355: 		my $pf = IO::File->new(">$passfilename");
 5356: 		print $pf "unix:\n";
 5357: 	    }
 5358: 	}
 5359:     } elsif ($umode eq 'none') {
 5360: 	{
 5361: 	    my $pf = IO::File->new("> $passfilename");
 5362: 	    print $pf "none:\n";
 5363: 	}
 5364:     } else {
 5365: 	$result="auth_mode_error\n";
 5366:     }
 5367:     return $result;
 5368: }
 5369: 
 5370: sub sethost {
 5371:     my ($remotereq) = @_;
 5372:     my (undef,$hostid)=split(/:/,$remotereq);
 5373:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 5374:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
 5375: 	$currenthostid  =$hostid;
 5376: 	$currentdomainid=$hostdom{$hostid};
 5377: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 5378:     } else {
 5379: 	&logthis("Requested host id $hostid not an alias of ".
 5380: 		 $perlvar{'lonHostID'}." refusing connection");
 5381: 	return 'unable_to_set';
 5382:     }
 5383:     return 'ok';
 5384: }
 5385: 
 5386: sub version {
 5387:     my ($userinput)=@_;
 5388:     $remoteVERSION=(split(/:/,$userinput))[1];
 5389:     return "version:$VERSION";
 5390: }
 5391: 
 5392: #There is a copy of this in lonnet.pm
 5393: sub userload {
 5394:     my $numusers=0;
 5395:     {
 5396: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 5397: 	my $filename;
 5398: 	my $curtime=time;
 5399: 	while ($filename=readdir(LONIDS)) {
 5400: 	    if ($filename eq '.' || $filename eq '..') {next;}
 5401: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 5402: 	    if ($curtime-$mtime < 1800) { $numusers++; }
 5403: 	}
 5404: 	closedir(LONIDS);
 5405:     }
 5406:     my $userloadpercent=0;
 5407:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 5408:     if ($maxuserload) {
 5409: 	$userloadpercent=100*$numusers/$maxuserload;
 5410:     }
 5411:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 5412:     return $userloadpercent;
 5413: }
 5414: 
 5415: # Routines for serializing arrays and hashes (copies from lonnet)
 5416: 
 5417: sub array2str {
 5418:   my (@array) = @_;
 5419:   my $result=&arrayref2str(\@array);
 5420:   $result=~s/^__ARRAY_REF__//;
 5421:   $result=~s/__END_ARRAY_REF__$//;
 5422:   return $result;
 5423: }
 5424:                                                                                  
 5425: sub arrayref2str {
 5426:   my ($arrayref) = @_;
 5427:   my $result='__ARRAY_REF__';
 5428:   foreach my $elem (@$arrayref) {
 5429:     if(ref($elem) eq 'ARRAY') {
 5430:       $result.=&arrayref2str($elem).'&';
 5431:     } elsif(ref($elem) eq 'HASH') {
 5432:       $result.=&hashref2str($elem).'&';
 5433:     } elsif(ref($elem)) {
 5434:       #print("Got a ref of ".(ref($elem))." skipping.");
 5435:     } else {
 5436:       $result.=&escape($elem).'&';
 5437:     }
 5438:   }
 5439:   $result=~s/\&$//;
 5440:   $result .= '__END_ARRAY_REF__';
 5441:   return $result;
 5442: }
 5443:                                                                                  
 5444: sub hash2str {
 5445:   my (%hash) = @_;
 5446:   my $result=&hashref2str(\%hash);
 5447:   $result=~s/^__HASH_REF__//;
 5448:   $result=~s/__END_HASH_REF__$//;
 5449:   return $result;
 5450: }
 5451:                                                                                  
 5452: sub hashref2str {
 5453:   my ($hashref)=@_;
 5454:   my $result='__HASH_REF__';
 5455:   foreach (sort(keys(%$hashref))) {
 5456:     if (ref($_) eq 'ARRAY') {
 5457:       $result.=&arrayref2str($_).'=';
 5458:     } elsif (ref($_) eq 'HASH') {
 5459:       $result.=&hashref2str($_).'=';
 5460:     } elsif (ref($_)) {
 5461:       $result.='=';
 5462:       #print("Got a ref of ".(ref($_))." skipping.");
 5463:     } else {
 5464:         if ($_) {$result.=&escape($_).'=';} else { last; }
 5465:     }
 5466: 
 5467:     if(ref($hashref->{$_}) eq 'ARRAY') {
 5468:       $result.=&arrayref2str($hashref->{$_}).'&';
 5469:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 5470:       $result.=&hashref2str($hashref->{$_}).'&';
 5471:     } elsif(ref($hashref->{$_})) {
 5472:        $result.='&';
 5473:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 5474:     } else {
 5475:       $result.=&escape($hashref->{$_}).'&';
 5476:     }
 5477:   }
 5478:   $result=~s/\&$//;
 5479:   $result .= '__END_HASH_REF__';
 5480:   return $result;
 5481: }
 5482: 
 5483: # ----------------------------------- POD (plain old documentation, CPAN style)
 5484: 
 5485: =head1 NAME
 5486: 
 5487: lond - "LON Daemon" Server (port "LOND" 5663)
 5488: 
 5489: =head1 SYNOPSIS
 5490: 
 5491: Usage: B<lond>
 5492: 
 5493: Should only be run as user=www.  This is a command-line script which
 5494: is invoked by B<loncron>.  There is no expectation that a typical user
 5495: will manually start B<lond> from the command-line.  (In other words,
 5496: DO NOT START B<lond> YOURSELF.)
 5497: 
 5498: =head1 DESCRIPTION
 5499: 
 5500: There are two characteristics associated with the running of B<lond>,
 5501: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 5502: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 5503: subscriptions, etc).  These are described in two large
 5504: sections below.
 5505: 
 5506: B<PROCESS MANAGEMENT>
 5507: 
 5508: Preforker - server who forks first. Runs as a daemon. HUPs.
 5509: Uses IDEA encryption
 5510: 
 5511: B<lond> forks off children processes that correspond to the other servers
 5512: in the network.  Management of these processes can be done at the
 5513: parent process level or the child process level.
 5514: 
 5515: B<logs/lond.log> is the location of log messages.
 5516: 
 5517: The process management is now explained in terms of linux shell commands,
 5518: subroutines internal to this code, and signal assignments:
 5519: 
 5520: =over 4
 5521: 
 5522: =item *
 5523: 
 5524: PID is stored in B<logs/lond.pid>
 5525: 
 5526: This is the process id number of the parent B<lond> process.
 5527: 
 5528: =item *
 5529: 
 5530: SIGTERM and SIGINT
 5531: 
 5532: Parent signal assignment:
 5533:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 5534: 
 5535: Child signal assignment:
 5536:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 5537: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 5538:  to restart a new child.)
 5539: 
 5540: Command-line invocations:
 5541:  B<kill> B<-s> SIGTERM I<PID>
 5542:  B<kill> B<-s> SIGINT I<PID>
 5543: 
 5544: Subroutine B<HUNTSMAN>:
 5545:  This is only invoked for the B<lond> parent I<PID>.
 5546: This kills all the children, and then the parent.
 5547: The B<lonc.pid> file is cleared.
 5548: 
 5549: =item *
 5550: 
 5551: SIGHUP
 5552: 
 5553: Current bug:
 5554:  This signal can only be processed the first time
 5555: on the parent process.  Subsequent SIGHUP signals
 5556: have no effect.
 5557: 
 5558: Parent signal assignment:
 5559:  $SIG{HUP}  = \&HUPSMAN;
 5560: 
 5561: Child signal assignment:
 5562:  none (nothing happens)
 5563: 
 5564: Command-line invocations:
 5565:  B<kill> B<-s> SIGHUP I<PID>
 5566: 
 5567: Subroutine B<HUPSMAN>:
 5568:  This is only invoked for the B<lond> parent I<PID>,
 5569: This kills all the children, and then the parent.
 5570: The B<lond.pid> file is cleared.
 5571: 
 5572: =item *
 5573: 
 5574: SIGUSR1
 5575: 
 5576: Parent signal assignment:
 5577:  $SIG{USR1} = \&USRMAN;
 5578: 
 5579: Child signal assignment:
 5580:  $SIG{USR1}= \&logstatus;
 5581: 
 5582: Command-line invocations:
 5583:  B<kill> B<-s> SIGUSR1 I<PID>
 5584: 
 5585: Subroutine B<USRMAN>:
 5586:  When invoked for the B<lond> parent I<PID>,
 5587: SIGUSR1 is sent to all the children, and the status of
 5588: each connection is logged.
 5589: 
 5590: =item *
 5591: 
 5592: SIGUSR2
 5593: 
 5594: Parent Signal assignment:
 5595:     $SIG{USR2} = \&UpdateHosts
 5596: 
 5597: Child signal assignment:
 5598:     NONE
 5599: 
 5600: 
 5601: =item *
 5602: 
 5603: SIGCHLD
 5604: 
 5605: Parent signal assignment:
 5606:  $SIG{CHLD} = \&REAPER;
 5607: 
 5608: Child signal assignment:
 5609:  none
 5610: 
 5611: Command-line invocations:
 5612:  B<kill> B<-s> SIGCHLD I<PID>
 5613: 
 5614: Subroutine B<REAPER>:
 5615:  This is only invoked for the B<lond> parent I<PID>.
 5616: Information pertaining to the child is removed.
 5617: The socket port is cleaned up.
 5618: 
 5619: =back
 5620: 
 5621: B<SERVER-SIDE ACTIVITIES>
 5622: 
 5623: Server-side information can be accepted in an encrypted or non-encrypted
 5624: method.
 5625: 
 5626: =over 4
 5627: 
 5628: =item ping
 5629: 
 5630: Query a client in the hosts.tab table; "Are you there?"
 5631: 
 5632: =item pong
 5633: 
 5634: Respond to a ping query.
 5635: 
 5636: =item ekey
 5637: 
 5638: Read in encrypted key, make cipher.  Respond with a buildkey.
 5639: 
 5640: =item load
 5641: 
 5642: Respond with CPU load based on a computation upon /proc/loadavg.
 5643: 
 5644: =item currentauth
 5645: 
 5646: Reply with current authentication information (only over an
 5647: encrypted channel).
 5648: 
 5649: =item auth
 5650: 
 5651: Only over an encrypted channel, reply as to whether a user's
 5652: authentication information can be validated.
 5653: 
 5654: =item passwd
 5655: 
 5656: Allow for a password to be set.
 5657: 
 5658: =item makeuser
 5659: 
 5660: Make a user.
 5661: 
 5662: =item passwd
 5663: 
 5664: Allow for authentication mechanism and password to be changed.
 5665: 
 5666: =item home
 5667: 
 5668: Respond to a question "are you the home for a given user?"
 5669: 
 5670: =item update
 5671: 
 5672: Update contents of a subscribed resource.
 5673: 
 5674: =item unsubscribe
 5675: 
 5676: The server is unsubscribing from a resource.
 5677: 
 5678: =item subscribe
 5679: 
 5680: The server is subscribing to a resource.
 5681: 
 5682: =item log
 5683: 
 5684: Place in B<logs/lond.log>
 5685: 
 5686: =item put
 5687: 
 5688: stores hash in namespace
 5689: 
 5690: =item rolesputy
 5691: 
 5692: put a role into a user's environment
 5693: 
 5694: =item get
 5695: 
 5696: returns hash with keys from array
 5697: reference filled in from namespace
 5698: 
 5699: =item eget
 5700: 
 5701: returns hash with keys from array
 5702: reference filled in from namesp (encrypts the return communication)
 5703: 
 5704: =item rolesget
 5705: 
 5706: get a role from a user's environment
 5707: 
 5708: =item del
 5709: 
 5710: deletes keys out of array from namespace
 5711: 
 5712: =item keys
 5713: 
 5714: returns namespace keys
 5715: 
 5716: =item dump
 5717: 
 5718: dumps the complete (or key matching regexp) namespace into a hash
 5719: 
 5720: =item store
 5721: 
 5722: stores hash permanently
 5723: for this url; hashref needs to be given and should be a \%hashname; the
 5724: remaining args aren't required and if they aren't passed or are '' they will
 5725: be derived from the ENV
 5726: 
 5727: =item restore
 5728: 
 5729: returns a hash for a given url
 5730: 
 5731: =item querysend
 5732: 
 5733: Tells client about the lonsql process that has been launched in response
 5734: to a sent query.
 5735: 
 5736: =item queryreply
 5737: 
 5738: Accept information from lonsql and make appropriate storage in temporary
 5739: file space.
 5740: 
 5741: =item idput
 5742: 
 5743: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 5744: for each student, defined perhaps by the institutional Registrar.)
 5745: 
 5746: =item idget
 5747: 
 5748: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 5749: for each student, defined perhaps by the institutional Registrar.)
 5750: 
 5751: =item tmpput
 5752: 
 5753: Accept and store information in temporary space.
 5754: 
 5755: =item tmpget
 5756: 
 5757: Send along temporarily stored information.
 5758: 
 5759: =item ls
 5760: 
 5761: List part of a user's directory.
 5762: 
 5763: =item pushtable
 5764: 
 5765: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 5766: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 5767: must be restored manually in case of a problem with the new table file.
 5768: pushtable requires that the request be encrypted and validated via
 5769: ValidateManager.  The form of the command is:
 5770: enc:pushtable tablename <tablecontents> \n
 5771: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 5772: cleartext newline.
 5773: 
 5774: =item Hanging up (exit or init)
 5775: 
 5776: What to do when a client tells the server that they (the client)
 5777: are leaving the network.
 5778: 
 5779: =item unknown command
 5780: 
 5781: If B<lond> is sent an unknown command (not in the list above),
 5782: it replys to the client "unknown_cmd".
 5783: 
 5784: 
 5785: =item UNKNOWN CLIENT
 5786: 
 5787: If the anti-spoofing algorithm cannot verify the client,
 5788: the client is rejected (with a "refused" message sent
 5789: to the client, and the connection is closed.
 5790: 
 5791: =back
 5792: 
 5793: =head1 PREREQUISITES
 5794: 
 5795: IO::Socket
 5796: IO::File
 5797: Apache::File
 5798: Symbol
 5799: POSIX
 5800: Crypt::IDEA
 5801: LWP::UserAgent()
 5802: GDBM_File
 5803: Authen::Krb4
 5804: Authen::Krb5
 5805: 
 5806: =head1 COREQUISITES
 5807: 
 5808: =head1 OSNAMES
 5809: 
 5810: linux
 5811: 
 5812: =head1 SCRIPT CATEGORIES
 5813: 
 5814: Server/Process
 5815: 
 5816: =cut

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