File:  [LON-CAPA] / loncom / lond
Revision 1.149: download - view: text, annotated - select for diffs
Tue Sep 30 09:44:13 2003 UTC (20 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Tested UpdateHosts ability to
- Remove live children for hosts that are no longer in the hosts.tab
- Remove live children for hosts whose IPs have changed in the hosts.tab

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

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