File:  [LON-CAPA] / loncom / lond
Revision 1.161: download - view: text, annotated - select for diffs
Tue Nov 11 12:39:14 2003 UTC (20 years, 5 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Support manager/client distinction.  Connection distinction tested,
client functionality tested, still need to re-test management
functionality.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.161 2003/11/11 12:39:14 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 File::Copy;
   49: 
   50: my $DEBUG = 0;		       # Non zero to enable debug log entries.
   51: 
   52: my $status='';
   53: my $lastlog='';
   54: 
   55: my $VERSION='$Revision: 1.161 $'; #' stupid emacs
   56: my $remoteVERSION;
   57: my $currenthostid;
   58: my $currentdomainid;
   59: 
   60: my $client;
   61: my $clientip;
   62: my $clientname;
   63: 
   64: my $server;
   65: my $thisserver;
   66: 
   67: # 
   68: #   Connection type is:
   69: #      client                   - All client actions are allowed
   70: #      manager                  - only management functions allowed.
   71: #      both                     - Both management and client actions are allowed
   72: #
   73: 
   74: my $ConnectionType;
   75: 
   76: my %hostid;
   77: my %hostdom;
   78: my %hostip;
   79: 
   80: my %managers;			# Ip -> manager names
   81: 
   82: my %perlvar;			# Will have the apache conf defined perl vars.
   83: 
   84: #
   85: #  The array below are password error strings."
   86: #
   87: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
   88: my @passwderrors = ("ok",
   89: 		   "lcpasswd must be run as user 'www'",
   90: 		   "lcpasswd got incorrect number of arguments",
   91: 		   "lcpasswd did not get the right nubmer of input text lines",
   92: 		   "lcpasswd too many simultaneous pwd changes in progress",
   93: 		   "lcpasswd User does not exist.",
   94: 		   "lcpasswd Incorrect current passwd",
   95: 		   "lcpasswd Unable to su to root.",
   96: 		   "lcpasswd Cannot set new passwd.",
   97: 		   "lcpasswd Username has invalid characters",
   98: 		   "lcpasswd Invalid characters in password",
   99: 		    "11", "12",
  100: 		    "lcpasswd Password mismatch");
  101: 
  102: 
  103: #  The array below are lcuseradd error strings.:
  104: 
  105: my $lastadderror = 13;
  106: my @adderrors    = ("ok",
  107: 		    "User ID mismatch, lcuseradd must run as user www",
  108: 		    "lcuseradd Incorrect number of command line parameters must be 3",
  109: 		    "lcuseradd Incorrect number of stdinput lines, must be 3",
  110: 		    "lcuseradd Too many other simultaneous pwd changes in progress",
  111: 		    "lcuseradd User does not exist",
  112: 		    "lcuseradd Unable to make www member of users's group",
  113: 		    "lcuseradd Unable to su to root",
  114: 		    "lcuseradd Unable to set password",
  115: 		    "lcuseradd Usrname has invalid characters",
  116: 		    "lcuseradd Password has an invalid character",
  117: 		    "lcuseradd User already exists",
  118: 		    "lcuseradd Could not add user.",
  119: 		    "lcuseradd Password mismatch");
  120: 
  121: 
  122: #
  123: #   GetCertificate: Given a transaction that requires a certificate,
  124: #   this function will extract the certificate from the transaction
  125: #   request.  Note that at this point, the only concept of a certificate
  126: #   is the hostname to which we are connected.
  127: #
  128: #   Parameter:
  129: #      request   - The request sent by our client (this parameterization may
  130: #                  need to change when we really use a certificate granting
  131: #                  authority.
  132: #
  133: sub GetCertificate {
  134:     my $request = shift;
  135: 
  136:     return $clientip;
  137: }
  138: 
  139: #
  140: #   Return true if client is a manager.
  141: #
  142: sub isManager {
  143:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
  144: }
  145: #
  146: #   Return tru if client can do client functions
  147: #
  148: sub isClient {
  149:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
  150: }
  151: 
  152: 
  153: #
  154: #   ReadManagerTable: Reads in the current manager table. For now this is
  155: #                     done on each manager authentication because:
  156: #                     - These authentications are not frequent
  157: #                     - This allows dynamic changes to the manager table
  158: #                       without the need to signal to the lond.
  159: #
  160: 
  161: sub ReadManagerTable {
  162: 
  163:     #   Clean out the old table first..
  164: 
  165:     foreach my $key (keys %managers) {
  166: 	delete $managers{$key};
  167:     }
  168: 
  169:     my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
  170:     if (!open (MANAGERS, $tablename)) {
  171: 	logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
  172: 	return;
  173:     }
  174:     while(my $host = <MANAGERS>) {
  175: 	chomp($host);
  176: 	if (!defined $hostip{$host}) { # This is a non cluster member
  177: 
  178: 	    #  The entry is of the form:
  179: 	    #    cluname:hostname
  180: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
  181: 	    #            the host key.
  182: 	    #  hostname- The dns name of the host.
  183: 	    #
  184: 	    
  185: 	    my($cluname, $dnsname) = split(/:/, $host);
  186: 	    open(MGRPIPE, "/usr/bin/host $dnsname |") || die "Can't make host pipeline";
  187: 	    my $dnsinfo = <MGRPIPE>;
  188: 	    chomp $dnsinfo;
  189: 	    close MGRPIPE;
  190: 	    my($jname, $jhas, $jaddress, $hostip) = split(/ /, $dnsinfo);
  191: 	    $managers{$hostip} = $cluname;
  192: 	} else {
  193: 	    $managers{$hostip{$host}} = $host;  # Use info from cluster tab if clumemeber
  194: 	}
  195:     }
  196: }
  197: 
  198: #
  199: #  ValidManager: Determines if a given certificate represents a valid manager.
  200: #                in this primitive implementation, the 'certificate' is
  201: #                just the connecting loncapa client name.  This is checked
  202: #                against a valid client list in the configuration.
  203: #
  204: #                  
  205: sub ValidManager {
  206:     my $certificate = shift; 
  207: 
  208:     ReadManagerTable;
  209: 
  210:     my $hostname   = $hostid{$certificate};
  211: 
  212: 
  213:     if ($hostname ne undef) {
  214: 	if($managers{$hostname} ne undef) {
  215: 	    &logthis('<font color="yellow">Authenticating manager'.
  216: 		     " $hostname</font>");
  217: 	    return 1;
  218: 	} else {
  219: 	    &logthis('<font color="red" failed manager authentication '.
  220: 		     $hostname." is not a valid manager host</font>");
  221: 	    return 0;
  222: 	}
  223:     } else {
  224: 	&logthis('<font color="red"> Failed manager authentication '.
  225: 		 "$certificate </font>");
  226: 	return 0;
  227:     }
  228: }
  229: #
  230: #  CopyFile:  Called as part of the process of installing a 
  231: #             new configuration file.  This function copies an existing
  232: #             file to a backup file.
  233: # Parameters:
  234: #     oldfile  - Name of the file to backup.
  235: #     newfile  - Name of the backup file.
  236: # Return:
  237: #     0   - Failure (errno has failure reason).
  238: #     1   - Success.
  239: #
  240: sub CopyFile {
  241:     my $oldfile = shift;
  242:     my $newfile = shift;
  243: 
  244:     #  The file must exist:
  245: 
  246:     if(-e $oldfile) {
  247: 
  248: 	 # Read the old file.
  249: 
  250: 	my $oldfh = IO::File->new("< $oldfile");
  251: 	if(!$oldfh) {
  252: 	    return 0;
  253: 	}
  254: 	my @contents = <$oldfh>;  # Suck in the entire file.
  255: 
  256: 	# write the backup file:
  257: 
  258: 	my $newfh = IO::File->new("> $newfile");
  259: 	if(!(defined $newfh)){
  260: 	    return 0;
  261: 	}
  262: 	my $lines = scalar @contents;
  263: 	for (my $i =0; $i < $lines; $i++) {
  264: 	    print $newfh ($contents[$i]);
  265: 	}
  266: 
  267: 	$oldfh->close;
  268: 	$newfh->close;
  269: 
  270: 	chmod(0660, $newfile);
  271: 
  272: 	return 1;
  273: 	    
  274:     } else {
  275: 	return 0;
  276:     }
  277: }
  278: #
  279: #  Host files are passed out with externally visible host IPs.
  280: #  If, for example, we are behind a fire-wall or NAT host, our 
  281: #  internally visible IP may be different than the externally
  282: #  visible IP.  Therefore, we always adjust the contents of the
  283: #  host file so that the entry for ME is the IP that we believe
  284: #  we have.  At present, this is defined as the entry that
  285: #  DNS has for us.  If by some chance we are not able to get a
  286: #  DNS translation for us, then we assume that the host.tab file
  287: #  is correct.  
  288: #    BUGBUGBUG - in the future, we really should see if we can
  289: #       easily query the interface(s) instead.
  290: # Parameter(s):
  291: #     contents    - The contents of the host.tab to check.
  292: # Returns:
  293: #     newcontents - The adjusted contents.
  294: #
  295: #
  296: sub AdjustHostContents {
  297:     my $contents  = shift;
  298:     my $adjusted;
  299:     my $me        = $perlvar{'lonHostID'};
  300: 
  301:     foreach my $line (split(/\n/,$contents)) {
  302: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
  303: 	    chomp($line);
  304: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
  305: 	    if ($id eq $me) {
  306: 		open(PIPE, " /usr/bin/host $name |") || die "Cant' make host pipeline";
  307: 		my $hostinfo = <PIPE>;
  308: 		close PIPE;
  309: 		
  310: 		my ($hostname, $has, $address, $ipnew) = split(/ /,$hostinfo);
  311: 		&logthis('<font color="green">'.
  312: 			 "hostname = $hostname me = $me, name = $name   actual ip = $ipnew </font>");
  313: 		
  314: 		if ($hostname eq $name) { # Lookup succeeded..
  315: 		    &logthis('<font color="green"> look up ok <font>');
  316: 		    $ip = $ipnew;
  317: 		} else {
  318: 		    &logthis('<font color="green"> Lookup failed: '
  319: 			     .$hostname." ne $name </font>");
  320: 		}
  321: 		#  Reconstruct the host line and append to adjusted:
  322: 		
  323: 		my $newline = "$id:$domain:$role:$name:$ip";
  324: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
  325: 		    $newline .= ":$maxcon:$idleto:$mincon";
  326: 		}
  327: 		$adjusted .= $newline."\n";
  328: 		
  329: 	    } else {		# Not me, pass unmodified.
  330: 		$adjusted .= $line."\n";
  331: 	    }
  332: 	} else {                  # Blank or comment never re-written.
  333: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
  334: 	}
  335:     }
  336:     return $adjusted;
  337: }
  338: #
  339: #   InstallFile: Called to install an administrative file:
  340: #       - The file is created with <name>.tmp
  341: #       - The <name>.tmp file is then mv'd to <name>
  342: #   This lugubrious procedure is done to ensure that we are never without
  343: #   a valid, even if dated, version of the file regardless of who crashes
  344: #   and when the crash occurs.
  345: #
  346: #  Parameters:
  347: #       Name of the file
  348: #       File Contents.
  349: #  Return:
  350: #      nonzero - success.
  351: #      0       - failure and $! has an errno.
  352: #
  353: sub InstallFile {
  354:     my $Filename = shift;
  355:     my $Contents = shift;
  356:     my $TempFile = $Filename.".tmp";
  357: 
  358:     #  Open the file for write:
  359: 
  360:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
  361:     if(!(defined $fh)) {
  362: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
  363: 	return 0;
  364:     }
  365:     #  write the contents of the file:
  366: 
  367:     print $fh ($Contents); 
  368:     $fh->close;			# In case we ever have a filesystem w. locking
  369: 
  370:     chmod(0660, $TempFile);
  371: 
  372:     # Now we can move install the file in position.
  373:     
  374:     move($TempFile, $Filename);
  375: 
  376:     return 1;
  377: }
  378: 
  379: #
  380: #   PushFile:  Called to do an administrative push of a file.
  381: #              - Ensure the file being pushed is one we support.
  382: #              - Backup the old file to <filename.saved>
  383: #              - Separate the contents of the new file out from the
  384: #                rest of the request.
  385: #              - Write the new file.
  386: #  Parameter:
  387: #     Request - The entire user request.  This consists of a : separated
  388: #               string pushfile:tablename:contents.
  389: #     NOTE:  The contents may have :'s in it as well making things a bit
  390: #            more interesting... but not much.
  391: #  Returns:
  392: #     String to send to client ("ok" or "refused" if bad file).
  393: #
  394: sub PushFile {
  395:     my $request = shift;    
  396:     my ($command, $filename, $contents) = split(":", $request, 3);
  397:     
  398:     #  At this point in time, pushes for only the following tables are
  399:     #  supported:
  400:     #   hosts.tab  ($filename eq host).
  401:     #   domain.tab ($filename eq domain).
  402:     # Construct the destination filename or reject the request.
  403:     #
  404:     # lonManage is supposed to ensure this, however this session could be
  405:     # part of some elaborate spoof that managed somehow to authenticate.
  406:     #
  407: 
  408:     my $tablefile = $perlvar{'lonTabDir'}.'/'; # need to precede with dir.
  409:     if ($filename eq "host") {
  410: 	$tablefile .= "hosts.tab";
  411:     } elsif ($filename eq "domain") {
  412: 	$tablefile .= "domain.tab";
  413:     } else {
  414: 	return "refused";
  415:     }
  416:     #
  417:     # >copy< the old table to the backup table
  418:     #        don't rename in case system crashes/reboots etc. in the time
  419:     #        window between a rename and write.
  420:     #
  421:     my $backupfile = $tablefile;
  422:     $backupfile    =~ s/\.tab$/.old/;
  423:     if(!CopyFile($tablefile, $backupfile)) {
  424: 	&logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
  425: 	return "error:$!";
  426:     }
  427:     &logthis('<font color="green"> Pushfile: backed up '
  428: 	    .$tablefile." to $backupfile</font>");
  429:     
  430:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
  431:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
  432:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
  433:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
  434:     #  that possibilty.
  435: 
  436:     if($filename eq "host") {
  437: 	$contents = AdjustHostContents($contents);
  438:     }
  439: 
  440:     #  Install the new file:
  441: 
  442:     if(!InstallFile($tablefile, $contents)) {
  443: 	&logthis('<font color="red"> Pushfile: unable to install '
  444: 	 .$tablefile." $! </font>");
  445: 	return "error:$!";
  446:     }
  447:     else {
  448: 	&logthis('<font color="green"> Installed new '.$tablefile
  449: 		 ."</font>");
  450: 
  451:     }
  452: 
  453: 
  454:     #  Indicate success:
  455:  
  456:     return "ok";
  457: 
  458: }
  459: 
  460: #
  461: #  Called to re-init either lonc or lond.
  462: #
  463: #  Parameters:
  464: #    request   - The full request by the client.  This is of the form
  465: #                reinit:<process>  
  466: #                where <process> is allowed to be either of 
  467: #                lonc or lond
  468: #
  469: #  Returns:
  470: #     The string to be sent back to the client either:
  471: #   ok         - Everything worked just fine.
  472: #   error:why  - There was a failure and why describes the reason.
  473: #
  474: #
  475: sub ReinitProcess {
  476:     my $request = shift;
  477: 
  478: 
  479:     # separate the request (reinit) from the process identifier and
  480:     # validate it producing the name of the .pid file for the process.
  481:     #
  482:     #
  483:     my ($junk, $process) = split(":", $request);
  484:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
  485:     if($process eq 'lonc') {
  486: 	$processpidfile = $processpidfile."lonc.pid";
  487: 	if (!open(PIDFILE, "< $processpidfile")) {
  488: 	    return "error:Open failed for $processpidfile";
  489: 	}
  490: 	my $loncpid = <PIDFILE>;
  491: 	close(PIDFILE);
  492: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
  493: 		."</font>");
  494: 	kill("USR2", $loncpid);
  495:     } elsif ($process eq 'lond') {
  496: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
  497: 	&UpdateHosts;			# Lond is us!!
  498:     } else {
  499: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
  500: 		 ."</font>");
  501: 	return "error:Invalid process identifier $process";
  502:     }
  503:     return 'ok';
  504: }
  505: 
  506: #
  507: #  Convert an error return code from lcpasswd to a string value.
  508: #
  509: sub lcpasswdstrerror {
  510:     my $ErrorCode = shift;
  511:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
  512: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
  513:     } else {
  514: 	return $passwderrors[$ErrorCode];
  515:     }
  516: }
  517: 
  518: #
  519: # Convert an error return code from lcuseradd to a string value:
  520: #
  521: sub lcuseraddstrerror {
  522:     my $ErrorCode = shift;
  523:     if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
  524: 	return "lcuseradd - Unrecognized error code: ".$ErrorCode;
  525:     } else {
  526: 	return $adderrors[$ErrorCode];
  527:     }
  528: }
  529: 
  530: # grabs exception and records it to log before exiting
  531: sub catchexception {
  532:     my ($error)=@_;
  533:     $SIG{'QUIT'}='DEFAULT';
  534:     $SIG{__DIE__}='DEFAULT';
  535:     &logthis("<font color=red>CRITICAL: "
  536:      ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
  537:      ."a crash with this error msg->[$error]</font>");
  538:     &logthis('Famous last words: '.$status.' - '.$lastlog);
  539:     if ($client) { print $client "error: $error\n"; }
  540:     $server->close();
  541:     die($error);
  542: }
  543: 
  544: sub timeout {
  545:     &logthis("<font color=ref>CRITICAL: TIME OUT ".$$."</font>");
  546:     &catchexception('Timeout');
  547: }
  548: # -------------------------------- Set signal handlers to record abnormal exits
  549: 
  550: $SIG{'QUIT'}=\&catchexception;
  551: $SIG{__DIE__}=\&catchexception;
  552: 
  553: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
  554: &status("Read loncapa.conf and loncapa_apache.conf");
  555: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
  556: %perlvar=%{$perlvarref};
  557: undef $perlvarref;
  558: 
  559: # ----------------------------- Make sure this process is running from user=www
  560: my $wwwid=getpwnam('www');
  561: if ($wwwid!=$<) {
  562:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  563:    my $subj="LON: $currenthostid User ID mismatch";
  564:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
  565:  mailto $emailto -s '$subj' > /dev/null");
  566:    exit 1;
  567: }
  568: 
  569: # --------------------------------------------- Check if other instance running
  570: 
  571: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
  572: 
  573: if (-e $pidfile) {
  574:    my $lfh=IO::File->new("$pidfile");
  575:    my $pide=<$lfh>;
  576:    chomp($pide);
  577:    if (kill 0 => $pide) { die "already running"; }
  578: }
  579: 
  580: # ------------------------------------------------------------- Read hosts file
  581: 
  582: 
  583: 
  584: # establish SERVER socket, bind and listen.
  585: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
  586:                                 Type      => SOCK_STREAM,
  587:                                 Proto     => 'tcp',
  588:                                 Reuse     => 1,
  589:                                 Listen    => 10 )
  590:   or die "making socket: $@\n";
  591: 
  592: # --------------------------------------------------------- Do global variables
  593: 
  594: # global variables
  595: 
  596: my %children               = ();       # keys are current child process IDs
  597: my $children               = 0;        # current number of children
  598: 
  599: sub REAPER {                        # takes care of dead children
  600:     $SIG{CHLD} = \&REAPER;
  601:     my $pid = wait;
  602:     if (defined($children{$pid})) {
  603: 	&logthis("Child $pid died");
  604: 	$children --;
  605: 	delete $children{$pid};
  606:     } else {
  607: 	&logthis("Unknown Child $pid died");
  608:     }
  609: }
  610: 
  611: sub HUNTSMAN {                      # signal handler for SIGINT
  612:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  613:     kill 'INT' => keys %children;
  614:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
  615:     my $execdir=$perlvar{'lonDaemons'};
  616:     unlink("$execdir/logs/lond.pid");
  617:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
  618:     exit;                           # clean up with dignity
  619: }
  620: 
  621: sub HUPSMAN {                      # signal handler for SIGHUP
  622:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  623:     kill 'INT' => keys %children;
  624:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
  625:     &logthis("<font color=red>CRITICAL: Restarting</font>");
  626:     my $execdir=$perlvar{'lonDaemons'};
  627:     unlink("$execdir/logs/lond.pid");
  628:     exec("$execdir/lond");         # here we go again
  629: }
  630: 
  631: #
  632: #    Kill off hashes that describe the host table prior to re-reading it.
  633: #    Hashes affected are:
  634: #       %hostid, %hostdom %hostip
  635: #
  636: sub KillHostHashes {
  637:     foreach my $key (keys %hostid) {
  638: 	delete $hostid{$key};
  639:     }
  640:     foreach my $key (keys %hostdom) {
  641: 	delete $hostdom{$key};
  642:     }
  643:     foreach my $key (keys %hostip) {
  644: 	delete $hostip{$key};
  645:     }
  646: }
  647: #
  648: #   Read in the host table from file and distribute it into the various hashes:
  649: #
  650: #    - %hostid  -  Indexed by IP, the loncapa hostname.
  651: #    - %hostdom -  Indexed by  loncapa hostname, the domain.
  652: #    - %hostip  -  Indexed by hostid, the Ip address of the host.
  653: sub ReadHostTable {
  654: 
  655:     open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
  656:     
  657:     while (my $configline=<CONFIG>) {
  658: 	my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
  659: 	chomp($ip); $ip=~s/\D+$//;
  660: 	$hostid{$ip}=$id;
  661: 	$hostdom{$id}=$domain;
  662: 	$hostip{$id}=$ip;
  663: 	if ($id eq $perlvar{'lonHostID'}) { $thisserver=$name; }
  664:     }
  665:     close(CONFIG);
  666: }
  667: #
  668: #  Reload the Apache daemon's state.
  669: #  This is done by invoking /home/httpd/perl/apachereload
  670: #  a setuid perl script that can be root for us to do this job.
  671: #
  672: sub ReloadApache {
  673:     my $execdir = $perlvar{'lonDaemons'};
  674:     my $script  = $execdir."/apachereload";
  675:     system($script);
  676: }
  677: 
  678: #
  679: #   Called in response to a USR2 signal.
  680: #   - Reread hosts.tab
  681: #   - All children connected to hosts that were removed from hosts.tab
  682: #     are killed via SIGINT
  683: #   - All children connected to previously existing hosts are sent SIGUSR1
  684: #   - Our internal hosts hash is updated to reflect the new contents of
  685: #     hosts.tab causing connections from hosts added to hosts.tab to
  686: #     now be honored.
  687: #
  688: sub UpdateHosts {
  689:     logthis('<font color="blue"> Updating connections </font>');
  690:     #
  691:     #  The %children hash has the set of IP's we currently have children
  692:     #  on.  These need to be matched against records in the hosts.tab
  693:     #  Any ip's no longer in the table get killed off they correspond to
  694:     #  either dropped or changed hosts.  Note that the re-read of the table
  695:     #  will take care of new and changed hosts as connections come into being.
  696: 
  697: 
  698:     KillHostHashes;
  699:     ReadHostTable;
  700: 
  701:     foreach my $child (keys %children) {
  702: 	my $childip = $children{$child};
  703: 	if(!$hostid{$childip}) {
  704: 	    logthis('<font color="blue"> UpdateHosts killing child '
  705: 		    ." $child for ip $childip </font>");
  706: 	    kill('INT', $child);
  707: 	} else {
  708: 	    logthis('<font color="green"> keeping child for ip '
  709: 		    ." $childip (pid=$child) </font>");
  710: 	}
  711:     }
  712:     ReloadApache;
  713: }
  714: 
  715: 
  716: sub checkchildren {
  717:     &initnewstatus();
  718:     &logstatus();
  719:     &logthis('Going to check on the children');
  720:     my $docdir=$perlvar{'lonDocRoot'};
  721:     foreach (sort keys %children) {
  722: 	sleep 1;
  723:         unless (kill 'USR1' => $_) {
  724: 	    &logthis ('Child '.$_.' is dead');
  725:             &logstatus($$.' is dead');
  726:         } 
  727:     }
  728:     sleep 5;
  729:     $SIG{ALRM} = sub { die "timeout" };
  730:     $SIG{__DIE__} = 'DEFAULT';
  731:     foreach (sort keys %children) {
  732:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
  733:           eval {
  734:             alarm(300);
  735: 	    &logthis('Child '.$_.' did not respond');
  736: 	    kill 9 => $_;
  737: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  738: 	    #$subj="LON: $currenthostid killed lond process $_";
  739: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
  740: 	    #$execdir=$perlvar{'lonDaemons'};
  741: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
  742: 	    alarm(0);
  743: 	  }
  744:         }
  745:     }
  746:     $SIG{ALRM} = 'DEFAULT';
  747:     $SIG{__DIE__} = \&catchexception;
  748: }
  749: 
  750: # --------------------------------------------------------------------- Logging
  751: 
  752: sub logthis {
  753:     my $message=shift;
  754:     my $execdir=$perlvar{'lonDaemons'};
  755:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
  756:     my $now=time;
  757:     my $local=localtime($now);
  758:     $lastlog=$local.': '.$message;
  759:     print $fh "$local ($$): $message\n";
  760: }
  761: 
  762: # ------------------------- Conditional log if $DEBUG true.
  763: sub Debug {
  764:     my $message = shift;
  765:     if($DEBUG) {
  766: 	&logthis($message);
  767:     }
  768: }
  769: 
  770: #
  771: #   Sub to do replies to client.. this gives a hook for some
  772: #   debug tracing too:
  773: #  Parameters:
  774: #     fd      - File open on client.
  775: #     reply   - Text to send to client.
  776: #     request - Original request from client.
  777: #
  778: sub Reply {
  779:     my $fd      = shift;
  780:     my $reply   = shift;
  781:     my $request = shift;
  782: 
  783:     print $fd $reply;
  784:     Debug("Request was $request  Reply was $reply");
  785: 
  786: }
  787: # ------------------------------------------------------------------ Log status
  788: 
  789: sub logstatus {
  790:     my $docdir=$perlvar{'lonDocRoot'};
  791:     {
  792:     my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
  793:     print $fh $$."\t".$currenthostid."\t".$status."\t".$lastlog."\n";
  794:     $fh->close();
  795:     }
  796:     {
  797: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
  798:         print $fh $status."\n".$lastlog."\n".time;
  799:         $fh->close();
  800:     }
  801: }
  802: 
  803: sub initnewstatus {
  804:     my $docdir=$perlvar{'lonDocRoot'};
  805:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
  806:     my $now=time;
  807:     my $local=localtime($now);
  808:     print $fh "LOND status $local - parent $$\n\n";
  809:     opendir(DIR,"$docdir/lon-status/londchld");
  810:     while (my $filename=readdir(DIR)) {
  811:         unlink("$docdir/lon-status/londchld/$filename");
  812:     }
  813:     closedir(DIR);
  814: }
  815: 
  816: # -------------------------------------------------------------- Status setting
  817: 
  818: sub status {
  819:     my $what=shift;
  820:     my $now=time;
  821:     my $local=localtime($now);
  822:     $status=$local.': '.$what;
  823:     $0='lond: '.$what.' '.$local;
  824: }
  825: 
  826: # -------------------------------------------------------- Escape Special Chars
  827: 
  828: sub escape {
  829:     my $str=shift;
  830:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  831:     return $str;
  832: }
  833: 
  834: # ----------------------------------------------------- Un-Escape Special Chars
  835: 
  836: sub unescape {
  837:     my $str=shift;
  838:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  839:     return $str;
  840: }
  841: 
  842: # ----------------------------------------------------------- Send USR1 to lonc
  843: 
  844: sub reconlonc {
  845:     my $peerfile=shift;
  846:     &logthis("Trying to reconnect for $peerfile");
  847:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  848:     if (my $fh=IO::File->new("$loncfile")) {
  849: 	my $loncpid=<$fh>;
  850:         chomp($loncpid);
  851:         if (kill 0 => $loncpid) {
  852: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  853:             kill USR1 => $loncpid;
  854:         } else {
  855: 	    &logthis(
  856:               "<font color=red>CRITICAL: "
  857:              ."lonc at pid $loncpid not responding, giving up</font>");
  858:         }
  859:     } else {
  860:       &logthis('<font color=red>CRITICAL: lonc not running, giving up</font>');
  861:     }
  862: }
  863: 
  864: # -------------------------------------------------- Non-critical communication
  865: 
  866: sub subreply {
  867:     my ($cmd,$server)=@_;
  868:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  869:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  870:                                       Type    => SOCK_STREAM,
  871:                                       Timeout => 10)
  872:        or return "con_lost";
  873:     print $sclient "$cmd\n";
  874:     my $answer=<$sclient>;
  875:     chomp($answer);
  876:     if (!$answer) { $answer="con_lost"; }
  877:     return $answer;
  878: }
  879: 
  880: sub reply {
  881:   my ($cmd,$server)=@_;
  882:   my $answer;
  883:   if ($server ne $currenthostid) { 
  884:     $answer=subreply($cmd,$server);
  885:     if ($answer eq 'con_lost') {
  886: 	$answer=subreply("ping",$server);
  887:         if ($answer ne $server) {
  888: 	    &logthis("sub reply: answer != server answer is $answer, server is $server");
  889:            &reconlonc("$perlvar{'lonSockDir'}/$server");
  890:         }
  891:         $answer=subreply($cmd,$server);
  892:     }
  893:   } else {
  894:     $answer='self_reply';
  895:   } 
  896:   return $answer;
  897: }
  898: 
  899: # -------------------------------------------------------------- Talk to lonsql
  900: 
  901: sub sqlreply {
  902:     my ($cmd)=@_;
  903:     my $answer=subsqlreply($cmd);
  904:     if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
  905:     return $answer;
  906: }
  907: 
  908: sub subsqlreply {
  909:     my ($cmd)=@_;
  910:     my $unixsock="mysqlsock";
  911:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
  912:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  913:                                       Type    => SOCK_STREAM,
  914:                                       Timeout => 10)
  915:        or return "con_lost";
  916:     print $sclient "$cmd\n";
  917:     my $answer=<$sclient>;
  918:     chomp($answer);
  919:     if (!$answer) { $answer="con_lost"; }
  920:     return $answer;
  921: }
  922: 
  923: # -------------------------------------------- Return path to profile directory
  924: 
  925: sub propath {
  926:     my ($udom,$uname)=@_;
  927:     $udom=~s/\W//g;
  928:     $uname=~s/\W//g;
  929:     my $subdir=$uname.'__';
  930:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  931:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  932:     return $proname;
  933: } 
  934: 
  935: # --------------------------------------- Is this the home server of an author?
  936: 
  937: sub ishome {
  938:     my $author=shift;
  939:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  940:     my ($udom,$uname)=split(/\//,$author);
  941:     my $proname=propath($udom,$uname);
  942:     if (-e $proname) {
  943: 	return 'owner';
  944:     } else {
  945:         return 'not_owner';
  946:     }
  947: }
  948: 
  949: # ======================================================= Continue main program
  950: # ---------------------------------------------------- Fork once and dissociate
  951: 
  952: my $fpid=fork;
  953: exit if $fpid;
  954: die "Couldn't fork: $!" unless defined ($fpid);
  955: 
  956: POSIX::setsid() or die "Can't start new session: $!";
  957: 
  958: # ------------------------------------------------------- Write our PID on disk
  959: 
  960: my $execdir=$perlvar{'lonDaemons'};
  961: open (PIDSAVE,">$execdir/logs/lond.pid");
  962: print PIDSAVE "$$\n";
  963: close(PIDSAVE);
  964: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
  965: &status('Starting');
  966: 
  967: 
  968: 
  969: # ----------------------------------------------------- Install signal handlers
  970: 
  971: 
  972: $SIG{CHLD} = \&REAPER;
  973: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  974: $SIG{HUP}  = \&HUPSMAN;
  975: $SIG{USR1} = \&checkchildren;
  976: $SIG{USR2} = \&UpdateHosts;
  977: 
  978: #  Read the host hashes:
  979: 
  980: ReadHostTable;
  981: 
  982: # --------------------------------------------------------------
  983: #   Accept connections.  When a connection comes in, it is validated
  984: #   and if good, a child process is created to process transactions
  985: #   along the connection.
  986: 
  987: while (1) {
  988:     $client = $server->accept() or next;
  989:     make_new_child($client);
  990: }
  991: 
  992: sub make_new_child {
  993:     my $pid;
  994:     my $cipher;
  995:     my $sigset;
  996: 
  997:     $client = shift;
  998:     &logthis('<font color="green"> Attempting to start child ('.$client.
  999: 	     ")</font>");    
 1000:     # block signal for fork
 1001:     $sigset = POSIX::SigSet->new(SIGINT);
 1002:     sigprocmask(SIG_BLOCK, $sigset)
 1003:         or die "Can't block SIGINT for fork: $!\n";
 1004: 
 1005:     die "fork: $!" unless defined ($pid = fork);
 1006: 
 1007:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
 1008: 	                               # connection liveness.
 1009: 
 1010:     #
 1011:     #  Figure out who we're talking to so we can record the peer in 
 1012:     #  the pid hash.
 1013:     #
 1014:     my $caller = getpeername($client);
 1015:     my ($port,$iaddr)=unpack_sockaddr_in($caller);
 1016:     $clientip=inet_ntoa($iaddr);
 1017:     
 1018:     if ($pid) {
 1019:         # Parent records the child's birth and returns.
 1020:         sigprocmask(SIG_UNBLOCK, $sigset)
 1021:             or die "Can't unblock SIGINT for fork: $!\n";
 1022:         $children{$pid} = $clientip;
 1023:         $children++;
 1024:         &status('Started child '.$pid);
 1025:         return;
 1026:     } else {
 1027:         # Child can *not* return from this subroutine.
 1028:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
 1029:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
 1030:                                 #don't get intercepted
 1031:         $SIG{USR1}= \&logstatus;
 1032:         $SIG{ALRM}= \&timeout;
 1033:         $lastlog='Forked ';
 1034:         $status='Forked';
 1035: 
 1036:         # unblock signals
 1037:         sigprocmask(SIG_UNBLOCK, $sigset)
 1038:             or die "Can't unblock SIGINT for fork: $!\n";
 1039: 
 1040:         my $tmpsnum=0;
 1041: #---------------------------------------------------- kerberos 5 initialization
 1042:         &Authen::Krb5::init_context();
 1043:         &Authen::Krb5::init_ets();
 1044: 
 1045: 	&status('Accepted connection');
 1046: # =============================================================================
 1047:             # do something with the connection
 1048: # -----------------------------------------------------------------------------
 1049: 	# see if we know client and check for spoof IP by challenge
 1050: 
 1051: 	ReadManagerTable;	# May also be a manager!!
 1052: 	
 1053: 	my $clientrec=($hostid{$clientip}     ne undef);
 1054: 	my $ismanager=($managers{$clientip}    ne undef);
 1055: 	$clientname  = "[unknonwn]";
 1056: 	if($clientrec) {	# Establish client type.
 1057: 	    $ConnectionType = "client";
 1058: 	    $clientname = $hostid{$clientip};
 1059: 	    if($ismanager) {
 1060: 		$ConnectionType = "both";
 1061: 	    }
 1062: 	} else {
 1063: 	    $ConnectionType = "manager";
 1064: 	    $clientname = $managers{$clientip};
 1065: 	}
 1066: 	my $clientok;
 1067: 	if ($clientrec || $ismanager) {
 1068: 	    &status("Waiting for init from $clientip $clientname");
 1069: 	    &logthis('<font color="yellow">INFO: Connection, '.
 1070: 		     $clientip.
 1071: 		  " ($clientname) connection type = $ConnectionType </font>" );
 1072: 	    &status("Connecting $clientip  ($clientname))"); 
 1073: 	    my $remotereq=<$client>;
 1074: 	    $remotereq=~s/[^\w:]//g;
 1075: 	    if ($remotereq =~ /^init/) {
 1076: 		&sethost("sethost:$perlvar{'lonHostID'}");
 1077: 		my $challenge="$$".time;
 1078: 		print $client "$challenge\n";
 1079: 		&status(
 1080: 			"Waiting for challenge reply from $clientip ($clientname)"); 
 1081: 		$remotereq=<$client>;
 1082: 		$remotereq=~s/\W//g;
 1083: 		if ($challenge eq $remotereq) {
 1084: 		    $clientok=1;
 1085: 		    print $client "ok\n";
 1086: 		} else {
 1087: 		    &logthis(
 1088: 			     "<font color=blue>WARNING: $clientip did not reply challenge</font>");
 1089: 		    &status('No challenge reply '.$clientip);
 1090: 		}
 1091: 	    } else {
 1092: 		&logthis(
 1093: 			 "<font color=blue>WARNING: "
 1094: 			 ."$clientip failed to initialize: >$remotereq< </font>");
 1095: 		&status('No init '.$clientip);
 1096: 	    }
 1097: 	} else {
 1098: 	    &logthis(
 1099: 		     "<font color=blue>WARNING: Unknown client $clientip</font>");
 1100: 	    &status('Hung up on '.$clientip);
 1101: 	}
 1102: 	if ($clientok) {
 1103: # ---------------- New known client connecting, could mean machine online again
 1104: 	    
 1105: 	    foreach my $id (keys(%hostip)) {
 1106: 		if ($hostip{$id} ne $clientip ||
 1107: 		    $hostip{$currenthostid} eq $clientip) {
 1108: 		    # no need to try to do recon's to myself
 1109: 		    next;
 1110: 		}
 1111: 		&reconlonc("$perlvar{'lonSockDir'}/$id");
 1112: 	    }
 1113: 	    &logthis("<font color=green>Established connection: $clientname</font>");
 1114: 	    &status('Will listen to '.$clientname);
 1115: # ------------------------------------------------------------ Process requests
 1116: 	    while (my $userinput=<$client>) {
 1117:                 chomp($userinput);
 1118: 		Debug("Request = $userinput\n");
 1119:                 &status('Processing '.$clientname.': '.$userinput);
 1120:                 my $wasenc=0;
 1121:                 alarm(120);
 1122: # ------------------------------------------------------------ See if encrypted
 1123: 		if ($userinput =~ /^enc/) {
 1124: 		    if ($cipher) {
 1125: 			my ($cmd,$cmdlength,$encinput)=split(/:/,$userinput);
 1126: 			$userinput='';
 1127: 			for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
 1128: 			    $userinput.=
 1129: 				$cipher->decrypt(
 1130: 						 pack("H16",substr($encinput,$encidx,16))
 1131: 						 );
 1132: 			}
 1133: 			$userinput=substr($userinput,0,$cmdlength);
 1134: 			$wasenc=1;
 1135: 		    }
 1136: 		}
 1137: 		
 1138: # ------------------------------------------------------------- Normal commands
 1139: # ------------------------------------------------------------------------ ping
 1140: 		if ($userinput =~ /^ping/) {	# client only
 1141: 		    if(isClient) {
 1142: 			print $client "$currenthostid\n";
 1143: 		    } else {
 1144: 			Reply($client, "refused\n", $userinput);
 1145: 		    }
 1146: # ------------------------------------------------------------------------ pong
 1147: 		}elsif ($userinput =~ /^pong/) { # client only
 1148: 		    if(isClient) {
 1149: 			my $reply=&reply("ping",$clientname);
 1150: 			print $client "$currenthostid:$reply\n"; 
 1151: 		    } else {
 1152: 			Reply($client, "refused\n", $userinput);
 1153: 		    }
 1154: # ------------------------------------------------------------------------ ekey
 1155: 		} elsif ($userinput =~ /^ekey/) { # ok for both clients & mgrs
 1156: 		    my $buildkey=time.$$.int(rand 100000);
 1157: 		    $buildkey=~tr/1-6/A-F/;
 1158: 		    $buildkey=int(rand 100000).$buildkey.int(rand 100000);
 1159: 		    my $key=$currenthostid.$clientname;
 1160: 		    $key=~tr/a-z/A-Z/;
 1161: 		    $key=~tr/G-P/0-9/;
 1162: 		    $key=~tr/Q-Z/0-9/;
 1163: 		    $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
 1164: 		    $key=substr($key,0,32);
 1165: 		    my $cipherkey=pack("H32",$key);
 1166: 		    $cipher=new IDEA $cipherkey;
 1167: 		    print $client "$buildkey\n"; 
 1168: # ------------------------------------------------------------------------ load
 1169: 		} elsif ($userinput =~ /^load/) { # client only
 1170: 		    if (isClient) {
 1171: 			my $loadavg;
 1172: 			{
 1173: 			    my $loadfile=IO::File->new('/proc/loadavg');
 1174: 			    $loadavg=<$loadfile>;
 1175: 			}
 1176: 			$loadavg =~ s/\s.*//g;
 1177: 			my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
 1178: 			print $client "$loadpercent\n";
 1179: 		    } else {
 1180: 			Reply($client, "refused\n", $userinput);
 1181: 	       
 1182: 		    }
 1183: # -------------------------------------------------------------------- userload
 1184: 		} elsif ($userinput =~ /^userload/) { # client only
 1185: 		    if(isClient) {
 1186: 			my $userloadpercent=&userload();
 1187: 			print $client "$userloadpercent\n";
 1188: 		    } else {
 1189: 			Reply($client, "refused\n", $userinput);
 1190: 		     
 1191: 		    }
 1192: #
 1193: #        Transactions requiring encryption:
 1194: #
 1195: # ----------------------------------------------------------------- currentauth
 1196: 		} elsif ($userinput =~ /^currentauth/) {
 1197: 		    if (($wasenc==1)  && isClient) { # Encoded & client only.
 1198: 			my ($cmd,$udom,$uname)=split(/:/,$userinput);
 1199: 			my $result = GetAuthType($udom, $uname);
 1200: 			if($result eq "nouser") {
 1201: 			    print $client "unknown_user\n";
 1202: 			}
 1203: 			else {
 1204: 			    print $client "$result\n"
 1205: 			    }
 1206: 		    } else {
 1207: 			Reply($client, "refused\n", $userinput);
 1208: 			
 1209: 		    }
 1210: #--------------------------------------------------------------------- pushfile
 1211: 		} elsif($userinput =~ /^pushfile/) {	# encoded & manager.
 1212: 		    if(($wasenc == 1) && isManager) {
 1213: 			my $cert = GetCertificate($userinput);
 1214: 			if(ValidManager($cert)) {
 1215: 			    my $reply = PushFile($userinput);
 1216: 			    print $client "$reply\n";
 1217: 			} else {
 1218: 			    print $client "refused\n";
 1219: 			} 
 1220: 		    } else {
 1221: 			Reply($client, "refused\n", $userinput);
 1222: 			
 1223: 		    }
 1224: #--------------------------------------------------------------------- reinit
 1225: 		} elsif($userinput =~ /^reinit/) { # Encoded and manager
 1226: 		    if (($wasenc == 1) && isManager) {
 1227: 			my $cert = GetCertificate($userinput);
 1228: 			if(ValidManager($cert)) {
 1229: 			    chomp($userinput);
 1230: 			    my $reply = ReinitProcess($userinput);
 1231: 			    print $client  "$reply\n";
 1232: 			} else {
 1233: 			    print $client "refused\n";
 1234: 			}
 1235: 		    } else {
 1236: 			Reply($client, "refused\n", $userinput);
 1237: 
 1238: 
 1239: 		    }
 1240: # ------------------------------------------------------------------------ auth
 1241: 		} elsif ($userinput =~ /^auth/) { # Encoded and client only.
 1242: 		    if (($wasenc==1) && isClient) {
 1243: 			my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
 1244: 			chomp($upass);
 1245: 			$upass=unescape($upass);
 1246: 			my $proname=propath($udom,$uname);
 1247: 			my $passfilename="$proname/passwd";
 1248: 			if (-e $passfilename) {
 1249: 			    my $pf = IO::File->new($passfilename);
 1250: 			    my $realpasswd=<$pf>;
 1251: 			    chomp($realpasswd);
 1252: 			    my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 1253: 			    my $pwdcorrect=0;
 1254: 			    if ($howpwd eq 'internal') {
 1255: 				&Debug("Internal auth");
 1256: 				$pwdcorrect=
 1257: 				    (crypt($upass,$contentpwd) eq $contentpwd);
 1258: 			    } elsif ($howpwd eq 'unix') {
 1259: 				&Debug("Unix auth");
 1260: 				if((getpwnam($uname))[1] eq "") { #no such user!
 1261: 				    $pwdcorrect = 0;
 1262: 				} else {
 1263: 				    $contentpwd=(getpwnam($uname))[1];
 1264: 				    my $pwauth_path="/usr/local/sbin/pwauth";
 1265: 				    unless ($contentpwd eq 'x') {
 1266: 					$pwdcorrect=
 1267: 					    (crypt($upass,$contentpwd) eq 
 1268: 					     $contentpwd);
 1269: 				    }
 1270: 				    
 1271: 				    elsif (-e $pwauth_path) {
 1272: 					open PWAUTH, "|$pwauth_path" or
 1273: 					    die "Cannot invoke authentication";
 1274: 					print PWAUTH "$uname\n$upass\n";
 1275: 					close PWAUTH;
 1276: 					$pwdcorrect=!$?;
 1277: 				    }
 1278: 				}
 1279: 			    } elsif ($howpwd eq 'krb4') {
 1280: 				my $null=pack("C",0);
 1281: 				unless ($upass=~/$null/) {
 1282: 				    my $krb4_error = &Authen::Krb4::get_pw_in_tkt
 1283: 					($uname,"",$contentpwd,'krbtgt',
 1284: 					 $contentpwd,1,$upass);
 1285: 				    if (!$krb4_error) {
 1286: 					$pwdcorrect = 1;
 1287: 				    } else { 
 1288: 					$pwdcorrect=0; 
 1289: 					# log error if it is not a bad password
 1290: 					if ($krb4_error != 62) {
 1291: 					    &logthis('krb4:'.$uname.','.$contentpwd.','.
 1292: 						     &Authen::Krb4::get_err_txt($Authen::Krb4::error));
 1293: 					}
 1294: 				    }
 1295: 				}
 1296: 			    } elsif ($howpwd eq 'krb5') {
 1297: 				my $null=pack("C",0);
 1298: 				unless ($upass=~/$null/) {
 1299: 				    my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
 1300: 				    my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
 1301: 				    my $krbserver=&Authen::Krb5::parse_name($krbservice);
 1302: 				    my $credentials=&Authen::Krb5::cc_default();
 1303: 				    $credentials->initialize($krbclient);
 1304: 				    my $krbreturn = 
 1305: 					&Authen::Krb5::get_in_tkt_with_password(
 1306: 										$krbclient,$krbserver,$upass,$credentials);
 1307: #				  unless ($krbreturn) {
 1308: #				      &logthis("Krb5 Error: ".
 1309: #					       &Authen::Krb5::error());
 1310: #				  }
 1311: 				    $pwdcorrect = ($krbreturn == 1);
 1312: 				} else { $pwdcorrect=0; }
 1313: 			    } elsif ($howpwd eq 'localauth') {
 1314: 				$pwdcorrect=&localauth::localauth($uname,$upass,
 1315: 								  $contentpwd);
 1316: 			    }
 1317: 			    if ($pwdcorrect) {
 1318: 				print $client "authorized\n";
 1319: 			    } else {
 1320: 				print $client "non_authorized\n";
 1321: 			    }  
 1322: 			} else {
 1323: 			    print $client "unknown_user\n";
 1324: 			}
 1325: 		    } else {
 1326: 			Reply($client, "refused\n", $userinput);
 1327: 		       
 1328: 		    }
 1329: # ---------------------------------------------------------------------- passwd
 1330: 		} elsif ($userinput =~ /^passwd/) { # encoded and client
 1331: 		    if (($wasenc==1) && isClient) {
 1332: 			my 
 1333: 			    ($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
 1334: 			chomp($npass);
 1335: 			$upass=&unescape($upass);
 1336: 			$npass=&unescape($npass);
 1337: 			&Debug("Trying to change password for $uname");
 1338: 			my $proname=propath($udom,$uname);
 1339: 			my $passfilename="$proname/passwd";
 1340: 			if (-e $passfilename) {
 1341: 			    my $realpasswd;
 1342: 			    { my $pf = IO::File->new($passfilename);
 1343: 			      $realpasswd=<$pf>; }
 1344: 			    chomp($realpasswd);
 1345: 			    my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
 1346: 			    if ($howpwd eq 'internal') {
 1347: 				&Debug("internal auth");
 1348: 				if (crypt($upass,$contentpwd) eq $contentpwd) {
 1349: 				    my $salt=time;
 1350: 				    $salt=substr($salt,6,2);
 1351: 				    my $ncpass=crypt($npass,$salt);
 1352: 				    {
 1353: 					my $pf;
 1354: 					if ($pf = IO::File->new(">$passfilename")) {
 1355: 					    print $pf "internal:$ncpass\n";
 1356: 					    &logthis("Result of password change for $uname: pwchange_success");
 1357: 					    print $client "ok\n";
 1358: 					} else {
 1359: 					    &logthis("Unable to open $uname passwd to change password");
 1360: 					    print $client "non_authorized\n";
 1361: 					}
 1362: 				    }             
 1363: 				    
 1364: 				} else {
 1365: 				    print $client "non_authorized\n";
 1366: 				}
 1367: 			    } elsif ($howpwd eq 'unix') {
 1368: 				# Unix means we have to access /etc/password
 1369: 				# one way or another.
 1370: 				# First: Make sure the current password is
 1371: 				#        correct
 1372: 				&Debug("auth is unix");
 1373: 				$contentpwd=(getpwnam($uname))[1];
 1374: 				my $pwdcorrect = "0";
 1375: 				my $pwauth_path="/usr/local/sbin/pwauth";
 1376: 				unless ($contentpwd eq 'x') {
 1377: 				    $pwdcorrect=
 1378: 					(crypt($upass,$contentpwd) eq $contentpwd);
 1379: 				} elsif (-e $pwauth_path) {
 1380: 				    open PWAUTH, "|$pwauth_path" or
 1381: 					die "Cannot invoke authentication";
 1382: 				    print PWAUTH "$uname\n$upass\n";
 1383: 				    close PWAUTH;
 1384: 				    &Debug("exited pwauth with $? ($uname,$upass) ");
 1385: 				    $pwdcorrect=($? == 0);
 1386: 				}
 1387: 				if ($pwdcorrect) {
 1388: 				    my $execdir=$perlvar{'lonDaemons'};
 1389: 				    &Debug("Opening lcpasswd pipeline");
 1390: 				    my $pf = IO::File->new("|$execdir/lcpasswd > $perlvar{'lonDaemons'}/logs/lcpasswd.log");
 1391: 				    print $pf "$uname\n$npass\n$npass\n";
 1392: 				    close $pf;
 1393: 				    my $err = $?;
 1394: 				    my $result = ($err>0 ? 'pwchange_failure' 
 1395: 						  : 'ok');
 1396: 				    &logthis("Result of password change for $uname: ".
 1397: 					     &lcpasswdstrerror($?));
 1398: 				    print $client "$result\n";
 1399: 				} else {
 1400: 				    print $client "non_authorized\n";
 1401: 				}
 1402: 			    } else {
 1403: 				print $client "auth_mode_error\n";
 1404: 			    }  
 1405: 			} else {
 1406: 			    print $client "unknown_user\n";
 1407: 			}
 1408: 		    } else {
 1409: 			Reply($client, "refused\n", $userinput);
 1410: 		       
 1411: 		    }
 1412: # -------------------------------------------------------------------- makeuser
 1413: 		} elsif ($userinput =~ /^makeuser/) { # encoded and client.
 1414: 		    &Debug("Make user received");
 1415: 		    my $oldumask=umask(0077);
 1416: 		    if (($wasenc==1) && isClient) {
 1417: 			my 
 1418: 			    ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
 1419: 			&Debug("cmd =".$cmd." $udom =".$udom.
 1420: 			       " uname=".$uname);
 1421: 			chomp($npass);
 1422: 			$npass=&unescape($npass);
 1423: 			my $proname=propath($udom,$uname);
 1424: 			my $passfilename="$proname/passwd";
 1425: 			&Debug("Password file created will be:".
 1426: 			       $passfilename);
 1427: 			if (-e $passfilename) {
 1428: 			    print $client "already_exists\n";
 1429: 			} elsif ($udom ne $currentdomainid) {
 1430: 			    print $client "not_right_domain\n";
 1431: 			} else {
 1432: 			    my @fpparts=split(/\//,$proname);
 1433: 			    my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
 1434: 			    my $fperror='';
 1435: 			    for (my $i=3;$i<=$#fpparts;$i++) {
 1436: 				$fpnow.='/'.$fpparts[$i]; 
 1437: 				unless (-e $fpnow) {
 1438: 				    unless (mkdir($fpnow,0777)) {
 1439: 					$fperror="error: ".($!+0)
 1440: 					    ." mkdir failed while attempting "
 1441: 					    ."makeuser\n";
 1442: 				    }
 1443: 				}
 1444: 			    }
 1445: 			    unless ($fperror) {
 1446: 				my $result=&make_passwd_file($uname, $umode,$npass,
 1447: 							     $passfilename);
 1448: 				print $client $result;
 1449: 			    } else {
 1450: 				print $client "$fperror\n";
 1451: 			    }
 1452: 			}
 1453: 		    } else {
 1454: 			Reply($client, "refused\n", $userinput);
 1455: 	      
 1456: 		    }
 1457: 		    umask($oldumask);
 1458: # -------------------------------------------------------------- changeuserauth
 1459: 		} elsif ($userinput =~ /^changeuserauth/) { # encoded & client
 1460: 		    &Debug("Changing authorization");
 1461: 		    if (($wasenc==1) && isClient) {
 1462: 			my 
 1463: 			    ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
 1464: 			chomp($npass);
 1465: 			&Debug("cmd = ".$cmd." domain= ".$udom.
 1466: 			       "uname =".$uname." umode= ".$umode);
 1467: 			$npass=&unescape($npass);
 1468: 			my $proname=&propath($udom,$uname);
 1469: 			my $passfilename="$proname/passwd";
 1470: 			if ($udom ne $currentdomainid) {
 1471: 			    print $client "not_right_domain\n";
 1472: 			} else {
 1473: 			    my $result=&make_passwd_file($uname, $umode,$npass,
 1474: 							 $passfilename);
 1475: 			    print $client $result;
 1476: 			}
 1477: 		    } else {
 1478: 			Reply($client, "refused\n", $userinput);
 1479: 		   
 1480: 		    }
 1481: # ------------------------------------------------------------------------ home
 1482: 		} elsif ($userinput =~ /^home/) { # client clear or encoded
 1483: 		    if(isClient) {
 1484: 			my ($cmd,$udom,$uname)=split(/:/,$userinput);
 1485: 			chomp($uname);
 1486: 			my $proname=propath($udom,$uname);
 1487: 			if (-e $proname) {
 1488: 			    print $client "found\n";
 1489: 			} else {
 1490: 			    print $client "not_found\n";
 1491: 			}
 1492: 		    } else {
 1493: 			Reply($client, "refused\n", $userinput);
 1494: 
 1495: 		    }
 1496: # ---------------------------------------------------------------------- update
 1497: 		} elsif ($userinput =~ /^update/) { # client clear or encoded.
 1498: 		    if(isClient) {
 1499: 			my ($cmd,$fname)=split(/:/,$userinput);
 1500: 			my $ownership=ishome($fname);
 1501: 			if ($ownership eq 'not_owner') {
 1502: 			    if (-e $fname) {
 1503: 				my ($dev,$ino,$mode,$nlink,
 1504: 				    $uid,$gid,$rdev,$size,
 1505: 				    $atime,$mtime,$ctime,
 1506: 				    $blksize,$blocks)=stat($fname);
 1507: 				my $now=time;
 1508: 				my $since=$now-$atime;
 1509: 				if ($since>$perlvar{'lonExpire'}) {
 1510: 				    my $reply=
 1511: 					&reply("unsub:$fname","$clientname");
 1512: 				    unlink("$fname");
 1513: 				} else {
 1514: 				    my $transname="$fname.in.transfer";
 1515: 				    my $remoteurl=
 1516: 					&reply("sub:$fname","$clientname");
 1517: 				    my $response;
 1518: 				    {
 1519: 					my $ua=new LWP::UserAgent;
 1520: 					my $request=new HTTP::Request('GET',"$remoteurl");
 1521: 					$response=$ua->request($request,$transname);
 1522: 				    }
 1523: 				    if ($response->is_error()) {
 1524: 					unlink($transname);
 1525: 					my $message=$response->status_line;
 1526: 					&logthis(
 1527: 						 "LWP GET: $message for $fname ($remoteurl)");
 1528: 				    } else {
 1529: 					if ($remoteurl!~/\.meta$/) {
 1530: 					    my $ua=new LWP::UserAgent;
 1531: 					    my $mrequest=
 1532: 						new HTTP::Request('GET',$remoteurl.'.meta');
 1533: 					    my $mresponse=
 1534: 						$ua->request($mrequest,$fname.'.meta');
 1535: 					    if ($mresponse->is_error()) {
 1536: 						unlink($fname.'.meta');
 1537: 					    }
 1538: 					}
 1539: 					rename($transname,$fname);
 1540: 				    }
 1541: 				}
 1542: 				print $client "ok\n";
 1543: 			    } else {
 1544: 				print $client "not_found\n";
 1545: 			    }
 1546: 			} else {
 1547: 			    print $client "rejected\n";
 1548: 			}
 1549: 		    } else {
 1550: 			Reply($client, "refused\n", $userinput);
 1551: 
 1552: 		    }
 1553: # -------------------------------------- fetch a user file from a remote server
 1554: 		} elsif ($userinput =~ /^fetchuserfile/) { # Client clear or enc.
 1555: 		    if(isClient) {
 1556: 			my ($cmd,$fname)=split(/:/,$userinput);
 1557: 			my ($udom,$uname,$ufile)=split(/\//,$fname);
 1558: 			my $udir=propath($udom,$uname).'/userfiles';
 1559: 			unless (-e $udir) { mkdir($udir,0770); }
 1560: 			if (-e $udir) {
 1561: 			    $ufile=~s/^[\.\~]+//;
 1562: 			    $ufile=~s/\///g;
 1563: 			    my $destname=$udir.'/'.$ufile;
 1564: 			    my $transname=$udir.'/'.$ufile.'.in.transit';
 1565: 			    my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
 1566: 			    my $response;
 1567: 			    {
 1568: 				my $ua=new LWP::UserAgent;
 1569: 				my $request=new HTTP::Request('GET',"$remoteurl");
 1570: 				$response=$ua->request($request,$transname);
 1571: 			    }
 1572: 			    if ($response->is_error()) {
 1573: 				unlink($transname);
 1574: 				my $message=$response->status_line;
 1575: 				&logthis("LWP GET: $message for $fname ($remoteurl)");
 1576: 				print $client "failed\n";
 1577: 			    } else {
 1578: 				if (!rename($transname,$destname)) {
 1579: 				    &logthis("Unable to move $transname to $destname");
 1580: 				    unlink($transname);
 1581: 				    print $client "failed\n";
 1582: 				} else {
 1583: 				    print $client "ok\n";
 1584: 				}
 1585: 			    }
 1586: 			} else {
 1587: 			    print $client "not_home\n";
 1588: 			}
 1589: 		    } else {
 1590: 			Reply($client, "refused\n", $userinput);
 1591: 
 1592: 		    }
 1593: # ------------------------------------------ authenticate access to a user file
 1594: 		} elsif ($userinput =~ /^tokenauthuserfile/) { # Client only
 1595: 		    if(isClient) {
 1596: 			my ($cmd,$fname,$session)=split(/:/,$userinput);
 1597: 			chomp($session);
 1598: 			my $reply='non_auth';
 1599: 			if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
 1600: 				 $session.'.id')) {
 1601: 			    while (my $line=<ENVIN>) {
 1602: 				if ($line=~/userfile\.$fname\=/) { $reply='ok'; }
 1603: 			    }
 1604: 			    close(ENVIN);
 1605: 			    print $client $reply."\n";
 1606: 			} else {
 1607: 			    print $client "invalid_token\n";
 1608: 			}
 1609: 		    } else {
 1610: 			Reply($client, "refused\n", $userinput);
 1611: 
 1612: 		    }
 1613: # ----------------------------------------------------------------- unsubscribe
 1614: 		} elsif ($userinput =~ /^unsub/) {
 1615: 		    if(isClient) {
 1616: 			my ($cmd,$fname)=split(/:/,$userinput);
 1617: 			if (-e $fname) {
 1618: 			    print $client &unsub($client,$fname,$clientip);
 1619: 			} else {
 1620: 			    print $client "not_found\n";
 1621: 			}
 1622: 		    } else {
 1623: 			Reply($client, "refused\n", $userinput);
 1624: 
 1625: 		    }
 1626: # ------------------------------------------------------------------- subscribe
 1627: 		} elsif ($userinput =~ /^sub/) {
 1628: 		    if(isClient) {
 1629: 			print $client &subscribe($userinput,$clientip);
 1630: 		    } else {
 1631: 			Reply($client, "refused\n", $userinput);
 1632: 
 1633: 		    }
 1634: # ------------------------------------------------------------- current version
 1635: 		} elsif ($userinput =~ /^currentversion/) {
 1636: 		    if(isClient) {
 1637: 			my ($cmd,$fname)=split(/:/,$userinput);
 1638: 			print $client &currentversion($fname)."\n";
 1639: 		    } else {
 1640: 			Reply($client, "refused\n", $userinput);
 1641: 
 1642: 		    }
 1643: # ------------------------------------------------------------------------- log
 1644: 		} elsif ($userinput =~ /^log/) {
 1645: 		    if(isClient) {
 1646: 			my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
 1647: 			chomp($what);
 1648: 			my $proname=propath($udom,$uname);
 1649: 			my $now=time;
 1650: 			{
 1651: 			    my $hfh;
 1652: 			    if ($hfh=IO::File->new(">>$proname/activity.log")) { 
 1653: 				print $hfh "$now:$clientname:$what\n";
 1654: 				print $client "ok\n"; 
 1655: 			    } else {
 1656: 				print $client "error: ".($!+0)
 1657: 				    ." IO::File->new Failed "
 1658: 				    ."while attempting log\n";
 1659: 			    }
 1660: 			}
 1661: 		    } else {
 1662: 			Reply($client, "refused\n", $userinput);
 1663: 
 1664: 		    }
 1665: # ------------------------------------------------------------------------- put
 1666: 		} elsif ($userinput =~ /^put/) {
 1667: 		    if(isClient) {
 1668: 			my ($cmd,$udom,$uname,$namespace,$what)
 1669: 			    =split(/:/,$userinput);
 1670: 			$namespace=~s/\//\_/g;
 1671: 			$namespace=~s/\W//g;
 1672: 			if ($namespace ne 'roles') {
 1673: 			    chomp($what);
 1674: 			    my $proname=propath($udom,$uname);
 1675: 			    my $now=time;
 1676: 			    unless ($namespace=~/^nohist\_/) {
 1677: 				my $hfh;
 1678: 				if (
 1679: 				    $hfh=IO::File->new(">>$proname/$namespace.hist")
 1680: 				    ) { print $hfh "P:$now:$what\n"; }
 1681: 			    }
 1682: 			    my @pairs=split(/\&/,$what);
 1683: 			    my %hash;
 1684: 			    if (tie(%hash,'GDBM_File',
 1685: 				    "$proname/$namespace.db",
 1686: 				    &GDBM_WRCREAT(),0640)) {
 1687: 				foreach my $pair (@pairs) {
 1688: 				    my ($key,$value)=split(/=/,$pair);
 1689: 				    $hash{$key}=$value;
 1690: 				}
 1691: 				if (untie(%hash)) {
 1692: 				    print $client "ok\n";
 1693: 				} else {
 1694: 				    print $client "error: ".($!+0)
 1695: 					." untie(GDBM) failed ".
 1696: 					"while attempting put\n";
 1697: 				}
 1698: 			    } else {
 1699: 				print $client "error: ".($!)
 1700: 				    ." tie(GDBM) Failed ".
 1701: 				    "while attempting put\n";
 1702: 			    }
 1703: 			} else {
 1704: 			    print $client "refused\n";
 1705: 			}
 1706: 		    } else {
 1707: 			Reply($client, "refused\n", $userinput);
 1708: 
 1709: 		    }
 1710: # -------------------------------------------------------------------- rolesput
 1711: 		} elsif ($userinput =~ /^rolesput/) {
 1712: 		    if(isClient) {
 1713: 			&Debug("rolesput");
 1714: 			if ($wasenc==1) {
 1715: 			    my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
 1716: 				=split(/:/,$userinput);
 1717: 			    &Debug("cmd = ".$cmd." exedom= ".$exedom.
 1718: 				   "user = ".$exeuser." udom=".$udom.
 1719: 				   "what = ".$what);
 1720: 			    my $namespace='roles';
 1721: 			    chomp($what);
 1722: 			    my $proname=propath($udom,$uname);
 1723: 			    my $now=time;
 1724: 			    {
 1725: 				my $hfh;
 1726: 				if (
 1727: 				    $hfh=IO::File->new(">>$proname/$namespace.hist")
 1728: 				    ) { 
 1729: 				    print $hfh "P:$now:$exedom:$exeuser:$what\n";
 1730: 				}
 1731: 			    }
 1732: 			    my @pairs=split(/\&/,$what);
 1733: 			    my %hash;
 1734: 			    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 1735: 				foreach my $pair (@pairs) {
 1736: 				    my ($key,$value)=split(/=/,$pair);
 1737: 				    &ManagePermissions($key, $udom, $uname,
 1738: 						       &GetAuthType( $udom, 
 1739: 								     $uname));
 1740: 				    $hash{$key}=$value;
 1741: 				}
 1742: 				if (untie(%hash)) {
 1743: 				    print $client "ok\n";
 1744: 				} else {
 1745: 				    print $client "error: ".($!+0)
 1746: 					." untie(GDBM) Failed ".
 1747: 					"while attempting rolesput\n";
 1748: 				}
 1749: 			    } else {
 1750: 				print $client "error: ".($!+0)
 1751: 				    ." tie(GDBM) Failed ".
 1752: 				    "while attempting rolesput\n";
 1753: 			    }
 1754: 			} else {
 1755: 			    print $client "refused\n";
 1756: 			}
 1757: 		    } else {
 1758: 			Reply($client, "refused\n", $userinput);
 1759: 		  
 1760: 		    }
 1761: # -------------------------------------------------------------------- rolesdel
 1762: 		} elsif ($userinput =~ /^rolesdel/) {
 1763: 		    if(isClient) {
 1764: 			&Debug("rolesdel");
 1765: 			if ($wasenc==1) {
 1766: 			    my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
 1767: 				=split(/:/,$userinput);
 1768: 			    &Debug("cmd = ".$cmd." exedom= ".$exedom.
 1769: 				   "user = ".$exeuser." udom=".$udom.
 1770: 				   "what = ".$what);
 1771: 			    my $namespace='roles';
 1772: 			    chomp($what);
 1773: 			    my $proname=propath($udom,$uname);
 1774: 			    my $now=time;
 1775: 			    {
 1776: 				my $hfh;
 1777: 				if (
 1778: 				    $hfh=IO::File->new(">>$proname/$namespace.hist")
 1779: 				    ) { 
 1780: 				    print $hfh "D:$now:$exedom:$exeuser:$what\n";
 1781: 				}
 1782: 			    }
 1783: 			    my @rolekeys=split(/\&/,$what);
 1784: 			    my %hash;
 1785: 			    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 1786: 				foreach my $key (@rolekeys) {
 1787: 				    delete $hash{$key};
 1788: 				}
 1789: 				if (untie(%hash)) {
 1790: 				    print $client "ok\n";
 1791: 				} else {
 1792: 				    print $client "error: ".($!+0)
 1793: 					." untie(GDBM) Failed ".
 1794: 					"while attempting rolesdel\n";
 1795: 				}
 1796: 			    } else {
 1797: 				print $client "error: ".($!+0)
 1798: 				    ." tie(GDBM) Failed ".
 1799: 				    "while attempting rolesdel\n";
 1800: 			    }
 1801: 			} else {
 1802: 			    print $client "refused\n";
 1803: 			}
 1804: 		    } else {
 1805: 			Reply($client, "refused\n", $userinput);
 1806: 		      
 1807: 		    }
 1808: # ------------------------------------------------------------------------- get
 1809: 		} elsif ($userinput =~ /^get/) {
 1810: 		    if(isClient) {
 1811: 			my ($cmd,$udom,$uname,$namespace,$what)
 1812: 			    =split(/:/,$userinput);
 1813: 			$namespace=~s/\//\_/g;
 1814: 			$namespace=~s/\W//g;
 1815: 			chomp($what);
 1816: 			my @queries=split(/\&/,$what);
 1817: 			my $proname=propath($udom,$uname);
 1818: 			my $qresult='';
 1819: 			my %hash;
 1820: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 1821: 			    for (my $i=0;$i<=$#queries;$i++) {
 1822: 				$qresult.="$hash{$queries[$i]}&";
 1823: 			    }
 1824: 			    if (untie(%hash)) {
 1825: 				$qresult=~s/\&$//;
 1826: 				print $client "$qresult\n";
 1827: 			    } else {
 1828: 				print $client "error: ".($!+0)
 1829: 				    ." untie(GDBM) Failed ".
 1830: 				    "while attempting get\n";
 1831: 			    }
 1832: 			} else {
 1833: 			    if ($!+0 == 2) {
 1834: 				print $client "error:No such file or ".
 1835: 				    "GDBM reported bad block error\n";
 1836: 			    } else {
 1837: 				print $client "error: ".($!+0)
 1838: 				    ." tie(GDBM) Failed ".
 1839: 				    "while attempting get\n";
 1840: 			    }
 1841: 			}
 1842: 		    } else {
 1843: 			Reply($client, "refused\n", $userinput);
 1844: 		       
 1845: 		    }
 1846: # ------------------------------------------------------------------------ eget
 1847: 		} elsif ($userinput =~ /^eget/) {
 1848: 		    if (isClient) {
 1849: 			my ($cmd,$udom,$uname,$namespace,$what)
 1850: 			    =split(/:/,$userinput);
 1851: 			$namespace=~s/\//\_/g;
 1852: 			$namespace=~s/\W//g;
 1853: 			chomp($what);
 1854: 			my @queries=split(/\&/,$what);
 1855: 			my $proname=propath($udom,$uname);
 1856: 			my $qresult='';
 1857: 			my %hash;
 1858: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 1859: 			    for (my $i=0;$i<=$#queries;$i++) {
 1860: 				$qresult.="$hash{$queries[$i]}&";
 1861: 			    }
 1862: 			    if (untie(%hash)) {
 1863: 				$qresult=~s/\&$//;
 1864: 				if ($cipher) {
 1865: 				    my $cmdlength=length($qresult);
 1866: 				    $qresult.="         ";
 1867: 				    my $encqresult='';
 1868: 				    for 
 1869: 					(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 1870: 					    $encqresult.=
 1871: 						unpack("H16",
 1872: 						       $cipher->encrypt(substr($qresult,$encidx,8)));
 1873: 					}
 1874: 				    print $client "enc:$cmdlength:$encqresult\n";
 1875: 				} else {
 1876: 				    print $client "error:no_key\n";
 1877: 				}
 1878: 			    } else {
 1879: 				print $client "error: ".($!+0)
 1880: 				    ." untie(GDBM) Failed ".
 1881: 				    "while attempting eget\n";
 1882: 			    }
 1883: 			} else {
 1884: 			    print $client "error: ".($!+0)
 1885: 				." tie(GDBM) Failed ".
 1886: 				"while attempting eget\n";
 1887: 			}
 1888: 		    } else {
 1889: 			Reply($client, "refused\n", $userinput);
 1890: 		    
 1891: 		    }
 1892: # ------------------------------------------------------------------------- del
 1893: 		} elsif ($userinput =~ /^del/) {
 1894: 		    if(isClient) {
 1895: 			my ($cmd,$udom,$uname,$namespace,$what)
 1896: 			    =split(/:/,$userinput);
 1897: 			$namespace=~s/\//\_/g;
 1898: 			$namespace=~s/\W//g;
 1899: 			chomp($what);
 1900: 			my $proname=propath($udom,$uname);
 1901: 			my $now=time;
 1902: 			unless ($namespace=~/^nohist\_/) {
 1903: 			    my $hfh;
 1904: 			    if (
 1905: 				$hfh=IO::File->new(">>$proname/$namespace.hist")
 1906: 				) { print $hfh "D:$now:$what\n"; }
 1907: 			}
 1908: 			my @keys=split(/\&/,$what);
 1909: 			my %hash;
 1910: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 1911: 			    foreach my $key (@keys) {
 1912: 				delete($hash{$key});
 1913: 			    }
 1914: 			    if (untie(%hash)) {
 1915: 				print $client "ok\n";
 1916: 			    } else {
 1917: 				print $client "error: ".($!+0)
 1918: 				    ." untie(GDBM) Failed ".
 1919: 				    "while attempting del\n";
 1920: 			    }
 1921: 			} else {
 1922: 			    print $client "error: ".($!+0)
 1923: 				." tie(GDBM) Failed ".
 1924: 				"while attempting del\n";
 1925: 			}
 1926: 		    } else {
 1927: 			Reply($client, "refused\n", $userinput);
 1928: 			
 1929: 		    }
 1930: # ------------------------------------------------------------------------ keys
 1931: 		} elsif ($userinput =~ /^keys/) {
 1932: 		    if(isClient) {
 1933: 			my ($cmd,$udom,$uname,$namespace)
 1934: 			    =split(/:/,$userinput);
 1935: 			$namespace=~s/\//\_/g;
 1936: 			$namespace=~s/\W//g;
 1937: 			my $proname=propath($udom,$uname);
 1938: 			my $qresult='';
 1939: 			my %hash;
 1940: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 1941: 			    foreach my $key (keys %hash) {
 1942: 				$qresult.="$key&";
 1943: 			    }
 1944: 			    if (untie(%hash)) {
 1945: 				$qresult=~s/\&$//;
 1946: 				print $client "$qresult\n";
 1947: 			    } else {
 1948: 				print $client "error: ".($!+0)
 1949: 				    ." untie(GDBM) Failed ".
 1950: 				    "while attempting keys\n";
 1951: 			    }
 1952: 			} else {
 1953: 			    print $client "error: ".($!+0)
 1954: 				." tie(GDBM) Failed ".
 1955: 				"while attempting keys\n";
 1956: 			}
 1957: 		    } else {
 1958: 			Reply($client, "refused\n", $userinput);
 1959: 		   
 1960: 		    }
 1961: # ----------------------------------------------------------------- dumpcurrent
 1962: 		} elsif ($userinput =~ /^currentdump/) {
 1963: 		    if (isClient) {
 1964: 			my ($cmd,$udom,$uname,$namespace)
 1965: 			    =split(/:/,$userinput);
 1966: 			$namespace=~s/\//\_/g;
 1967: 			$namespace=~s/\W//g;
 1968: 			my $qresult='';
 1969: 			my $proname=propath($udom,$uname);
 1970: 			my %hash;
 1971: 			if (tie(%hash,'GDBM_File',
 1972: 				"$proname/$namespace.db",
 1973: 				&GDBM_READER(),0640)) {
 1974: 			    # Structure of %data:
 1975: 			    # $data{$symb}->{$parameter}=$value;
 1976: 			    # $data{$symb}->{'v.'.$parameter}=$version;
 1977: 			    # since $parameter will be unescaped, we do not
 1978: 			    # have to worry about silly parameter names...
 1979: 			    my %data = ();
 1980: 			    while (my ($key,$value) = each(%hash)) {
 1981: 				my ($v,$symb,$param) = split(/:/,$key);
 1982: 				next if ($v eq 'version' || $symb eq 'keys');
 1983: 				next if (exists($data{$symb}) && 
 1984: 					 exists($data{$symb}->{$param}) &&
 1985: 					 $data{$symb}->{'v.'.$param} > $v);
 1986: 				$data{$symb}->{$param}=$value;
 1987: 				$data{$symb}->{'v.'.$param}=$v;
 1988: 			    }
 1989: 			    if (untie(%hash)) {
 1990: 				while (my ($symb,$param_hash) = each(%data)) {
 1991: 				    while(my ($param,$value) = each (%$param_hash)){
 1992: 					next if ($param =~ /^v\./);
 1993: 					$qresult.=$symb.':'.$param.'='.$value.'&';
 1994: 				    }
 1995: 				}
 1996: 				chop($qresult);
 1997: 				print $client "$qresult\n";
 1998: 			    } else {
 1999: 				print $client "error: ".($!+0)
 2000: 				    ." untie(GDBM) Failed ".
 2001: 				    "while attempting currentdump\n";
 2002: 			    }
 2003: 			} else {
 2004: 			    print $client "error: ".($!+0)
 2005: 				." tie(GDBM) Failed ".
 2006: 				"while attempting currentdump\n";
 2007: 			}
 2008: 		    } else {
 2009: 			Reply($client, "refused\n", $userinput);
 2010: 		    }
 2011: # ------------------------------------------------------------------------ dump
 2012: 		} elsif ($userinput =~ /^dump/) {
 2013: 		    if(isClient) {
 2014: 			my ($cmd,$udom,$uname,$namespace,$regexp)
 2015: 			    =split(/:/,$userinput);
 2016: 			$namespace=~s/\//\_/g;
 2017: 			$namespace=~s/\W//g;
 2018: 			if (defined($regexp)) {
 2019: 			    $regexp=&unescape($regexp);
 2020: 			} else {
 2021: 			    $regexp='.';
 2022: 			}
 2023: 			my $qresult='';
 2024: 			my $proname=propath($udom,$uname);
 2025: 			my %hash;
 2026: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 2027: 			       study($regexp);
 2028: 			       while (my ($key,$value) = each(%hash)) {
 2029: 				   if ($regexp eq '.') {
 2030: 				       $qresult.=$key.'='.$value.'&';
 2031: 				   } else {
 2032: 				       my $unescapeKey = &unescape($key);
 2033: 				       if (eval('$unescapeKey=~/$regexp/')) {
 2034: 					   $qresult.="$key=$value&";
 2035: 				       }
 2036: 				   }
 2037: 			       }
 2038: 			       if (untie(%hash)) {
 2039: 				   chop($qresult);
 2040: 				   print $client "$qresult\n";
 2041: 			       } else {
 2042: 				   print $client "error: ".($!+0)
 2043: 				       ." untie(GDBM) Failed ".
 2044:                                        "while attempting dump\n";
 2045: 			       }
 2046: 			   } else {
 2047: 			       print $client "error: ".($!+0)
 2048: 				   ." tie(GDBM) Failed ".
 2049: 				   "while attempting dump\n";
 2050: 			   }
 2051: 		    } else {
 2052: 			Reply($client, "refused\n", $userinput);
 2053: 		 
 2054: 		    }
 2055: # ----------------------------------------------------------------------- store
 2056: 		} elsif ($userinput =~ /^store/) {
 2057: 		    if(isClient) {
 2058: 			my ($cmd,$udom,$uname,$namespace,$rid,$what)
 2059: 			    =split(/:/,$userinput);
 2060: 			$namespace=~s/\//\_/g;
 2061: 			$namespace=~s/\W//g;
 2062: 			if ($namespace ne 'roles') {
 2063: 			    chomp($what);
 2064: 			    my $proname=propath($udom,$uname);
 2065: 			    my $now=time;
 2066: 			    unless ($namespace=~/^nohist\_/) {
 2067: 				my $hfh;
 2068: 				if (
 2069: 				    $hfh=IO::File->new(">>$proname/$namespace.hist")
 2070: 				    ) { print $hfh "P:$now:$rid:$what\n"; }
 2071: 			    }
 2072: 			    my @pairs=split(/\&/,$what);
 2073: 			    my %hash;
 2074: 			    if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
 2075: 				my @previouskeys=split(/&/,$hash{"keys:$rid"});
 2076: 				my $key;
 2077: 				$hash{"version:$rid"}++;
 2078: 				my $version=$hash{"version:$rid"};
 2079: 				my $allkeys=''; 
 2080: 				foreach my $pair (@pairs) {
 2081: 				    my ($key,$value)=split(/=/,$pair);
 2082: 				    $allkeys.=$key.':';
 2083: 				    $hash{"$version:$rid:$key"}=$value;
 2084: 				}
 2085: 				$hash{"$version:$rid:timestamp"}=$now;
 2086: 				$allkeys.='timestamp';
 2087: 				$hash{"$version:keys:$rid"}=$allkeys;
 2088: 				if (untie(%hash)) {
 2089: 				    print $client "ok\n";
 2090: 				} else {
 2091: 				    print $client "error: ".($!+0)
 2092: 					." untie(GDBM) Failed ".
 2093: 					"while attempting store\n";
 2094: 				}
 2095: 			    } else {
 2096: 				print $client "error: ".($!+0)
 2097: 				    ." tie(GDBM) Failed ".
 2098: 				    "while attempting store\n";
 2099: 			    }
 2100: 			} else {
 2101: 			    print $client "refused\n";
 2102: 			}
 2103: 		    } else {
 2104: 			Reply($client, "refused\n", $userinput);
 2105: 		     
 2106: 		    }
 2107: # --------------------------------------------------------------------- restore
 2108: 		} elsif ($userinput =~ /^restore/) {
 2109: 		    if(isClient) {
 2110: 			my ($cmd,$udom,$uname,$namespace,$rid)
 2111: 			    =split(/:/,$userinput);
 2112: 			$namespace=~s/\//\_/g;
 2113: 			$namespace=~s/\W//g;
 2114: 			chomp($rid);
 2115: 			my $proname=propath($udom,$uname);
 2116: 			my $qresult='';
 2117: 			my %hash;
 2118: 			if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 2119: 			    my $version=$hash{"version:$rid"};
 2120: 			    $qresult.="version=$version&";
 2121: 			    my $scope;
 2122: 			    for ($scope=1;$scope<=$version;$scope++) {
 2123: 				my $vkeys=$hash{"$scope:keys:$rid"};
 2124: 				my @keys=split(/:/,$vkeys);
 2125: 				my $key;
 2126: 				$qresult.="$scope:keys=$vkeys&";
 2127: 				foreach $key (@keys) {
 2128: 				    $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 2129: 				}                                  
 2130: 			    }
 2131: 			    if (untie(%hash)) {
 2132: 				$qresult=~s/\&$//;
 2133: 				print $client "$qresult\n";
 2134: 			    } else {
 2135: 				print $client "error: ".($!+0)
 2136: 				    ." untie(GDBM) Failed ".
 2137: 				    "while attempting restore\n";
 2138: 			    }
 2139: 			} else {
 2140: 			    print $client "error: ".($!+0)
 2141: 				." tie(GDBM) Failed ".
 2142: 				"while attempting restore\n";
 2143: 			}
 2144: 		    } else  {
 2145: 			Reply($client, "refused\n", $userinput);
 2146: 		       
 2147: 		    }
 2148: # -------------------------------------------------------------------- chatsend
 2149: 		} elsif ($userinput =~ /^chatsend/) {
 2150: 		    if(isClient) {
 2151: 			my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
 2152: 			&chatadd($cdom,$cnum,$newpost);
 2153: 			print $client "ok\n";
 2154: 		    } else {
 2155: 			Reply($client, "refused\n", $userinput);
 2156: 		      
 2157: 		    }
 2158: # -------------------------------------------------------------------- chatretr
 2159: 		} elsif ($userinput =~ /^chatretr/) {
 2160: 		    if(isClient) {
 2161: 			my 
 2162: 			    ($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
 2163: 			my $reply='';
 2164: 			foreach (&getchat($cdom,$cnum,$udom,$uname)) {
 2165: 			    $reply.=&escape($_).':';
 2166: 			}
 2167: 			$reply=~s/\:$//;
 2168: 			print $client $reply."\n";
 2169: 		    } else {
 2170: 			Reply($client, "refused\n", $userinput);
 2171: 		       
 2172: 		    }
 2173: # ------------------------------------------------------------------- querysend
 2174: 		} elsif ($userinput =~ /^querysend/) {
 2175: 		    if(isClient) {
 2176: 			my ($cmd,$query,
 2177: 			    $arg1,$arg2,$arg3)=split(/\:/,$userinput);
 2178: 			$query=~s/\n*$//g;
 2179: 			print $client "".
 2180: 			    sqlreply("$clientname\&$query".
 2181: 				     "\&$arg1"."\&$arg2"."\&$arg3")."\n";
 2182: 		    } else {
 2183: 			Reply($client, "refused\n", $userinput);
 2184: 		      
 2185: 		    }
 2186: # ------------------------------------------------------------------ queryreply
 2187: 		} elsif ($userinput =~ /^queryreply/) {
 2188: 		    if(isClient) {
 2189: 			my ($cmd,$id,$reply)=split(/:/,$userinput); 
 2190: 			my $store;
 2191: 			my $execdir=$perlvar{'lonDaemons'};
 2192: 			if ($store=IO::File->new(">$execdir/tmp/$id")) {
 2193: 			    $reply=~s/\&/\n/g;
 2194: 			    print $store $reply;
 2195: 			    close $store;
 2196: 			    my $store2=IO::File->new(">$execdir/tmp/$id.end");
 2197: 			    print $store2 "done\n";
 2198: 			    close $store2;
 2199: 			    print $client "ok\n";
 2200: 			}
 2201: 			else {
 2202: 			    print $client "error: ".($!+0)
 2203: 				." IO::File->new Failed ".
 2204: 				"while attempting queryreply\n";
 2205: 			}
 2206: 		    } else {
 2207: 			Reply($client, "refused\n", $userinput);
 2208: 		     
 2209: 		    }
 2210: # ----------------------------------------------------------------- courseidput
 2211: 		} elsif ($userinput =~ /^courseidput/) {
 2212: 		    if(isClient) {
 2213: 			my ($cmd,$udom,$what)=split(/:/,$userinput);
 2214: 			chomp($what);
 2215: 			$udom=~s/\W//g;
 2216: 			my $proname=
 2217: 			    "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
 2218: 			my $now=time;
 2219: 			my @pairs=split(/\&/,$what);
 2220: 			my %hash;
 2221: 			if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
 2222: 			    foreach my $pair (@pairs) {
 2223: 				my ($key,$value)=split(/=/,$pair);
 2224: 				$hash{$key}=$value.':'.$now;
 2225: 			    }
 2226: 			    if (untie(%hash)) {
 2227: 				print $client "ok\n";
 2228: 			    } else {
 2229: 				print $client "error: ".($!+0)
 2230: 				    ." untie(GDBM) Failed ".
 2231: 				    "while attempting courseidput\n";
 2232: 			    }
 2233: 			} else {
 2234: 			    print $client "error: ".($!+0)
 2235: 				." tie(GDBM) Failed ".
 2236: 				"while attempting courseidput\n";
 2237: 			}
 2238: 		    } else {
 2239: 			Reply($client, "refused\n", $userinput);
 2240: 		       
 2241: 		    }
 2242: # ---------------------------------------------------------------- courseiddump
 2243: 		} elsif ($userinput =~ /^courseiddump/) {
 2244: 		    if(isClient) {
 2245: 			my ($cmd,$udom,$since,$description)
 2246: 			    =split(/:/,$userinput);
 2247: 			if (defined($description)) {
 2248: 			    $description=&unescape($description);
 2249: 			} else {
 2250: 			    $description='.';
 2251: 			}
 2252: 			unless (defined($since)) { $since=0; }
 2253: 			my $qresult='';
 2254: 			my $proname=
 2255: 			    "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
 2256: 			my %hash;
 2257: 			if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
 2258: 			    while (my ($key,$value) = each(%hash)) {
 2259: 				my ($descr,$lasttime)=split(/\:/,$value);
 2260: 				if ($lasttime<$since) { next; }
 2261: 				if ($description eq '.') {
 2262: 				    $qresult.=$key.'='.$descr.'&';
 2263: 				} else {
 2264: 				    my $unescapeVal = &unescape($descr);
 2265: 				    if (eval('$unescapeVal=~/$description/i')) {
 2266: 					$qresult.="$key=$descr&";
 2267: 				    }
 2268: 				}
 2269: 			    }
 2270: 			    if (untie(%hash)) {
 2271: 				chop($qresult);
 2272: 				print $client "$qresult\n";
 2273: 			    } else {
 2274: 				print $client "error: ".($!+0)
 2275: 				    ." untie(GDBM) Failed ".
 2276: 				    "while attempting courseiddump\n";
 2277: 			    }
 2278: 			} else {
 2279: 			    print $client "error: ".($!+0)
 2280: 				." tie(GDBM) Failed ".
 2281: 				"while attempting courseiddump\n";
 2282: 			}
 2283: 		    } else {
 2284: 			Reply($client, "refused\n", $userinput);
 2285: 		       
 2286: 		    }
 2287: # ----------------------------------------------------------------------- idput
 2288: 		} elsif ($userinput =~ /^idput/) {
 2289: 		    if(isClient) {
 2290: 			my ($cmd,$udom,$what)=split(/:/,$userinput);
 2291: 			chomp($what);
 2292: 			$udom=~s/\W//g;
 2293: 			my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 2294: 			my $now=time;
 2295: 			{
 2296: 			    my $hfh;
 2297: 			    if (
 2298: 				$hfh=IO::File->new(">>$proname.hist")
 2299: 				) { print $hfh "P:$now:$what\n"; }
 2300: 			}
 2301: 			my @pairs=split(/\&/,$what);
 2302: 			my %hash;
 2303: 			if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
 2304: 			    foreach my $pair (@pairs) {
 2305: 				my ($key,$value)=split(/=/,$pair);
 2306: 				$hash{$key}=$value;
 2307: 			    }
 2308: 			    if (untie(%hash)) {
 2309: 				print $client "ok\n";
 2310: 			    } else {
 2311: 				print $client "error: ".($!+0)
 2312: 				    ." untie(GDBM) Failed ".
 2313: 				    "while attempting idput\n";
 2314: 			    }
 2315: 			} else {
 2316: 			    print $client "error: ".($!+0)
 2317: 				." tie(GDBM) Failed ".
 2318: 				"while attempting idput\n";
 2319: 			}
 2320: 		    } else {
 2321: 			Reply($client, "refused\n", $userinput);
 2322: 		       
 2323: 		    }
 2324: # ----------------------------------------------------------------------- idget
 2325: 		} elsif ($userinput =~ /^idget/) {
 2326: 		    if(isClient) {
 2327: 			my ($cmd,$udom,$what)=split(/:/,$userinput);
 2328: 			chomp($what);
 2329: 			$udom=~s/\W//g;
 2330: 			my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 2331: 			my @queries=split(/\&/,$what);
 2332: 			my $qresult='';
 2333: 			my %hash;
 2334: 			if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
 2335: 			    for (my $i=0;$i<=$#queries;$i++) {
 2336: 				$qresult.="$hash{$queries[$i]}&";
 2337: 			    }
 2338: 			    if (untie(%hash)) {
 2339: 				$qresult=~s/\&$//;
 2340: 				print $client "$qresult\n";
 2341: 			    } else {
 2342: 				print $client "error: ".($!+0)
 2343: 				    ." untie(GDBM) Failed ".
 2344: 				    "while attempting idget\n";
 2345: 			    }
 2346: 			} else {
 2347: 			    print $client "error: ".($!+0)
 2348: 				." tie(GDBM) Failed ".
 2349: 				"while attempting idget\n";
 2350: 			}
 2351: 		    } else {
 2352: 			Reply($client, "refused\n", $userinput);
 2353: 		       
 2354: 		    }
 2355: # ---------------------------------------------------------------------- tmpput
 2356: 		} elsif ($userinput =~ /^tmpput/) {
 2357: 		    if(isClient) {
 2358: 			my ($cmd,$what)=split(/:/,$userinput);
 2359: 			my $store;
 2360: 			$tmpsnum++;
 2361: 			my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 2362: 			$id=~s/\W/\_/g;
 2363: 			$what=~s/\n//g;
 2364: 			my $execdir=$perlvar{'lonDaemons'};
 2365: 			if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 2366: 			    print $store $what;
 2367: 			    close $store;
 2368: 			    print $client "$id\n";
 2369: 			}
 2370: 			else {
 2371: 			    print $client "error: ".($!+0)
 2372: 				."IO::File->new Failed ".
 2373: 				"while attempting tmpput\n";
 2374: 			}
 2375: 		    } else {
 2376: 			Reply($client, "refused\n", $userinput);
 2377: 		    
 2378: 		    }
 2379: 		    
 2380: # ---------------------------------------------------------------------- tmpget
 2381: 		} elsif ($userinput =~ /^tmpget/) {
 2382: 		    if(isClient) {
 2383: 			my ($cmd,$id)=split(/:/,$userinput);
 2384: 			chomp($id);
 2385: 			$id=~s/\W/\_/g;
 2386: 			my $store;
 2387: 			my $execdir=$perlvar{'lonDaemons'};
 2388: 			if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 2389: 			    my $reply=<$store>;
 2390: 			    print $client "$reply\n";
 2391: 			    close $store;
 2392: 			}
 2393: 			else {
 2394: 			    print $client "error: ".($!+0)
 2395: 				."IO::File->new Failed ".
 2396: 				"while attempting tmpget\n";
 2397: 			}
 2398: 		    } else {
 2399: 			Reply($client, "refused\n", $userinput);
 2400: 		      
 2401: 		    }
 2402: # ---------------------------------------------------------------------- tmpdel
 2403: 		} elsif ($userinput =~ /^tmpdel/) {
 2404: 		    if(isClient) {
 2405: 			my ($cmd,$id)=split(/:/,$userinput);
 2406: 			chomp($id);
 2407: 			$id=~s/\W/\_/g;
 2408: 			my $execdir=$perlvar{'lonDaemons'};
 2409: 			if (unlink("$execdir/tmp/$id.tmp")) {
 2410: 			    print $client "ok\n";
 2411: 			} else {
 2412: 			    print $client "error: ".($!+0)
 2413: 				."Unlink tmp Failed ".
 2414: 				"while attempting tmpdel\n";
 2415: 			}
 2416: 		    } else {
 2417: 			Reply($client, "refused\n", $userinput);
 2418: 		     
 2419: 		    }
 2420: # -------------------------------------------------------------------------- ls
 2421: 		} elsif ($userinput =~ /^ls/) {
 2422: 		    if(isClient) {
 2423: 			my ($cmd,$ulsdir)=split(/:/,$userinput);
 2424: 			my $ulsout='';
 2425: 			my $ulsfn;
 2426: 			if (-e $ulsdir) {
 2427: 			    if(-d $ulsdir) {
 2428: 				if (opendir(LSDIR,$ulsdir)) {
 2429: 				    while ($ulsfn=readdir(LSDIR)) {
 2430: 					my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 2431: 					$ulsout.=$ulsfn.'&'.
 2432: 					    join('&',@ulsstats).':';
 2433: 				    }
 2434: 				    closedir(LSDIR);
 2435: 				}
 2436: 			    } else {
 2437: 				my @ulsstats=stat($ulsdir);
 2438: 				$ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 2439: 			    }
 2440: 			} else {
 2441: 			    $ulsout='no_such_dir';
 2442: 			}
 2443: 			if ($ulsout eq '') { $ulsout='empty'; }
 2444: 			print $client "$ulsout\n";
 2445: 		    } else {
 2446: 			Reply($client, "refused\n", $userinput);
 2447: 		     
 2448: 		    }
 2449: # ----------------------------------------------------------------- setannounce
 2450: 		} elsif ($userinput =~ /^setannounce/) {
 2451: 		    if (isClient) {
 2452: 			my ($cmd,$announcement)=split(/:/,$userinput);
 2453: 			chomp($announcement);
 2454: 			$announcement=&unescape($announcement);
 2455: 			if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
 2456: 						    '/announcement.txt')) {
 2457: 			    print $store $announcement;
 2458: 			    close $store;
 2459: 			    print $client "ok\n";
 2460: 			} else {
 2461: 			    print $client "error: ".($!+0)."\n";
 2462: 			}
 2463: 		    } else {
 2464: 			Reply($client, "refused\n", $userinput);
 2465: 		       
 2466: 		    }
 2467: # ------------------------------------------------------------------ Hanging up
 2468: 		} elsif (($userinput =~ /^exit/) ||
 2469: 			 ($userinput =~ /^init/)) { # no restrictions.
 2470: 		    &logthis(
 2471: 			     "Client $clientip ($clientname) hanging up: $userinput");
 2472: 		    print $client "bye\n";
 2473: 		    $client->close();
 2474: 		    last;
 2475: 
 2476: # ---------------------------------- set current host/domain
 2477: 		} elsif ($userinput =~ /^sethost:/) {
 2478: 		    if (isClient) {
 2479: 			print $client &sethost($userinput)."\n";
 2480: 		    } else {
 2481: 			print $client "refused\n";
 2482: 		    }
 2483: #---------------------------------- request file (?) version.
 2484: 		} elsif ($userinput =~/^version:/) {
 2485: 		    if (isClient) {
 2486: 			print $client &version($userinput)."\n";
 2487: 		    } else {
 2488: 			print $client "refused\n";
 2489: 		    }
 2490: # ------------------------------------------------------------- unknown command
 2491: 
 2492: 		} else {
 2493: 		    # unknown command
 2494: 		    print $client "unknown_cmd\n";
 2495: 		}
 2496: # -------------------------------------------------------------------- complete
 2497: 		alarm(0);
 2498: 		&status('Listening to '.$clientname);
 2499: 	    }
 2500: # --------------------------------------------- client unknown or fishy, refuse
 2501: 	} else {
 2502: 	    print $client "refused\n";
 2503: 	    $client->close();
 2504: 	    &logthis("<font color=blue>WARNING: "
 2505: 		     ."Rejected client $clientip, closing connection</font>");
 2506: 	}
 2507:     }             
 2508:     
 2509: # =============================================================================
 2510:     
 2511:     &logthis("<font color=red>CRITICAL: "
 2512: 	     ."Disconnect from $clientip ($clientname)</font>");    
 2513:     
 2514:     
 2515:     # this exit is VERY important, otherwise the child will become
 2516:     # a producer of more and more children, forking yourself into
 2517:     # process death.
 2518:     exit;
 2519:     
 2520: }
 2521: 
 2522: 
 2523: #
 2524: #   Checks to see if the input roleput request was to set
 2525: # an author role.  If so, invokes the lchtmldir script to set
 2526: # up a correct public_html 
 2527: # Parameters:
 2528: #    request   - The request sent to the rolesput subchunk.
 2529: #                We're looking for  /domain/_au
 2530: #    domain    - The domain in which the user is having roles doctored.
 2531: #    user      - Name of the user for which the role is being put.
 2532: #    authtype  - The authentication type associated with the user.
 2533: #
 2534: sub ManagePermissions
 2535: {
 2536:     my $request = shift;
 2537:     my $domain  = shift;
 2538:     my $user    = shift;
 2539:     my $authtype= shift;
 2540: 
 2541:     # See if the request is of the form /$domain/_au
 2542:     &logthis("ruequest is $request");
 2543:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
 2544: 	my $execdir = $perlvar{'lonDaemons'};
 2545: 	my $userhome= "/home/$user" ;
 2546: 	&logthis("system $execdir/lchtmldir $userhome $user $authtype");
 2547: 	system("$execdir/lchtmldir $userhome $user $authtype");
 2548:     }
 2549: }
 2550: #
 2551: #   GetAuthType - Determines the authorization type of a user in a domain.
 2552: 
 2553: #     Returns the authorization type or nouser if there is no such user.
 2554: #
 2555: sub GetAuthType 
 2556: {
 2557:     my $domain = shift;
 2558:     my $user   = shift;
 2559: 
 2560:     Debug("GetAuthType( $domain, $user ) \n");
 2561:     my $proname    = &propath($domain, $user); 
 2562:     my $passwdfile = "$proname/passwd";
 2563:     if( -e $passwdfile ) {
 2564: 	my $pf = IO::File->new($passwdfile);
 2565: 	my $realpassword = <$pf>;
 2566: 	chomp($realpassword);
 2567: 	Debug("Password info = $realpassword\n");
 2568: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 2569: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 2570: 	my $availinfo = '';
 2571: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
 2572: 	    $availinfo = $contentpwd;
 2573: 	}
 2574: 
 2575: 	return "$authtype:$availinfo";
 2576:     }
 2577:     else {
 2578: 	Debug("Returning nouser");
 2579: 	return "nouser";
 2580:     }
 2581: }
 2582: 
 2583: sub addline {
 2584:     my ($fname,$hostid,$ip,$newline)=@_;
 2585:     my $contents;
 2586:     my $found=0;
 2587:     my $expr='^'.$hostid.':'.$ip.':';
 2588:     $expr =~ s/\./\\\./g;
 2589:     my $sh;
 2590:     if ($sh=IO::File->new("$fname.subscription")) {
 2591: 	while (my $subline=<$sh>) {
 2592: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 2593: 	}
 2594: 	$sh->close();
 2595:     }
 2596:     $sh=IO::File->new(">$fname.subscription");
 2597:     if ($contents) { print $sh $contents; }
 2598:     if ($newline) { print $sh $newline; }
 2599:     $sh->close();
 2600:     return $found;
 2601: }
 2602: 
 2603: sub getchat {
 2604:     my ($cdom,$cname,$udom,$uname)=@_;
 2605:     my %hash;
 2606:     my $proname=&propath($cdom,$cname);
 2607:     my @entries=();
 2608:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 2609: 	    &GDBM_READER(),0640)) {
 2610: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 2611: 	untie %hash;
 2612:     }
 2613:     my @participants=();
 2614:     my $cutoff=time-60;
 2615:     if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
 2616: 	    &GDBM_WRCREAT(),0640)) {
 2617:         $hash{$uname.':'.$udom}=time;
 2618:         foreach (sort keys %hash) {
 2619: 	    if ($hash{$_}>$cutoff) {
 2620: 		$participants[$#participants+1]='active_participant:'.$_;
 2621:             }
 2622:         }
 2623:         untie %hash;
 2624:     }
 2625:     return (@participants,@entries);
 2626: }
 2627: 
 2628: sub chatadd {
 2629:     my ($cdom,$cname,$newchat)=@_;
 2630:     my %hash;
 2631:     my $proname=&propath($cdom,$cname);
 2632:     my @entries=();
 2633:     my $time=time;
 2634:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 2635: 	    &GDBM_WRCREAT(),0640)) {
 2636: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 2637: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 2638: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 2639: 	my $newid=$time.'_000000';
 2640: 	if ($thentime==$time) {
 2641: 	    $idnum=~s/^0+//;
 2642: 	    $idnum++;
 2643: 	    $idnum=substr('000000'.$idnum,-6,6);
 2644: 	    $newid=$time.'_'.$idnum;
 2645: 	}
 2646: 	$hash{$newid}=$newchat;
 2647: 	my $expired=$time-3600;
 2648: 	foreach (keys %hash) {
 2649: 	    my ($thistime)=($_=~/(\d+)\_/);
 2650: 	    if ($thistime<$expired) {
 2651: 		delete $hash{$_};
 2652: 	    }
 2653: 	}
 2654: 	untie %hash;
 2655:     }
 2656:     {
 2657: 	my $hfh;
 2658: 	if ($hfh=IO::File->new(">>$proname/chatroom.log")) { 
 2659: 	    print $hfh "$time:".&unescape($newchat)."\n";
 2660: 	}
 2661:     }
 2662: }
 2663: 
 2664: sub unsub {
 2665:     my ($fname,$clientip)=@_;
 2666:     my $result;
 2667:     if (unlink("$fname.$clientname")) {
 2668: 	$result="ok\n";
 2669:     } else {
 2670: 	$result="not_subscribed\n";
 2671:     }
 2672:     if (-e "$fname.subscription") {
 2673: 	my $found=&addline($fname,$clientname,$clientip,'');
 2674: 	if ($found) { $result="ok\n"; }
 2675:     } else {
 2676: 	if ($result != "ok\n") { $result="not_subscribed\n"; }
 2677:     }
 2678:     return $result;
 2679: }
 2680: 
 2681: sub currentversion {
 2682:     my $fname=shift;
 2683:     my $version=-1;
 2684:     my $ulsdir='';
 2685:     if ($fname=~/^(.+)\/[^\/]+$/) {
 2686:        $ulsdir=$1;
 2687:     }
 2688:     my ($fnamere1,$fnamere2);
 2689:     # remove version if already specified
 2690:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 2691:     # get the bits that go before and after the version number
 2692:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
 2693: 	$fnamere1=$1;
 2694: 	$fnamere2='.'.$2;
 2695:     }
 2696:     if (-e $fname) { $version=1; }
 2697:     if (-e $ulsdir) {
 2698: 	if(-d $ulsdir) {
 2699: 	    if (opendir(LSDIR,$ulsdir)) {
 2700: 		my $ulsfn;
 2701: 		while ($ulsfn=readdir(LSDIR)) {
 2702: # see if this is a regular file (ignore links produced earlier)
 2703: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
 2704: 		    unless (-l $thisfile) {
 2705: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
 2706: 			    if ($1>$version) { $version=$1; }
 2707: 			}
 2708: 		    }
 2709: 		}
 2710: 		closedir(LSDIR);
 2711: 		$version++;
 2712: 	    }
 2713: 	}
 2714:     }
 2715:     return $version;
 2716: }
 2717: 
 2718: sub thisversion {
 2719:     my $fname=shift;
 2720:     my $version=-1;
 2721:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 2722: 	$version=$1;
 2723:     }
 2724:     return $version;
 2725: }
 2726: 
 2727: sub subscribe {
 2728:     my ($userinput,$clientip)=@_;
 2729:     my $result;
 2730:     my ($cmd,$fname)=split(/:/,$userinput);
 2731:     my $ownership=&ishome($fname);
 2732:     if ($ownership eq 'owner') {
 2733: # explitly asking for the current version?
 2734:         unless (-e $fname) {
 2735:             my $currentversion=&currentversion($fname);
 2736: 	    if (&thisversion($fname)==$currentversion) {
 2737:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 2738: 		    my $root=$1;
 2739:                     my $extension=$2;
 2740:                     symlink($root.'.'.$extension,
 2741:                             $root.'.'.$currentversion.'.'.$extension);
 2742:                     unless ($extension=~/\.meta$/) {
 2743:                        symlink($root.'.'.$extension.'.meta',
 2744:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 2745: 		    }
 2746:                 }
 2747:             }
 2748:         }
 2749: 	if (-e $fname) {
 2750: 	    if (-d $fname) {
 2751: 		$result="directory\n";
 2752: 	    } else {
 2753: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
 2754: 		my $now=time;
 2755: 		my $found=&addline($fname,$clientname,$clientip,
 2756: 				   "$clientname:$clientip:$now\n");
 2757: 		if ($found) { $result="$fname\n"; }
 2758: 		# if they were subscribed to only meta data, delete that
 2759:                 # subscription, when you subscribe to a file you also get
 2760:                 # the metadata
 2761: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 2762: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 2763: 		$fname="http://$thisserver/".$fname;
 2764: 		$result="$fname\n";
 2765: 	    }
 2766: 	} else {
 2767: 	    $result="not_found\n";
 2768: 	}
 2769:     } else {
 2770: 	$result="rejected\n";
 2771:     }
 2772:     return $result;
 2773: }
 2774: 
 2775: sub make_passwd_file {
 2776:     my ($uname, $umode,$npass,$passfilename)=@_;
 2777:     my $result="ok\n";
 2778:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 2779: 	{
 2780: 	    my $pf = IO::File->new(">$passfilename");
 2781: 	    print $pf "$umode:$npass\n";
 2782: 	}
 2783:     } elsif ($umode eq 'internal') {
 2784: 	my $salt=time;
 2785: 	$salt=substr($salt,6,2);
 2786: 	my $ncpass=crypt($npass,$salt);
 2787: 	{
 2788: 	    &Debug("Creating internal auth");
 2789: 	    my $pf = IO::File->new(">$passfilename");
 2790: 	    print $pf "internal:$ncpass\n"; 
 2791: 	}
 2792:     } elsif ($umode eq 'localauth') {
 2793: 	{
 2794: 	    my $pf = IO::File->new(">$passfilename");
 2795: 	    print $pf "localauth:$npass\n";
 2796: 	}
 2797:     } elsif ($umode eq 'unix') {
 2798: 	{
 2799: 	    my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
 2800: 	    {
 2801: 		&Debug("Executing external: ".$execpath);
 2802: 		&Debug("user  = ".$uname.", Password =". $npass);
 2803: 		my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
 2804: 		print $se "$uname\n";
 2805: 		print $se "$npass\n";
 2806: 		print $se "$npass\n";
 2807: 	    }
 2808: 	    my $useraddok = $?;
 2809: 	    if($useraddok > 0) {
 2810: 		&logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
 2811: 	    }
 2812: 	    my $pf = IO::File->new(">$passfilename");
 2813: 	    print $pf "unix:\n";
 2814: 	}
 2815:     } elsif ($umode eq 'none') {
 2816: 	{
 2817: 	    my $pf = IO::File->new(">$passfilename");
 2818: 	    print $pf "none:\n";
 2819: 	}
 2820:     } else {
 2821: 	$result="auth_mode_error\n";
 2822:     }
 2823:     return $result;
 2824: }
 2825: 
 2826: sub sethost {
 2827:     my ($remotereq) = @_;
 2828:     my (undef,$hostid)=split(/:/,$remotereq);
 2829:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
 2830:     if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
 2831: 	$currenthostid=$hostid;
 2832: 	$currentdomainid=$hostdom{$hostid};
 2833: 	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
 2834:     } else {
 2835: 	&logthis("Requested host id $hostid not an alias of ".
 2836: 		 $perlvar{'lonHostID'}." refusing connection");
 2837: 	return 'unable_to_set';
 2838:     }
 2839:     return 'ok';
 2840: }
 2841: 
 2842: sub version {
 2843:     my ($userinput)=@_;
 2844:     $remoteVERSION=(split(/:/,$userinput))[1];
 2845:     return "version:$VERSION";
 2846: }
 2847: 
 2848: #There is a copy of this in lonnet.pm
 2849: sub userload {
 2850:     my $numusers=0;
 2851:     {
 2852: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 2853: 	my $filename;
 2854: 	my $curtime=time;
 2855: 	while ($filename=readdir(LONIDS)) {
 2856: 	    if ($filename eq '.' || $filename eq '..') {next;}
 2857: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 2858: 	    if ($curtime-$mtime < 1800) { $numusers++; }
 2859: 	}
 2860: 	closedir(LONIDS);
 2861:     }
 2862:     my $userloadpercent=0;
 2863:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 2864:     if ($maxuserload) {
 2865: 	$userloadpercent=100*$numusers/$maxuserload;
 2866:     }
 2867:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 2868:     return $userloadpercent;
 2869: }
 2870: 
 2871: # ----------------------------------- POD (plain old documentation, CPAN style)
 2872: 
 2873: =head1 NAME
 2874: 
 2875: lond - "LON Daemon" Server (port "LOND" 5663)
 2876: 
 2877: =head1 SYNOPSIS
 2878: 
 2879: Usage: B<lond>
 2880: 
 2881: Should only be run as user=www.  This is a command-line script which
 2882: is invoked by B<loncron>.  There is no expectation that a typical user
 2883: will manually start B<lond> from the command-line.  (In other words,
 2884: DO NOT START B<lond> YOURSELF.)
 2885: 
 2886: =head1 DESCRIPTION
 2887: 
 2888: There are two characteristics associated with the running of B<lond>,
 2889: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 2890: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 2891: subscriptions, etc).  These are described in two large
 2892: sections below.
 2893: 
 2894: B<PROCESS MANAGEMENT>
 2895: 
 2896: Preforker - server who forks first. Runs as a daemon. HUPs.
 2897: Uses IDEA encryption
 2898: 
 2899: B<lond> forks off children processes that correspond to the other servers
 2900: in the network.  Management of these processes can be done at the
 2901: parent process level or the child process level.
 2902: 
 2903: B<logs/lond.log> is the location of log messages.
 2904: 
 2905: The process management is now explained in terms of linux shell commands,
 2906: subroutines internal to this code, and signal assignments:
 2907: 
 2908: =over 4
 2909: 
 2910: =item *
 2911: 
 2912: PID is stored in B<logs/lond.pid>
 2913: 
 2914: This is the process id number of the parent B<lond> process.
 2915: 
 2916: =item *
 2917: 
 2918: SIGTERM and SIGINT
 2919: 
 2920: Parent signal assignment:
 2921:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 2922: 
 2923: Child signal assignment:
 2924:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 2925: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 2926:  to restart a new child.)
 2927: 
 2928: Command-line invocations:
 2929:  B<kill> B<-s> SIGTERM I<PID>
 2930:  B<kill> B<-s> SIGINT I<PID>
 2931: 
 2932: Subroutine B<HUNTSMAN>:
 2933:  This is only invoked for the B<lond> parent I<PID>.
 2934: This kills all the children, and then the parent.
 2935: The B<lonc.pid> file is cleared.
 2936: 
 2937: =item *
 2938: 
 2939: SIGHUP
 2940: 
 2941: Current bug:
 2942:  This signal can only be processed the first time
 2943: on the parent process.  Subsequent SIGHUP signals
 2944: have no effect.
 2945: 
 2946: Parent signal assignment:
 2947:  $SIG{HUP}  = \&HUPSMAN;
 2948: 
 2949: Child signal assignment:
 2950:  none (nothing happens)
 2951: 
 2952: Command-line invocations:
 2953:  B<kill> B<-s> SIGHUP I<PID>
 2954: 
 2955: Subroutine B<HUPSMAN>:
 2956:  This is only invoked for the B<lond> parent I<PID>,
 2957: This kills all the children, and then the parent.
 2958: The B<lond.pid> file is cleared.
 2959: 
 2960: =item *
 2961: 
 2962: SIGUSR1
 2963: 
 2964: Parent signal assignment:
 2965:  $SIG{USR1} = \&USRMAN;
 2966: 
 2967: Child signal assignment:
 2968:  $SIG{USR1}= \&logstatus;
 2969: 
 2970: Command-line invocations:
 2971:  B<kill> B<-s> SIGUSR1 I<PID>
 2972: 
 2973: Subroutine B<USRMAN>:
 2974:  When invoked for the B<lond> parent I<PID>,
 2975: SIGUSR1 is sent to all the children, and the status of
 2976: each connection is logged.
 2977: 
 2978: =item *
 2979: 
 2980: SIGUSR2
 2981: 
 2982: Parent Signal assignment:
 2983:     $SIG{USR2} = \&UpdateHosts
 2984: 
 2985: Child signal assignment:
 2986:     NONE
 2987: 
 2988: 
 2989: =item *
 2990: 
 2991: SIGCHLD
 2992: 
 2993: Parent signal assignment:
 2994:  $SIG{CHLD} = \&REAPER;
 2995: 
 2996: Child signal assignment:
 2997:  none
 2998: 
 2999: Command-line invocations:
 3000:  B<kill> B<-s> SIGCHLD I<PID>
 3001: 
 3002: Subroutine B<REAPER>:
 3003:  This is only invoked for the B<lond> parent I<PID>.
 3004: Information pertaining to the child is removed.
 3005: The socket port is cleaned up.
 3006: 
 3007: =back
 3008: 
 3009: B<SERVER-SIDE ACTIVITIES>
 3010: 
 3011: Server-side information can be accepted in an encrypted or non-encrypted
 3012: method.
 3013: 
 3014: =over 4
 3015: 
 3016: =item ping
 3017: 
 3018: Query a client in the hosts.tab table; "Are you there?"
 3019: 
 3020: =item pong
 3021: 
 3022: Respond to a ping query.
 3023: 
 3024: =item ekey
 3025: 
 3026: Read in encrypted key, make cipher.  Respond with a buildkey.
 3027: 
 3028: =item load
 3029: 
 3030: Respond with CPU load based on a computation upon /proc/loadavg.
 3031: 
 3032: =item currentauth
 3033: 
 3034: Reply with current authentication information (only over an
 3035: encrypted channel).
 3036: 
 3037: =item auth
 3038: 
 3039: Only over an encrypted channel, reply as to whether a user's
 3040: authentication information can be validated.
 3041: 
 3042: =item passwd
 3043: 
 3044: Allow for a password to be set.
 3045: 
 3046: =item makeuser
 3047: 
 3048: Make a user.
 3049: 
 3050: =item passwd
 3051: 
 3052: Allow for authentication mechanism and password to be changed.
 3053: 
 3054: =item home
 3055: 
 3056: Respond to a question "are you the home for a given user?"
 3057: 
 3058: =item update
 3059: 
 3060: Update contents of a subscribed resource.
 3061: 
 3062: =item unsubscribe
 3063: 
 3064: The server is unsubscribing from a resource.
 3065: 
 3066: =item subscribe
 3067: 
 3068: The server is subscribing to a resource.
 3069: 
 3070: =item log
 3071: 
 3072: Place in B<logs/lond.log>
 3073: 
 3074: =item put
 3075: 
 3076: stores hash in namespace
 3077: 
 3078: =item rolesput
 3079: 
 3080: put a role into a user's environment
 3081: 
 3082: =item get
 3083: 
 3084: returns hash with keys from array
 3085: reference filled in from namespace
 3086: 
 3087: =item eget
 3088: 
 3089: returns hash with keys from array
 3090: reference filled in from namesp (encrypts the return communication)
 3091: 
 3092: =item rolesget
 3093: 
 3094: get a role from a user's environment
 3095: 
 3096: =item del
 3097: 
 3098: deletes keys out of array from namespace
 3099: 
 3100: =item keys
 3101: 
 3102: returns namespace keys
 3103: 
 3104: =item dump
 3105: 
 3106: dumps the complete (or key matching regexp) namespace into a hash
 3107: 
 3108: =item store
 3109: 
 3110: stores hash permanently
 3111: for this url; hashref needs to be given and should be a \%hashname; the
 3112: remaining args aren't required and if they aren't passed or are '' they will
 3113: be derived from the ENV
 3114: 
 3115: =item restore
 3116: 
 3117: returns a hash for a given url
 3118: 
 3119: =item querysend
 3120: 
 3121: Tells client about the lonsql process that has been launched in response
 3122: to a sent query.
 3123: 
 3124: =item queryreply
 3125: 
 3126: Accept information from lonsql and make appropriate storage in temporary
 3127: file space.
 3128: 
 3129: =item idput
 3130: 
 3131: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 3132: for each student, defined perhaps by the institutional Registrar.)
 3133: 
 3134: =item idget
 3135: 
 3136: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 3137: for each student, defined perhaps by the institutional Registrar.)
 3138: 
 3139: =item tmpput
 3140: 
 3141: Accept and store information in temporary space.
 3142: 
 3143: =item tmpget
 3144: 
 3145: Send along temporarily stored information.
 3146: 
 3147: =item ls
 3148: 
 3149: List part of a user's directory.
 3150: 
 3151: =item pushtable
 3152: 
 3153: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
 3154: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
 3155: must be restored manually in case of a problem with the new table file.
 3156: pushtable requires that the request be encrypted and validated via
 3157: ValidateManager.  The form of the command is:
 3158: enc:pushtable tablename <tablecontents> \n
 3159: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
 3160: cleartext newline.
 3161: 
 3162: =item Hanging up (exit or init)
 3163: 
 3164: What to do when a client tells the server that they (the client)
 3165: are leaving the network.
 3166: 
 3167: =item unknown command
 3168: 
 3169: If B<lond> is sent an unknown command (not in the list above),
 3170: it replys to the client "unknown_cmd".
 3171: 
 3172: 
 3173: =item UNKNOWN CLIENT
 3174: 
 3175: If the anti-spoofing algorithm cannot verify the client,
 3176: the client is rejected (with a "refused" message sent
 3177: to the client, and the connection is closed.
 3178: 
 3179: =back
 3180: 
 3181: =head1 PREREQUISITES
 3182: 
 3183: IO::Socket
 3184: IO::File
 3185: Apache::File
 3186: Symbol
 3187: POSIX
 3188: Crypt::IDEA
 3189: LWP::UserAgent()
 3190: GDBM_File
 3191: Authen::Krb4
 3192: Authen::Krb5
 3193: 
 3194: =head1 COREQUISITES
 3195: 
 3196: =head1 OSNAMES
 3197: 
 3198: linux
 3199: 
 3200: =head1 SCRIPT CATEGORIES
 3201: 
 3202: Server/Process
 3203: 
 3204: =cut

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