File:  [LON-CAPA] / loncom / lond
Revision 1.156: download - view: text, annotated - select for diffs
Mon Oct 13 08:49:54 2003 UTC (20 years, 6 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Add host based authentication.

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

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