File:  [LON-CAPA] / loncom / lond
Revision 1.147: download - view: text, annotated - select for diffs
Tue Sep 23 11:23:31 2003 UTC (20 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Comlplete implementation of reinit functionality.  Must still implement
the actual initialization functionality, but the process can now
receive the request and either invoke the appropriate internal function or
signal the correct lonc.

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

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