Annotation of loncom/lond, revision 1.152

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

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