File:  [LON-CAPA] / loncom / lond
Revision 1.145: download - view: text, annotated - select for diffs
Tue Sep 16 10:13:20 2003 UTC (20 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Added ReinitProcess function to oversee the parsing and processing of the
reinit:<process> client request.

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

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