File:  [LON-CAPA] / loncom / lond
Revision 1.166: download - view: text, annotated - select for diffs
Mon Dec 22 11:03:37 2003 UTC (20 years, 4 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Skeletal support for edit subcommand.

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

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