Annotation of loncom/lond, revision 1.158

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

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