File:  [LON-CAPA] / loncom / lond
Revision 1.143: download - view: text, annotated - select for diffs
Mon Sep 15 10:03:52 2003 UTC (20 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Completed and tested code for pushfile.

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

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