File:  [LON-CAPA] / loncom / lond
Revision 1.144: download - view: text, annotated - select for diffs
Tue Sep 16 09:47:01 2003 UTC (20 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Added skeletal support for SIGUSR2 (update hosts.tab)

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

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