Annotation of loncom/lond, revision 1.192

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

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