Annotation of loncom/lond, revision 1.149

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

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