Annotation of loncom/lond, revision 1.150

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

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