File:  [LON-CAPA] / loncom / lond
Revision 1.71: download - view: text, annotated - select for diffs
Tue Feb 12 23:08:27 2002 UTC (22 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Hopefully avoid null byte problem

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.71 2002/02/12 23:08:27 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/26 Scott Harrison
   35: # 06/29,06/30,07/14,07/15,07/17,07/20,07/25,09/18 Gerd Kortemeyer
   36: # 12/05 Scott Harrison
   37: # 12/05,12/13,12/29 Gerd Kortemeyer
   38: # YEAR=2001
   39: # Jan 01 Scott Harrison
   40: # 02/12 Gerd Kortemeyer
   41: # 03/15 Scott Harrison
   42: # 03/24 Gerd Kortemeyer
   43: # 04/02 Scott Harrison
   44: # 05/11,05/28,08/30 Gerd Kortemeyer
   45: # 9/30,10/22,11/13,11/15,11/16 Scott Harrison
   46: # 11/26,11/27 Gerd Kortemeyer
   47: # 12/20 Scott Harrison
   48: # 12/22 Gerd Kortemeyer
   49: # YEAR=2002
   50: # 01/20/02,02/05 Gerd Kortemeyer
   51: # 02/05 Guy Albertelli
   52: # 02/07 Scott Harrison
   53: # 02/12 Gerd Kortemeyer
   54: ###
   55: 
   56: # based on "Perl Cookbook" ISBN 1-56592-243-3
   57: # preforker - server who forks first
   58: # runs as a daemon
   59: # HUPs
   60: # uses IDEA encryption
   61: 
   62: use IO::Socket;
   63: use IO::File;
   64: use Apache::File;
   65: use Symbol;
   66: use POSIX;
   67: use Crypt::IDEA;
   68: use LWP::UserAgent();
   69: use GDBM_File;
   70: use Authen::Krb4;
   71: use lib '/home/httpd/lib/perl/';
   72: use localauth;
   73: 
   74: my $status='';
   75: my $lastlog='';
   76: 
   77: # grabs exception and records it to log before exiting
   78: sub catchexception {
   79:     my ($error)=@_;
   80:     $SIG{'QUIT'}='DEFAULT';
   81:     $SIG{__DIE__}='DEFAULT';
   82:     &logthis("<font color=red>CRITICAL: "
   83:      ."ABNORMAL EXIT. Child $$ for server $wasserver died through "
   84:      ."a crash with this error msg->[$error]</font>");
   85:     &logthis('Famous last words: '.$status.' - '.$lastlog);
   86:     if ($client) { print $client "error: $error\n"; }
   87:     $server->close();
   88:     die($error);
   89: }
   90: 
   91: sub timeout {
   92:     &logthis("<font color=ref>CRITICAL: TIME OUT ".$$."</font>");
   93:     &catchexception('Timeout');
   94: }
   95: # -------------------------------- Set signal handlers to record abnormal exits
   96: 
   97: $SIG{'QUIT'}=\&catchexception;
   98: $SIG{__DIE__}=\&catchexception;
   99: 
  100: # ------------------------------------ Read httpd access.conf and get variables
  101: 
  102: open (CONFIG,"/etc/httpd/conf/access.conf") || die "Can't read access.conf";
  103: 
  104: while ($configline=<CONFIG>) {
  105:     if ($configline =~ /PerlSetVar/) {
  106: 	my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
  107:         chomp($varvalue);
  108:         $perlvar{$varname}=$varvalue;
  109:     }
  110: }
  111: close(CONFIG);
  112: 
  113: # ----------------------------- Make sure this process is running from user=www
  114: my $wwwid=getpwnam('www');
  115: if ($wwwid!=$<) {
  116:    $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  117:    $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
  118:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
  119:  mailto $emailto -s '$subj' > /dev/null");
  120:    exit 1;
  121: }
  122: 
  123: # --------------------------------------------- Check if other instance running
  124: 
  125: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
  126: 
  127: if (-e $pidfile) {
  128:    my $lfh=IO::File->new("$pidfile");
  129:    my $pide=<$lfh>;
  130:    chomp($pide);
  131:    if (kill 0 => $pide) { die "already running"; }
  132: }
  133: 
  134: $PREFORK=4; # number of children to maintain, at least four spare
  135: 
  136: # ------------------------------------------------------------- Read hosts file
  137: 
  138: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
  139: 
  140: while ($configline=<CONFIG>) {
  141:     my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
  142:     chomp($ip); $ip=~s/\D+$//;
  143:     $hostid{$ip}=$id;
  144:     if ($id eq $perlvar{'lonHostID'}) { $thisserver=$name; }
  145:     $PREFORK++;
  146: }
  147: close(CONFIG);
  148: 
  149: # establish SERVER socket, bind and listen.
  150: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
  151:                                 Type      => SOCK_STREAM,
  152:                                 Proto     => 'tcp',
  153:                                 Reuse     => 1,
  154:                                 Listen    => 10 )
  155:   or die "making socket: $@\n";
  156: 
  157: # --------------------------------------------------------- Do global variables
  158: 
  159: # global variables
  160: 
  161: $MAX_CLIENTS_PER_CHILD  = 5;        # number of clients each child should 
  162:                                     # process
  163: %children               = ();       # keys are current child process IDs
  164: $children               = 0;        # current number of children
  165: 
  166: sub REAPER {                        # takes care of dead children
  167:     $SIG{CHLD} = \&REAPER;
  168:     my $pid = wait;
  169:     if (defined($children{$pid})) {
  170: 	&logthis("Child $pid died");
  171: 	$children --;
  172: 	delete $children{$pid};
  173:     } else {
  174: 	&logthis("Unknown Child $pid died");
  175:     }
  176: }
  177: 
  178: sub HUNTSMAN {                      # signal handler for SIGINT
  179:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  180:     kill 'INT' => keys %children;
  181:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
  182:     my $execdir=$perlvar{'lonDaemons'};
  183:     unlink("$execdir/logs/lond.pid");
  184:     &logthis("<font color=red>CRITICAL: Shutting down</font>");
  185:     exit;                           # clean up with dignity
  186: }
  187: 
  188: sub HUPSMAN {                      # signal handler for SIGHUP
  189:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
  190:     kill 'INT' => keys %children;
  191:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
  192:     &logthis("<font color=red>CRITICAL: Restarting</font>");
  193:     unlink("$execdir/logs/lond.pid");
  194:     my $execdir=$perlvar{'lonDaemons'};
  195:     exec("$execdir/lond");         # here we go again
  196: }
  197: 
  198: sub checkchildren {
  199:     &initnewstatus();
  200:     &logstatus();
  201:     &logthis('Going to check on the children');
  202:     $docdir=$perlvar{'lonDocRoot'};
  203:     foreach (sort keys %children) {
  204: 	sleep 1;
  205:         unless (kill 'USR1' => $_) {
  206: 	    &logthis ('Child '.$_.' is dead');
  207:             &logstatus($$.' is dead');
  208:         } 
  209:     }
  210:     sleep 5;
  211:     foreach (sort keys %children) {
  212:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
  213: 	    &logthis('Child '.$_.' did not respond');
  214: 	    kill 9 => $_;
  215: 	    $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  216: 	    $subj="LON: $perlvar{'lonHostID'} killed lond process $_";
  217: 	    my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
  218: 	    $execdir=$perlvar{'lonDaemons'};
  219: 	    $result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`
  220:         }
  221:     }
  222: }
  223: 
  224: # --------------------------------------------------------------------- Logging
  225: 
  226: sub logthis {
  227:     my $message=shift;
  228:     my $execdir=$perlvar{'lonDaemons'};
  229:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
  230:     my $now=time;
  231:     my $local=localtime($now);
  232:     $lastlog=$local.': '.$message;
  233:     print $fh "$local ($$): $message\n";
  234: }
  235: 
  236: # ------------------------------------------------------------------ Log status
  237: 
  238: sub logstatus {
  239:     my $docdir=$perlvar{'lonDocRoot'};
  240:     {
  241:     my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
  242:     print $fh $$."\t".$status."\t".$lastlog."\n";
  243:     $fh->close();
  244:     }
  245:     {
  246: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
  247:         print $fh $status."\n".$lastlog."\n".time;
  248:         $fh->close();
  249:     }
  250: }
  251: 
  252: sub initnewstatus {
  253:     my $docdir=$perlvar{'lonDocRoot'};
  254:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
  255:     my $now=time;
  256:     my $local=localtime($now);
  257:     print $fh "LOND status $local - parent $$\n\n";
  258:     opendir(DIR,"$docdir/lon-status/londchld");
  259:     while ($filename=readdir(DIR)) {
  260:         unlink("$docdir/lon-status/londchld/$filename");
  261:     }
  262:     closedir(DIR);
  263: }
  264: 
  265: # -------------------------------------------------------------- Status setting
  266: 
  267: sub status {
  268:     my $what=shift;
  269:     my $now=time;
  270:     my $local=localtime($now);
  271:     $status=$local.': '.$what;
  272: }
  273: 
  274: # -------------------------------------------------------- Escape Special Chars
  275: 
  276: sub escape {
  277:     my $str=shift;
  278:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  279:     return $str;
  280: }
  281: 
  282: # ----------------------------------------------------- Un-Escape Special Chars
  283: 
  284: sub unescape {
  285:     my $str=shift;
  286:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  287:     return $str;
  288: }
  289: 
  290: # ----------------------------------------------------------- Send USR1 to lonc
  291: 
  292: sub reconlonc {
  293:     my $peerfile=shift;
  294:     &logthis("Trying to reconnect for $peerfile");
  295:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  296:     if (my $fh=IO::File->new("$loncfile")) {
  297: 	my $loncpid=<$fh>;
  298:         chomp($loncpid);
  299:         if (kill 0 => $loncpid) {
  300: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  301:             kill USR1 => $loncpid;
  302:             sleep 1;
  303:             if (-e "$peerfile") { return; }
  304:             &logthis("$peerfile still not there, give it another try");
  305:             sleep 5;
  306:             if (-e "$peerfile") { return; }
  307:             &logthis(
  308:  "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  309:         } else {
  310: 	    &logthis(
  311:               "<font color=red>CRITICAL: "
  312:              ."lonc at pid $loncpid not responding, giving up</font>");
  313:         }
  314:     } else {
  315:       &logthis('<font color=red>CRITICAL: lonc not running, giving up</font>');
  316:     }
  317: }
  318: 
  319: # -------------------------------------------------- Non-critical communication
  320: 
  321: sub subreply {
  322:     my ($cmd,$server)=@_;
  323:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  324:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  325:                                       Type    => SOCK_STREAM,
  326:                                       Timeout => 10)
  327:        or return "con_lost";
  328:     print $sclient "$cmd\n";
  329:     my $answer=<$sclient>;
  330:     chomp($answer);
  331:     if (!$answer) { $answer="con_lost"; }
  332:     return $answer;
  333: }
  334: 
  335: sub reply {
  336:   my ($cmd,$server)=@_;
  337:   my $answer;
  338:   if ($server ne $perlvar{'lonHostID'}) { 
  339:     $answer=subreply($cmd,$server);
  340:     if ($answer eq 'con_lost') {
  341: 	$answer=subreply("ping",$server);
  342:         if ($answer ne $server) {
  343:            &reconlonc("$perlvar{'lonSockDir'}/$server");
  344:         }
  345:         $answer=subreply($cmd,$server);
  346:     }
  347:   } else {
  348:     $answer='self_reply';
  349:   } 
  350:   return $answer;
  351: }
  352: 
  353: # -------------------------------------------------------------- Talk to lonsql
  354: 
  355: sub sqlreply {
  356:     my ($cmd)=@_;
  357:     my $answer=subsqlreply($cmd);
  358:     if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
  359:     return $answer;
  360: }
  361: 
  362: sub subsqlreply {
  363:     my ($cmd)=@_;
  364:     my $unixsock="mysqlsock";
  365:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
  366:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  367:                                       Type    => SOCK_STREAM,
  368:                                       Timeout => 10)
  369:        or return "con_lost";
  370:     print $sclient "$cmd\n";
  371:     my $answer=<$sclient>;
  372:     chomp($answer);
  373:     if (!$answer) { $answer="con_lost"; }
  374:     return $answer;
  375: }
  376: 
  377: # -------------------------------------------- Return path to profile directory
  378: 
  379: sub propath {
  380:     my ($udom,$uname)=@_;
  381:     $udom=~s/\W//g;
  382:     $uname=~s/\W//g;
  383:     my $subdir=$uname.'__';
  384:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  385:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  386:     return $proname;
  387: } 
  388: 
  389: # --------------------------------------- Is this the home server of an author?
  390: 
  391: sub ishome {
  392:     my $author=shift;
  393:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  394:     my ($udom,$uname)=split(/\//,$author);
  395:     my $proname=propath($udom,$uname);
  396:     if (-e $proname) {
  397: 	return 'owner';
  398:     } else {
  399:         return 'not_owner';
  400:     }
  401: }
  402: 
  403: # ======================================================= Continue main program
  404: # ---------------------------------------------------- Fork once and dissociate
  405: 
  406: $fpid=fork;
  407: exit if $fpid;
  408: die "Couldn't fork: $!" unless defined ($fpid);
  409: 
  410: POSIX::setsid() or die "Can't start new session: $!";
  411: 
  412: # ------------------------------------------------------- Write our PID on disk
  413: 
  414: $execdir=$perlvar{'lonDaemons'};
  415: open (PIDSAVE,">$execdir/logs/lond.pid");
  416: print PIDSAVE "$$\n";
  417: close(PIDSAVE);
  418: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
  419: &status('Starting');
  420: 
  421: # ------------------------------------------------------- Now we are on our own
  422:     
  423: # Fork off our children.
  424: for (1 .. $PREFORK) {
  425:     make_new_child();
  426: }
  427: 
  428: # ----------------------------------------------------- Install signal handlers
  429: 
  430: &status('Forked children');
  431: 
  432: $SIG{CHLD} = \&REAPER;
  433: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  434: $SIG{HUP}  = \&HUPSMAN;
  435: $SIG{USR1} = \&checkchildren;
  436: 
  437: # And maintain the population.
  438: while (1) {
  439:     &status('Sleeping');
  440:     sleep;                          # wait for a signal (i.e., child's death)
  441:     &logthis('Woke up');
  442:     &status('Woke up');
  443:     for ($i = $children; $i < $PREFORK; $i++) {
  444:         make_new_child();           # top up the child pool
  445:     }
  446: }
  447: 
  448: sub make_new_child {
  449:     my $pid;
  450:     my $cipher;
  451:     my $sigset;
  452:     &logthis("Attempting to start child");    
  453:     # block signal for fork
  454:     $sigset = POSIX::SigSet->new(SIGINT);
  455:     sigprocmask(SIG_BLOCK, $sigset)
  456:         or die "Can't block SIGINT for fork: $!\n";
  457:     
  458:     die "fork: $!" unless defined ($pid = fork);
  459:     
  460:     if ($pid) {
  461:         # Parent records the child's birth and returns.
  462:         sigprocmask(SIG_UNBLOCK, $sigset)
  463:             or die "Can't unblock SIGINT for fork: $!\n";
  464:         $children{$pid} = 1;
  465:         $children++;
  466:         &status('Started child '.$pid);
  467:         return;
  468:     } else {
  469:         # Child can *not* return from this subroutine.
  470:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  471:         $SIG{USR1}= \&logstatus;
  472:         $SIG{ALRM}= \&timeout;
  473:         $lastlog='Forked ';
  474:         $status='Forked';
  475: 
  476:         # unblock signals
  477:         sigprocmask(SIG_UNBLOCK, $sigset)
  478:             or die "Can't unblock SIGINT for fork: $!\n";
  479: 
  480:         $tmpsnum=0;
  481:     
  482:         # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
  483:         for ($i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
  484:             &status('Idle, waiting for connection');
  485:             $client = $server->accept()     or last;
  486:             &status('Accepted connection');
  487: # =============================================================================
  488:             # do something with the connection
  489: # -----------------------------------------------------------------------------
  490:             # see if we know client and check for spoof IP by challenge
  491:             my $caller=getpeername($client);
  492:             my ($port,$iaddr)=unpack_sockaddr_in($caller);
  493:             my $clientip=inet_ntoa($iaddr);
  494:             my $clientrec=($hostid{$clientip} ne undef);
  495:             &logthis(
  496: "<font color=yellow>INFO: Connection $i, $clientip ($hostid{$clientip})</font>"
  497:             );
  498:             &status("Connecting $clientip ($hostid{$clientip})"); 
  499:             my $clientok;
  500:             if ($clientrec) {
  501: 	      &status("Waiting for init from $clientip ($hostid{$clientip})");
  502: 	      my $remotereq=<$client>;
  503:               $remotereq=~s/\W//g;
  504:               if ($remotereq eq 'init') {
  505: 		  my $challenge="$$".time;
  506:                   print $client "$challenge\n";
  507:                   &status(
  508:            "Waiting for challenge reply from $clientip ($hostid{$clientip})"); 
  509:                   $remotereq=<$client>;
  510:                   $remotereq=~s/\W//g;
  511:                   if ($challenge eq $remotereq) {
  512: 		      $clientok=1;
  513:                       print $client "ok\n";
  514:                   } else {
  515: 		      &logthis(
  516:  "<font color=blue>WARNING: $clientip did not reply challenge</font>");
  517:                       &status('No challenge reply '.$clientip);
  518:                   }
  519:               } else {
  520: 		  &logthis(
  521:                     "<font color=blue>WARNING: "
  522:                    ."$clientip failed to initialize: >$remotereq< </font>");
  523:                   &status('No init '.$clientip);
  524:               }
  525: 	    } else {
  526:               &logthis(
  527:  "<font color=blue>WARNING: Unknown client $clientip</font>");
  528:               &status('Hung up on '.$clientip);
  529:             }
  530:             if ($clientok) {
  531: # ---------------- New known client connecting, could mean machine online again
  532: 	      &reconlonc("$perlvar{'lonSockDir'}/$hostid{$clientip}");
  533:               &logthis(
  534:        "<font color=green>Established connection: $hostid{$clientip}</font>");
  535:               &status('Will listen to '.$hostid{$clientip});
  536: # ------------------------------------------------------------ Process requests
  537:               while (my $userinput=<$client>) {
  538:                 chomp($userinput);
  539:                 &status('Processing '.$hostid{$clientip}.': '.$userinput);
  540:                 my $wasenc=0;
  541:                 alarm(120);
  542: # ------------------------------------------------------------ See if encrypted
  543: 		if ($userinput =~ /^enc/) {
  544: 		  if ($cipher) {
  545:                     my ($cmd,$cmdlength,$encinput)=split(/:/,$userinput);
  546: 		    $userinput='';
  547:                     for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
  548:                        $userinput.=
  549: 			   $cipher->decrypt(
  550:                             pack("H16",substr($encinput,$encidx,16))
  551:                            );
  552: 		    }
  553: 		    $userinput=substr($userinput,0,$cmdlength);
  554:                     $wasenc=1;
  555: 		  }
  556: 		}
  557: # ------------------------------------------------------------- Normal commands
  558: # ------------------------------------------------------------------------ ping
  559: 		   if ($userinput =~ /^ping/) {
  560:                        print $client "$perlvar{'lonHostID'}\n";
  561: # ------------------------------------------------------------------------ pong
  562: 		   } elsif ($userinput =~ /^pong/) {
  563:                        $reply=reply("ping",$hostid{$clientip});
  564:                        print $client "$perlvar{'lonHostID'}:$reply\n"; 
  565: # ------------------------------------------------------------------------ ekey
  566: 		   } elsif ($userinput =~ /^ekey/) {
  567:                        my $buildkey=time.$$.int(rand 100000);
  568:                        $buildkey=~tr/1-6/A-F/;
  569:                        $buildkey=int(rand 100000).$buildkey.int(rand 100000);
  570:                        my $key=$perlvar{'lonHostID'}.$hostid{$clientip};
  571:                        $key=~tr/a-z/A-Z/;
  572:                        $key=~tr/G-P/0-9/;
  573:                        $key=~tr/Q-Z/0-9/;
  574:                        $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
  575:                        $key=substr($key,0,32);
  576:                        my $cipherkey=pack("H32",$key);
  577:                        $cipher=new IDEA $cipherkey;
  578:                        print $client "$buildkey\n"; 
  579: # ------------------------------------------------------------------------ load
  580: 		   } elsif ($userinput =~ /^load/) {
  581:                        my $loadavg;
  582:                        {
  583:                           my $loadfile=IO::File->new('/proc/loadavg');
  584:                           $loadavg=<$loadfile>;
  585:                        }
  586:                        $loadavg =~ s/\s.*//g;
  587:                        my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
  588: 		       print $client "$loadpercent\n";
  589: # ----------------------------------------------------------------- currentauth
  590: 		   } elsif ($userinput =~ /^currentauth/) {
  591: 		     if ($wasenc==1) {
  592:                        my ($cmd,$udom,$uname)=split(/:/,$userinput);
  593:                        my $proname=propath($udom,$uname);
  594:                        my $passfilename="$proname/passwd";
  595:                        if (-e $passfilename) {
  596: 			   my $pf = IO::File->new($passfilename);
  597: 			   my $realpasswd=<$pf>;
  598: 			   chomp($realpasswd);
  599: 			   my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
  600: 			   my $availablecontent='';
  601: 			   if ($howpwd eq 'krb4') {
  602: 			       $availablecontent=$contentpwd;
  603: 			   }
  604: 			   print $client "$howpwd:$availablecontent\n";
  605: 		       } else {
  606:                           print $client "unknown_user\n";
  607:                        }
  608: 		     } else {
  609: 		       print $client "refused\n";
  610: 		     }
  611: # ------------------------------------------------------------------------ auth
  612:                    } elsif ($userinput =~ /^auth/) {
  613: 		     if ($wasenc==1) {
  614:                        my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
  615:                        chomp($upass);
  616:                        $upass=unescape($upass);
  617:                        my $proname=propath($udom,$uname);
  618:                        my $passfilename="$proname/passwd";
  619:                        if (-e $passfilename) {
  620:                           my $pf = IO::File->new($passfilename);
  621:                           my $realpasswd=<$pf>;
  622:                           chomp($realpasswd);
  623:                           my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
  624:                           my $pwdcorrect=0;
  625:                           if ($howpwd eq 'internal') {
  626: 			      $pwdcorrect=
  627: 				  (crypt($upass,$contentpwd) eq $contentpwd);
  628:                           } elsif ($howpwd eq 'unix') {
  629:                               $contentpwd=(getpwnam($uname))[1];
  630: 			      my $pwauth_path="/usr/local/sbin/pwauth";
  631: 			      unless ($contentpwd eq 'x') {
  632: 				  $pwdcorrect=
  633:                                     (crypt($upass,$contentpwd) eq $contentpwd);
  634: 			      }
  635: 			      elsif (-e $pwauth_path) {
  636: 				  open PWAUTH, "|$pwauth_path" or
  637: 				      die "Cannot invoke authentication";
  638: 				  print PWAUTH "$uname\n$upass\n";
  639: 				  close PWAUTH;
  640: 				  $pwdcorrect=!$?;
  641: 			      }
  642:                           } elsif ($howpwd eq 'krb4') {
  643:                              $null=pack("C",0);
  644: 			     unless ($upass=~/$null/) {
  645:                               $pwdcorrect=(
  646:                                  Authen::Krb4::get_pw_in_tkt($uname,"",
  647:                                         $contentpwd,'krbtgt',$contentpwd,1,
  648: 							     $upass) == 0);
  649: 			     } else { $pwdcorrect=0; }
  650:                           } elsif ($howpwd eq 'localauth') {
  651: 			    $pwdcorrect=&localauth::localauth($uname,$upass,
  652: 							      $contentpwd);
  653: 			  }
  654:                           if ($pwdcorrect) {
  655:                              print $client "authorized\n";
  656:                           } else {
  657:                              print $client "non_authorized\n";
  658:                           }  
  659: 		       } else {
  660:                           print $client "unknown_user\n";
  661:                        }
  662: 		     } else {
  663: 		       print $client "refused\n";
  664: 		     }
  665: # ---------------------------------------------------------------------- passwd
  666:                    } elsif ($userinput =~ /^passwd/) {
  667: 		     if ($wasenc==1) {
  668:                        my 
  669:                        ($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
  670:                        chomp($npass);
  671:                        $upass=&unescape($upass);
  672:                        $npass=&unescape($npass);
  673:                        my $proname=propath($udom,$uname);
  674:                        my $passfilename="$proname/passwd";
  675:                        if (-e $passfilename) {
  676: 			   my $realpasswd;
  677:                           { my $pf = IO::File->new($passfilename);
  678: 			    $realpasswd=<$pf>; }
  679:                           chomp($realpasswd);
  680:                           my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
  681:                           if ($howpwd eq 'internal') {
  682: 			   if (crypt($upass,$contentpwd) eq $contentpwd) {
  683: 			     my $salt=time;
  684:                              $salt=substr($salt,6,2);
  685: 			     my $ncpass=crypt($npass,$salt);
  686:                              { my $pf = IO::File->new(">$passfilename");
  687:  	  		       print $pf "internal:$ncpass\n"; }             
  688:                              print $client "ok\n";
  689:                            } else {
  690:                              print $client "non_authorized\n";
  691:                            }
  692:                           } else {
  693:                             print $client "auth_mode_error\n";
  694:                           }  
  695: 		       } else {
  696:                           print $client "unknown_user\n";
  697:                        }
  698: 		     } else {
  699: 		       print $client "refused\n";
  700: 		     }
  701: # -------------------------------------------------------------------- makeuser
  702:                    } elsif ($userinput =~ /^makeuser/) {
  703:     	             my $oldumask=umask(0077);
  704: 		     if ($wasenc==1) {
  705:                        my 
  706:                        ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
  707:                        chomp($npass);
  708:                        $npass=&unescape($npass);
  709:                        my $proname=propath($udom,$uname);
  710:                        my $passfilename="$proname/passwd";
  711:                        if (-e $passfilename) {
  712: 			   print $client "already_exists\n";
  713:                        } elsif ($udom ne $perlvar{'lonDefDomain'}) {
  714:                            print $client "not_right_domain\n";
  715:                        } else {
  716:                            @fpparts=split(/\//,$proname);
  717:                            $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
  718:                            $fperror='';
  719:                            for ($i=3;$i<=$#fpparts;$i++) {
  720:                                $fpnow.='/'.$fpparts[$i]; 
  721:                                unless (-e $fpnow) {
  722: 				   unless (mkdir($fpnow,0777)) {
  723:                                       $fperror="error:$!";
  724:                                    }
  725:                                }
  726:                            }
  727:                            unless ($fperror) {
  728: 			     if ($umode eq 'krb4') {
  729:                                { 
  730:                                  my $pf = IO::File->new(">$passfilename");
  731:  	  		         print $pf "krb4:$npass\n"; 
  732:                                }             
  733:                                print $client "ok\n";
  734:                              } elsif ($umode eq 'internal') {
  735: 			       my $salt=time;
  736:                                $salt=substr($salt,6,2);
  737: 			       my $ncpass=crypt($npass,$salt);
  738:                                { 
  739:                                  my $pf = IO::File->new(">$passfilename");
  740:  	  		         print $pf "internal:$ncpass\n"; 
  741:                                }
  742:                                print $client "ok\n";
  743: 			     } elsif ($umode eq 'localauth') {
  744: 			       {
  745: 				 my $pf = IO::File->new(">$passfilename");
  746:   	  		         print $pf "localauth:$npass\n";
  747: 			       }
  748: 			       print $client "ok\n";
  749: 			     } elsif ($umode eq 'unix') {
  750: 			       {
  751: 				 my $execpath="$perlvar{'lonDaemons'}/".
  752: 				              "lcuseradd";
  753: 				 {
  754: 				     my $se = IO::File->new("|$execpath");
  755: 				     print $se "$uname\n";
  756: 				     print $se "$npass\n";
  757: 				     print $se "$npass\n";
  758: 				 }
  759:                                  my $pf = IO::File->new(">$passfilename");
  760:  	  		         print $pf "unix:\n"; 
  761: 			       }
  762: 			       print $client "ok\n";
  763: 			     } elsif ($umode eq 'none') {
  764:                                { 
  765:                                  my $pf = IO::File->new(">$passfilename");
  766:  	  		         print $pf "none:\n"; 
  767:                                }             
  768:                                print $client "ok\n";
  769:                              } else {
  770:                                print $client "auth_mode_error\n";
  771:                              }  
  772:                            } else {
  773:                                print $client "$fperror\n";
  774:                            }
  775:                        }
  776: 		     } else {
  777: 		       print $client "refused\n";
  778: 		     }
  779: 		     umask($oldumask);
  780: # -------------------------------------------------------------- changeuserauth
  781:                    } elsif ($userinput =~ /^changeuserauth/) {
  782: 		     if ($wasenc==1) {
  783:                        my 
  784:                        ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
  785:                        chomp($npass);
  786:                        $npass=&unescape($npass);
  787:                        my $proname=propath($udom,$uname);
  788:                        my $passfilename="$proname/passwd";
  789: 		       if ($udom ne $perlvar{'lonDefDomain'}) {
  790:                            print $client "not_right_domain\n";
  791:                        } else {
  792: 			   if ($umode eq 'krb4') {
  793:                                { 
  794: 				   my $pf = IO::File->new(">$passfilename");
  795: 				   print $pf "krb4:$npass\n"; 
  796:                                }             
  797:                                print $client "ok\n";
  798: 			   } elsif ($umode eq 'internal') {
  799: 			       my $salt=time;
  800:                                $salt=substr($salt,6,2);
  801: 			       my $ncpass=crypt($npass,$salt);
  802:                                { 
  803: 				   my $pf = IO::File->new(">$passfilename");
  804: 				   print $pf "internal:$ncpass\n"; 
  805:                                }
  806:                                print $client "ok\n";
  807: 			   } elsif ($umode eq 'localauth') {
  808: 			       {
  809: 				   my $pf = IO::File->new(">$passfilename");
  810: 				   print $pf "localauth:$npass\n";
  811: 			       }
  812: 			       print $client "ok\n";
  813: 			   } elsif ($umode eq 'unix') {
  814: 			       {
  815: 				   my $execpath="$perlvar{'lonDaemons'}/".
  816: 				       "lcuseradd";
  817: 				   {
  818: 				       my $se = IO::File->new("|$execpath");
  819: 				       print $se "$uname\n";
  820: 				       print $se "$npass\n";
  821: 				       print $se "$npass\n";
  822: 				   }
  823: 				   my $pf = IO::File->new(">$passfilename");
  824: 				   print $pf "unix:\n"; 
  825: 			       }
  826: 			       print $client "ok\n";
  827: 			   } elsif ($umode eq 'none') {
  828:                                { 
  829: 				   my $pf = IO::File->new(">$passfilename");
  830: 				   print $pf "none:\n"; 
  831:                                }             
  832:                                print $client "ok\n";
  833: 			   } else {
  834:                                print $client "auth_mode_error\n";
  835: 			   }  
  836:                        }
  837: 		     } else {
  838: 		       print $client "refused\n";
  839: 		     }
  840: # ------------------------------------------------------------------------ home
  841:                    } elsif ($userinput =~ /^home/) {
  842:                        my ($cmd,$udom,$uname)=split(/:/,$userinput);
  843:                        chomp($uname);
  844:                        my $proname=propath($udom,$uname);
  845:                        if (-e $proname) {
  846:                           print $client "found\n";
  847:                        } else {
  848: 			  print $client "not_found\n";
  849:                        }
  850: # ---------------------------------------------------------------------- update
  851:                    } elsif ($userinput =~ /^update/) {
  852:                        my ($cmd,$fname)=split(/:/,$userinput);
  853:                        my $ownership=ishome($fname);
  854:                        if ($ownership eq 'not_owner') {
  855:                         if (-e $fname) {
  856:                           my ($dev,$ino,$mode,$nlink,
  857:                               $uid,$gid,$rdev,$size,
  858:                               $atime,$mtime,$ctime,
  859:                               $blksize,$blocks)=stat($fname);
  860:                           $now=time;
  861:                           $since=$now-$atime;
  862:                           if ($since>$perlvar{'lonExpire'}) {
  863:                               $reply=
  864:                                     reply("unsub:$fname","$hostid{$clientip}");
  865:                               unlink("$fname");
  866:                           } else {
  867: 			     my $transname="$fname.in.transfer";
  868:                              my $remoteurl=
  869:                                     reply("sub:$fname","$hostid{$clientip}");
  870:                              my $response;
  871:                               {
  872:                              my $ua=new LWP::UserAgent;
  873:                              my $request=new HTTP::Request('GET',"$remoteurl");
  874:                              $response=$ua->request($request,$transname);
  875: 			      }
  876:                              if ($response->is_error()) {
  877: 				 unlink($transname);
  878:                                  my $message=$response->status_line;
  879:                                  &logthis(
  880:                                   "LWP GET: $message for $fname ($remoteurl)");
  881:                              } else {
  882: 	                         if ($remoteurl!~/\.meta$/) {
  883:                                   my $ua=new LWP::UserAgent;
  884:                                   my $mrequest=
  885:                                    new HTTP::Request('GET',$remoteurl.'.meta');
  886:                                   my $mresponse=
  887:                                    $ua->request($mrequest,$fname.'.meta');
  888:                                   if ($mresponse->is_error()) {
  889: 		                    unlink($fname.'.meta');
  890:                                   }
  891: 	                         }
  892:                                  rename($transname,$fname);
  893: 			     }
  894:                           }
  895:                           print $client "ok\n";
  896:                         } else {
  897:                           print $client "not_found\n";
  898:                         }
  899: 		       } else {
  900: 			print $client "rejected\n";
  901:                        }
  902: # ----------------------------------------------------------------- unsubscribe
  903:                    } elsif ($userinput =~ /^unsub/) {
  904:                        my ($cmd,$fname)=split(/:/,$userinput);
  905:                        if (-e $fname) {
  906:                            if (unlink("$fname.$hostid{$clientip}")) {
  907:                               print $client "ok\n";
  908: 			   } else {
  909:                               print $client "not_subscribed\n";
  910: 			   }
  911:                        } else {
  912: 			   print $client "not_found\n";
  913:                        }
  914: # ------------------------------------------------------------------- subscribe
  915:                    } elsif ($userinput =~ /^sub/) {
  916:                        my ($cmd,$fname)=split(/:/,$userinput);
  917:                        my $ownership=ishome($fname);
  918:                        if ($ownership eq 'owner') {
  919:                         if (-e $fname) {
  920: 			 if (-d $fname) {
  921: 			   print $client "directory\n";
  922:                          } else {
  923:                            $now=time;
  924:                            { 
  925: 			    my $sh;
  926:                             if ($sh=
  927:                              IO::File->new(">$fname.$hostid{$clientip}")) {
  928:                                print $sh "$clientip:$now\n";
  929: 			    }
  930: 			   }
  931:                            unless ($fname=~/\.meta$/) {
  932: 			       unlink("$fname.meta.$hostid{$clientip}");
  933:                            }
  934:                            $fname=~s/\/home\/httpd\/html\/res/raw/;
  935:                            $fname="http://$thisserver/".$fname;
  936:                            print $client "$fname\n";
  937: 		         }
  938:                         } else {
  939: 		      	   print $client "not_found\n";
  940:                         }
  941: 		       } else {
  942:                         print $client "rejected\n";
  943: 		       }
  944: # ------------------------------------------------------------------------- log
  945:                    } elsif ($userinput =~ /^log/) {
  946:                        my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
  947:                        chomp($what);
  948:                        my $proname=propath($udom,$uname);
  949:                        my $now=time;
  950:                        {
  951: 			 my $hfh;
  952: 			 if ($hfh=IO::File->new(">>$proname/activity.log")) { 
  953:                             print $hfh "$now:$hostid{$clientip}:$what\n";
  954:                             print $client "ok\n"; 
  955: 			} else {
  956:                             print $client "error:$!\n";
  957: 		        }
  958: 		       }
  959: # ------------------------------------------------------------------------- put
  960:                    } elsif ($userinput =~ /^put/) {
  961:                       my ($cmd,$udom,$uname,$namespace,$what)
  962:                           =split(/:/,$userinput);
  963:                       $namespace=~s/\//\_/g;
  964:                       $namespace=~s/\W//g;
  965:                       if ($namespace ne 'roles') {
  966:                        chomp($what);
  967:                        my $proname=propath($udom,$uname);
  968:                        my $now=time;
  969:                        unless ($namespace=~/^nohist\_/) {
  970: 			   my $hfh;
  971: 			   if (
  972:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
  973: 			       ) { print $hfh "P:$now:$what\n"; }
  974: 		       }
  975:                        my @pairs=split(/\&/,$what);
  976:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
  977:                            foreach $pair (@pairs) {
  978: 			       ($key,$value)=split(/=/,$pair);
  979:                                $hash{$key}=$value;
  980:                            }
  981: 			   if (untie(%hash)) {
  982:                               print $client "ok\n";
  983:                            } else {
  984:                               print $client "error:$!\n";
  985:                            }
  986:                        } else {
  987:                            print $client "error:$!\n";
  988:                        }
  989: 		      } else {
  990:                           print $client "refused\n";
  991:                       }
  992: # -------------------------------------------------------------------- rolesput
  993:                    } elsif ($userinput =~ /^rolesput/) {
  994: 		    if ($wasenc==1) {
  995:                        my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
  996:                           =split(/:/,$userinput);
  997:                        my $namespace='roles';
  998:                        chomp($what);
  999:                        my $proname=propath($udom,$uname);
 1000:                        my $now=time;
 1001:                        {
 1002: 			   my $hfh;
 1003: 			   if (
 1004:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1005: 			       ) { 
 1006:                                   print $hfh "P:$now:$exedom:$exeuser:$what\n";
 1007:                                  }
 1008: 		       }
 1009:                        my @pairs=split(/\&/,$what);
 1010:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1011:                            foreach $pair (@pairs) {
 1012: 			       ($key,$value)=split(/=/,$pair);
 1013:                                $hash{$key}=$value;
 1014:                            }
 1015: 			   if (untie(%hash)) {
 1016:                               print $client "ok\n";
 1017:                            } else {
 1018:                               print $client "error:$!\n";
 1019:                            }
 1020:                        } else {
 1021:                            print $client "error:$!\n";
 1022:                        }
 1023: 		      } else {
 1024:                           print $client "refused\n";
 1025:                       }
 1026: # ------------------------------------------------------------------------- get
 1027:                    } elsif ($userinput =~ /^get/) {
 1028:                        my ($cmd,$udom,$uname,$namespace,$what)
 1029:                           =split(/:/,$userinput);
 1030:                        $namespace=~s/\//\_/g;
 1031:                        $namespace=~s/\W//g;
 1032:                        chomp($what);
 1033:                        my @queries=split(/\&/,$what);
 1034:                        my $proname=propath($udom,$uname);
 1035:                        my $qresult='';
 1036:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1037:                            for ($i=0;$i<=$#queries;$i++) {
 1038:                                $qresult.="$hash{$queries[$i]}&";
 1039:                            }
 1040: 			   if (untie(%hash)) {
 1041: 		              $qresult=~s/\&$//;
 1042:                               print $client "$qresult\n";
 1043:                            } else {
 1044:                               print $client "error:$!\n";
 1045:                            }
 1046:                        } else {
 1047:                            print $client "error:$!\n";
 1048:                        }
 1049: # ------------------------------------------------------------------------ eget
 1050:                    } elsif ($userinput =~ /^eget/) {
 1051:                        my ($cmd,$udom,$uname,$namespace,$what)
 1052:                           =split(/:/,$userinput);
 1053:                        $namespace=~s/\//\_/g;
 1054:                        $namespace=~s/\W//g;
 1055:                        chomp($what);
 1056:                        my @queries=split(/\&/,$what);
 1057:                        my $proname=propath($udom,$uname);
 1058:                        my $qresult='';
 1059:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1060:                            for ($i=0;$i<=$#queries;$i++) {
 1061:                                $qresult.="$hash{$queries[$i]}&";
 1062:                            }
 1063: 			   if (untie(%hash)) {
 1064: 		              $qresult=~s/\&$//;
 1065:                               if ($cipher) {
 1066:                                 my $cmdlength=length($qresult);
 1067:                                 $qresult.="         ";
 1068:                                 my $encqresult='';
 1069:                                 for 
 1070: 				(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 1071:                                  $encqresult.=
 1072:                                  unpack("H16",
 1073:                                  $cipher->encrypt(substr($qresult,$encidx,8)));
 1074:                                 }
 1075:                                 print $client "enc:$cmdlength:$encqresult\n";
 1076: 			      } else {
 1077: 			        print $client "error:no_key\n";
 1078:                               }
 1079:                            } else {
 1080:                               print $client "error:$!\n";
 1081:                            }
 1082:                        } else {
 1083:                            print $client "error:$!\n";
 1084:                        }
 1085: # ------------------------------------------------------------------------- del
 1086:                    } elsif ($userinput =~ /^del/) {
 1087:                        my ($cmd,$udom,$uname,$namespace,$what)
 1088:                           =split(/:/,$userinput);
 1089:                        $namespace=~s/\//\_/g;
 1090:                        $namespace=~s/\W//g;
 1091:                        chomp($what);
 1092:                        my $proname=propath($udom,$uname);
 1093:                        my $now=time;
 1094:                        unless ($namespace=~/^nohist\_/) {
 1095: 			   my $hfh;
 1096: 			   if (
 1097:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1098: 			       ) { print $hfh "D:$now:$what\n"; }
 1099: 		       }
 1100:                        my @keys=split(/\&/,$what);
 1101:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1102:                            foreach $key (@keys) {
 1103:                                delete($hash{$key});
 1104:                            }
 1105: 			   if (untie(%hash)) {
 1106:                               print $client "ok\n";
 1107:                            } else {
 1108:                               print $client "error:$!\n";
 1109:                            }
 1110:                        } else {
 1111:                            print $client "error:$!\n";
 1112:                        }
 1113: # ------------------------------------------------------------------------ keys
 1114:                    } elsif ($userinput =~ /^keys/) {
 1115:                        my ($cmd,$udom,$uname,$namespace)
 1116:                           =split(/:/,$userinput);
 1117:                        $namespace=~s/\//\_/g;
 1118:                        $namespace=~s/\W//g;
 1119:                        my $proname=propath($udom,$uname);
 1120:                        my $qresult='';
 1121:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1122:                            foreach $key (keys %hash) {
 1123:                                $qresult.="$key&";
 1124:                            }
 1125: 			   if (untie(%hash)) {
 1126: 		              $qresult=~s/\&$//;
 1127:                               print $client "$qresult\n";
 1128:                            } else {
 1129:                               print $client "error:$!\n";
 1130:                            }
 1131:                        } else {
 1132:                            print $client "error:$!\n";
 1133:                        }
 1134: # ------------------------------------------------------------------------ dump
 1135:                    } elsif ($userinput =~ /^dump/) {
 1136:                        my ($cmd,$udom,$uname,$namespace,$regexp)
 1137:                           =split(/:/,$userinput);
 1138:                        $namespace=~s/\//\_/g;
 1139:                        $namespace=~s/\W//g;
 1140:                        if (defined($regexp)) {
 1141:                           $regexp=&unescape($regexp);
 1142: 		       } else {
 1143:                           $regexp='.';
 1144: 		       }
 1145:                        my $proname=propath($udom,$uname);
 1146:                        my $qresult='';
 1147:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1148:                            foreach $key (keys %hash) {
 1149:                                if (eval('$key=~/$regexp/')) {
 1150:                                   $qresult.="$key=$hash{$key}&";
 1151: 			       }
 1152:                            }
 1153: 			   if (untie(%hash)) {
 1154: 		              $qresult=~s/\&$//;
 1155:                               print $client "$qresult\n";
 1156:                            } else {
 1157:                               print $client "error:$!\n";
 1158:                            }
 1159:                        } else {
 1160:                            print $client "error:$!\n";
 1161:                        }
 1162: # ----------------------------------------------------------------------- store
 1163:                    } elsif ($userinput =~ /^store/) {
 1164:                       my ($cmd,$udom,$uname,$namespace,$rid,$what)
 1165:                           =split(/:/,$userinput);
 1166:                       $namespace=~s/\//\_/g;
 1167:                       $namespace=~s/\W//g;
 1168:                       if ($namespace ne 'roles') {
 1169:                        chomp($what);
 1170:                        my $proname=propath($udom,$uname);
 1171:                        my $now=time;
 1172:                        unless ($namespace=~/^nohist\_/) {
 1173: 			   my $hfh;
 1174: 			   if (
 1175:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1176: 			       ) { print $hfh "P:$now:$rid:$what\n"; }
 1177: 		       }
 1178:                        my @pairs=split(/\&/,$what);
 1179:                          
 1180:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1181:                            my @previouskeys=split(/&/,$hash{"keys:$rid"});
 1182:                            my $key;
 1183:                            $hash{"version:$rid"}++;
 1184:                            my $version=$hash{"version:$rid"};
 1185:                            my $allkeys=''; 
 1186:                            foreach $pair (@pairs) {
 1187: 			       ($key,$value)=split(/=/,$pair);
 1188:                                $allkeys.=$key.':';
 1189:                                $hash{"$version:$rid:$key"}=$value;
 1190:                            }
 1191:                            $hash{"$version:$rid:timestamp"}=$now;
 1192:                            $allkeys.='timestamp';
 1193:                            $hash{"$version:keys:$rid"}=$allkeys;
 1194: 			   if (untie(%hash)) {
 1195:                               print $client "ok\n";
 1196:                            } else {
 1197:                               print $client "error:$!\n";
 1198:                            }
 1199:                        } else {
 1200:                            print $client "error:$!\n";
 1201:                        }
 1202: 		      } else {
 1203:                           print $client "refused\n";
 1204:                       }
 1205: # --------------------------------------------------------------------- restore
 1206:                    } elsif ($userinput =~ /^restore/) {
 1207:                        my ($cmd,$udom,$uname,$namespace,$rid)
 1208:                           =split(/:/,$userinput);
 1209:                        $namespace=~s/\//\_/g;
 1210:                        $namespace=~s/\W//g;
 1211:                        chomp($rid);
 1212:                        my $proname=propath($udom,$uname);
 1213:                        my $qresult='';
 1214:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1215:                 	   my $version=$hash{"version:$rid"};
 1216:                            $qresult.="version=$version&";
 1217:                            my $scope;
 1218:                            for ($scope=1;$scope<=$version;$scope++) {
 1219: 			      my $vkeys=$hash{"$scope:keys:$rid"};
 1220:                               my @keys=split(/:/,$vkeys);
 1221:                               my $key;
 1222:                               $qresult.="$scope:keys=$vkeys&";
 1223:                               foreach $key (@keys) {
 1224: 	     $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 1225:                               }                                  
 1226:                            }
 1227: 			   if (untie(%hash)) {
 1228: 		              $qresult=~s/\&$//;
 1229:                               print $client "$qresult\n";
 1230:                            } else {
 1231:                               print $client "error:$!\n";
 1232:                            }
 1233:                        } else {
 1234:                            print $client "error:$!\n";
 1235:                        }
 1236: # ------------------------------------------------------------------- querysend
 1237:                    } elsif ($userinput =~ /^querysend/) {
 1238:                        my ($cmd,$query,
 1239: 			   $custom,$customshow)=split(/:/,$userinput);
 1240: 		       $query=~s/\n*$//g;
 1241: 		       unless ($custom or $customshow) {
 1242: 			   print $client "".
 1243: 			       sqlreply("$hostid{$clientip}\&$query")."\n";
 1244: 		       }
 1245: 		       else {
 1246: 			   print $client "".
 1247: 			       sqlreply("$hostid{$clientip}\&$query".
 1248: 					"\&$custom"."\&$customshow")."\n";
 1249: 		       }
 1250: # ------------------------------------------------------------------ queryreply
 1251:                    } elsif ($userinput =~ /^queryreply/) {
 1252:                        my ($cmd,$id,$reply)=split(/:/,$userinput); 
 1253: 		       my $store;
 1254:                        my $execdir=$perlvar{'lonDaemons'};
 1255:                        if ($store=IO::File->new(">$execdir/tmp/$id")) {
 1256: 			   $reply=~s/\&/\n/g;
 1257: 			   print $store $reply;
 1258: 			   close $store;
 1259: 			   my $store2=IO::File->new(">$execdir/tmp/$id.end");
 1260: 			   print $store2 "done\n";
 1261: 			   close $store2;
 1262: 			   print $client "ok\n";
 1263: 		       }
 1264: 		       else {
 1265: 			   print $client "error:$!\n";
 1266: 		       }
 1267: # ----------------------------------------------------------------------- idput
 1268:                    } elsif ($userinput =~ /^idput/) {
 1269:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1270:                        chomp($what);
 1271:                        $udom=~s/\W//g;
 1272:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1273:                        my $now=time;
 1274:                        {
 1275: 			   my $hfh;
 1276: 			   if (
 1277:                              $hfh=IO::File->new(">>$proname.hist")
 1278: 			       ) { print $hfh "P:$now:$what\n"; }
 1279: 		       }
 1280:                        my @pairs=split(/\&/,$what);
 1281:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT,0640)) {
 1282:                            foreach $pair (@pairs) {
 1283: 			       ($key,$value)=split(/=/,$pair);
 1284:                                $hash{$key}=$value;
 1285:                            }
 1286: 			   if (untie(%hash)) {
 1287:                               print $client "ok\n";
 1288:                            } else {
 1289:                               print $client "error:$!\n";
 1290:                            }
 1291:                        } else {
 1292:                            print $client "error:$!\n";
 1293:                        }
 1294: # ----------------------------------------------------------------------- idget
 1295:                    } elsif ($userinput =~ /^idget/) {
 1296:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1297:                        chomp($what);
 1298:                        $udom=~s/\W//g;
 1299:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1300:                        my @queries=split(/\&/,$what);
 1301:                        my $qresult='';
 1302:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER,0640)) {
 1303:                            for ($i=0;$i<=$#queries;$i++) {
 1304:                                $qresult.="$hash{$queries[$i]}&";
 1305:                            }
 1306: 			   if (untie(%hash)) {
 1307: 		              $qresult=~s/\&$//;
 1308:                               print $client "$qresult\n";
 1309:                            } else {
 1310:                               print $client "error:$!\n";
 1311:                            }
 1312:                        } else {
 1313:                            print $client "error:$!\n";
 1314:                        }
 1315: # ---------------------------------------------------------------------- tmpput
 1316:                    } elsif ($userinput =~ /^tmpput/) {
 1317:                        my ($cmd,$what)=split(/:/,$userinput);
 1318: 		       my $store;
 1319:                        $tmpsnum++;
 1320:                        my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 1321:                        $id=~s/\W/\_/g;
 1322:                        $what=~s/\n//g;
 1323:                        my $execdir=$perlvar{'lonDaemons'};
 1324:                        if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 1325: 			   print $store $what;
 1326: 			   close $store;
 1327: 			   print $client "$id\n";
 1328: 		       }
 1329: 		       else {
 1330: 			   print $client "error:$!\n";
 1331: 		       }
 1332: 
 1333: # ---------------------------------------------------------------------- tmpget
 1334:                    } elsif ($userinput =~ /^tmpget/) {
 1335:                        my ($cmd,$id)=split(/:/,$userinput);
 1336:                        chomp($id);
 1337:                        $id=~s/\W/\_/g;
 1338:                        my $store;
 1339:                        my $execdir=$perlvar{'lonDaemons'};
 1340:                        if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 1341:                            my $reply=<$store>;
 1342: 			   print $client "$reply\n";
 1343:                            close $store;
 1344: 		       }
 1345: 		       else {
 1346: 			   print $client "error:$!\n";
 1347: 		       }
 1348: 
 1349: # -------------------------------------------------------------------------- ls
 1350:                    } elsif ($userinput =~ /^ls/) {
 1351:                        my ($cmd,$ulsdir)=split(/:/,$userinput);
 1352:                        my $ulsout='';
 1353:                        my $ulsfn;
 1354:                        if (-e $ulsdir) {
 1355: 			if (opendir(LSDIR,$ulsdir)) {
 1356:                           while ($ulsfn=readdir(LSDIR)) {
 1357: 			     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1358:                              $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1359:                           }
 1360:                           closedir(LSDIR);
 1361: 		        }
 1362: 		       } else {
 1363:                           $ulsout='no_such_dir';
 1364:                        }
 1365:                        if ($ulsout eq '') { $ulsout='empty'; }
 1366:                        print $client "$ulsout\n";
 1367: # ------------------------------------------------------------------ Hanging up
 1368:                    } elsif (($userinput =~ /^exit/) ||
 1369:                             ($userinput =~ /^init/)) {
 1370:                        &logthis(
 1371:       "Client $clientip ($hostid{$clientip}) hanging up: $userinput");
 1372:                        print $client "bye\n";
 1373:                        $client->close();
 1374: 		       last;
 1375: # ------------------------------------------------------------- unknown command
 1376:                    } else {
 1377:                        # unknown command
 1378:                        print $client "unknown_cmd\n";
 1379:                    }
 1380: # -------------------------------------------------------------------- complete
 1381: 		   alarm(0);
 1382:                    &status('Listening to '.$hostid{$clientip});
 1383: 	       }
 1384: # --------------------------------------------- client unknown or fishy, refuse
 1385:             } else {
 1386: 	        print $client "refused\n";
 1387:                 $client->close();
 1388:                 &logthis("<font color=blue>WARNING: "
 1389:                 ."Rejected client $clientip, closing connection</font>");
 1390:             }              
 1391:             &logthis("<font color=red>CRITICAL: "
 1392:                     ."Disconnect from $clientip ($hostid{$clientip})</font>");
 1393: # =============================================================================
 1394:         }
 1395:     
 1396:         # tidy up gracefully and finish
 1397:     
 1398:         $client->close();
 1399:         $server->close();
 1400: 
 1401:         # this exit is VERY important, otherwise the child will become
 1402:         # a producer of more and more children, forking yourself into
 1403:         # process death.
 1404:         exit;
 1405:     }
 1406: }
 1407: 
 1408: # ----------------------------------- POD (plain old documentation, CPAN style)
 1409: 
 1410: =head1 NAME
 1411: 
 1412: lond - "LON Daemon" Server (port "LOND" 5663)
 1413: 
 1414: =head1 SYNOPSIS
 1415: 
 1416: Should only be run as user=www.  Invoked by loncron.
 1417: 
 1418: =head1 DESCRIPTION
 1419: 
 1420: Preforker - server who forks first. Runs as a daemon. HUPs.
 1421: Uses IDEA encryption
 1422: 
 1423: =head1 README
 1424: 
 1425: Not yet written.
 1426: 
 1427: =head1 PREREQUISITES
 1428: 
 1429: IO::Socket
 1430: IO::File
 1431: Apache::File
 1432: Symbol
 1433: POSIX
 1434: Crypt::IDEA
 1435: LWP::UserAgent()
 1436: GDBM_File
 1437: Authen::Krb4
 1438: 
 1439: =head1 COREQUISITES
 1440: 
 1441: =head1 OSNAMES
 1442: 
 1443: linux
 1444: 
 1445: =head1 SCRIPT CATEGORIES
 1446: 
 1447: Server/Process
 1448: 
 1449: =cut
 1450: 
 1451: 
 1452: 
 1453: 

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