Annotation of loncom/lond, revision 1.157

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

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