File:  [LON-CAPA] / loncom / lond
Revision 1.142: download - view: text, annotated - select for diffs
Tue Sep 9 20:47:46 2003 UTC (20 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Permanently store chatroom entries in chatroom.log

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

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