File:  [LON-CAPA] / loncom / lond
Revision 1.72: download - view: text, annotated - select for diffs
Tue Feb 19 21:52:54 2002 UTC (22 years, 2 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added unix (filesystem) authentication handling to passwd handler.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.72 2002/02/19 21:52:54 matthew 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: 		       &logthis("Trying to change password for $uname");
  674: 		       my $proname=propath($udom,$uname);
  675:                        my $passfilename="$proname/passwd";
  676:                        if (-e $passfilename) {
  677: 			   my $realpasswd;
  678:                           { my $pf = IO::File->new($passfilename);
  679: 			    $realpasswd=<$pf>; }
  680:                           chomp($realpasswd);
  681:                           my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
  682:                           if ($howpwd eq 'internal') {
  683: 			   if (crypt($upass,$contentpwd) eq $contentpwd) {
  684: 			     my $salt=time;
  685:                              $salt=substr($salt,6,2);
  686: 			     my $ncpass=crypt($npass,$salt);
  687:                              { my $pf = IO::File->new(">$passfilename");
  688:  	  		       print $pf "internal:$ncpass\n"; }             
  689: 			     &logthis("Result of password change for $uname: pwchange_success");
  690:                              print $client "ok\n";
  691:                            } else {
  692:                              print $client "non_authorized\n";
  693:                            }
  694:                           } elsif ($howpwd eq 'unix') {
  695: 			      # Unix means we have to access /etc/password
  696: 			      # one way or another.
  697: 			      # First: Make sure the current password is
  698: 			      #        correct
  699: 			      $contentpwd=(getpwnam($uname))[1];
  700: 			      my $pwdcorrect = "0";
  701: 			      my $pwauth_path="/usr/local/sbin/pwauth";
  702: 			      unless ($contentpwd eq 'x') {
  703: 				  $pwdcorrect=
  704:                                     (crypt($upass,$contentpwd) eq $contentpwd);
  705: 			      } elsif (-e $pwauth_path) {
  706: 				  open PWAUTH, "|$pwauth_path" or
  707: 				      die "Cannot invoke authentication";
  708: 				  print PWAUTH "$uname\n$upass\n";
  709: 				  close PWAUTH;
  710: 				  $pwdcorrect=!$?;
  711: 			      }
  712: 			     if ($pwdcorrect) {
  713: 				 my $execdir=$perlvar{'lonDaemons'};
  714: 				 my $pf = IO::File->new("|$execdir/lcpasswd");
  715: 				 print $pf "$uname\n$npass\n$npass\n";
  716: 				 close $pf;
  717: 				 my $result = ($?>0 ? 'pwchange_failure' 
  718: 					       : 'ok');
  719: 				 &logthis("Result of password change for $uname: $result");
  720: 				 print $client "$result\n";
  721: 			     } else {
  722: 				 print $client "non_authorized\n";
  723: 			     }
  724: 			  } else {
  725:                             print $client "auth_mode_error\n";
  726:                           }  
  727: 		       } else {
  728:                           print $client "unknown_user\n";
  729:                        }
  730: 		     } else {
  731: 		       print $client "refused\n";
  732: 		     }
  733: # -------------------------------------------------------------------- makeuser
  734:                    } elsif ($userinput =~ /^makeuser/) {
  735:     	             my $oldumask=umask(0077);
  736: 		     if ($wasenc==1) {
  737:                        my 
  738:                        ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
  739:                        chomp($npass);
  740:                        $npass=&unescape($npass);
  741:                        my $proname=propath($udom,$uname);
  742:                        my $passfilename="$proname/passwd";
  743:                        if (-e $passfilename) {
  744: 			   print $client "already_exists\n";
  745:                        } elsif ($udom ne $perlvar{'lonDefDomain'}) {
  746:                            print $client "not_right_domain\n";
  747:                        } else {
  748:                            @fpparts=split(/\//,$proname);
  749:                            $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
  750:                            $fperror='';
  751:                            for ($i=3;$i<=$#fpparts;$i++) {
  752:                                $fpnow.='/'.$fpparts[$i]; 
  753:                                unless (-e $fpnow) {
  754: 				   unless (mkdir($fpnow,0777)) {
  755:                                       $fperror="error:$!";
  756:                                    }
  757:                                }
  758:                            }
  759:                            unless ($fperror) {
  760: 			     if ($umode eq 'krb4') {
  761:                                { 
  762:                                  my $pf = IO::File->new(">$passfilename");
  763:  	  		         print $pf "krb4:$npass\n"; 
  764:                                }             
  765:                                print $client "ok\n";
  766:                              } elsif ($umode eq 'internal') {
  767: 			       my $salt=time;
  768:                                $salt=substr($salt,6,2);
  769: 			       my $ncpass=crypt($npass,$salt);
  770:                                { 
  771:                                  my $pf = IO::File->new(">$passfilename");
  772:  	  		         print $pf "internal:$ncpass\n"; 
  773:                                }
  774:                                print $client "ok\n";
  775: 			     } elsif ($umode eq 'localauth') {
  776: 			       {
  777: 				 my $pf = IO::File->new(">$passfilename");
  778:   	  		         print $pf "localauth:$npass\n";
  779: 			       }
  780: 			       print $client "ok\n";
  781: 			     } elsif ($umode eq 'unix') {
  782: 			       {
  783: 				 my $execpath="$perlvar{'lonDaemons'}/".
  784: 				              "lcuseradd";
  785: 				 {
  786: 				     my $se = IO::File->new("|$execpath");
  787: 				     print $se "$uname\n";
  788: 				     print $se "$npass\n";
  789: 				     print $se "$npass\n";
  790: 				 }
  791:                                  my $pf = IO::File->new(">$passfilename");
  792:  	  		         print $pf "unix:\n"; 
  793: 			       }
  794: 			       print $client "ok\n";
  795: 			     } elsif ($umode eq 'none') {
  796:                                { 
  797:                                  my $pf = IO::File->new(">$passfilename");
  798:  	  		         print $pf "none:\n"; 
  799:                                }             
  800:                                print $client "ok\n";
  801:                              } else {
  802:                                print $client "auth_mode_error\n";
  803:                              }  
  804:                            } else {
  805:                                print $client "$fperror\n";
  806:                            }
  807:                        }
  808: 		     } else {
  809: 		       print $client "refused\n";
  810: 		     }
  811: 		     umask($oldumask);
  812: # -------------------------------------------------------------- changeuserauth
  813:                    } elsif ($userinput =~ /^changeuserauth/) {
  814: 		     if ($wasenc==1) {
  815:                        my 
  816:                        ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
  817:                        chomp($npass);
  818:                        $npass=&unescape($npass);
  819:                        my $proname=propath($udom,$uname);
  820:                        my $passfilename="$proname/passwd";
  821: 		       if ($udom ne $perlvar{'lonDefDomain'}) {
  822:                            print $client "not_right_domain\n";
  823:                        } else {
  824: 			   if ($umode eq 'krb4') {
  825:                                { 
  826: 				   my $pf = IO::File->new(">$passfilename");
  827: 				   print $pf "krb4:$npass\n"; 
  828:                                }             
  829:                                print $client "ok\n";
  830: 			   } elsif ($umode eq 'internal') {
  831: 			       my $salt=time;
  832:                                $salt=substr($salt,6,2);
  833: 			       my $ncpass=crypt($npass,$salt);
  834:                                { 
  835: 				   my $pf = IO::File->new(">$passfilename");
  836: 				   print $pf "internal:$ncpass\n"; 
  837:                                }
  838:                                print $client "ok\n";
  839: 			   } elsif ($umode eq 'localauth') {
  840: 			       {
  841: 				   my $pf = IO::File->new(">$passfilename");
  842: 				   print $pf "localauth:$npass\n";
  843: 			       }
  844: 			       print $client "ok\n";
  845: 			   } elsif ($umode eq 'unix') {
  846: 			       {
  847: 				   my $execpath="$perlvar{'lonDaemons'}/".
  848: 				       "lcuseradd";
  849: 				   {
  850: 				       my $se = IO::File->new("|$execpath");
  851: 				       print $se "$uname\n";
  852: 				       print $se "$npass\n";
  853: 				       print $se "$npass\n";
  854: 				   }
  855: 				   my $pf = IO::File->new(">$passfilename");
  856: 				   print $pf "unix:\n"; 
  857: 			       }
  858: 			       print $client "ok\n";
  859: 			   } elsif ($umode eq 'none') {
  860:                                { 
  861: 				   my $pf = IO::File->new(">$passfilename");
  862: 				   print $pf "none:\n"; 
  863:                                }             
  864:                                print $client "ok\n";
  865: 			   } else {
  866:                                print $client "auth_mode_error\n";
  867: 			   }  
  868:                        }
  869: 		     } else {
  870: 		       print $client "refused\n";
  871: 		     }
  872: # ------------------------------------------------------------------------ home
  873:                    } elsif ($userinput =~ /^home/) {
  874:                        my ($cmd,$udom,$uname)=split(/:/,$userinput);
  875:                        chomp($uname);
  876:                        my $proname=propath($udom,$uname);
  877:                        if (-e $proname) {
  878:                           print $client "found\n";
  879:                        } else {
  880: 			  print $client "not_found\n";
  881:                        }
  882: # ---------------------------------------------------------------------- update
  883:                    } elsif ($userinput =~ /^update/) {
  884:                        my ($cmd,$fname)=split(/:/,$userinput);
  885:                        my $ownership=ishome($fname);
  886:                        if ($ownership eq 'not_owner') {
  887:                         if (-e $fname) {
  888:                           my ($dev,$ino,$mode,$nlink,
  889:                               $uid,$gid,$rdev,$size,
  890:                               $atime,$mtime,$ctime,
  891:                               $blksize,$blocks)=stat($fname);
  892:                           $now=time;
  893:                           $since=$now-$atime;
  894:                           if ($since>$perlvar{'lonExpire'}) {
  895:                               $reply=
  896:                                     reply("unsub:$fname","$hostid{$clientip}");
  897:                               unlink("$fname");
  898:                           } else {
  899: 			     my $transname="$fname.in.transfer";
  900:                              my $remoteurl=
  901:                                     reply("sub:$fname","$hostid{$clientip}");
  902:                              my $response;
  903:                               {
  904:                              my $ua=new LWP::UserAgent;
  905:                              my $request=new HTTP::Request('GET',"$remoteurl");
  906:                              $response=$ua->request($request,$transname);
  907: 			      }
  908:                              if ($response->is_error()) {
  909: 				 unlink($transname);
  910:                                  my $message=$response->status_line;
  911:                                  &logthis(
  912:                                   "LWP GET: $message for $fname ($remoteurl)");
  913:                              } else {
  914: 	                         if ($remoteurl!~/\.meta$/) {
  915:                                   my $ua=new LWP::UserAgent;
  916:                                   my $mrequest=
  917:                                    new HTTP::Request('GET',$remoteurl.'.meta');
  918:                                   my $mresponse=
  919:                                    $ua->request($mrequest,$fname.'.meta');
  920:                                   if ($mresponse->is_error()) {
  921: 		                    unlink($fname.'.meta');
  922:                                   }
  923: 	                         }
  924:                                  rename($transname,$fname);
  925: 			     }
  926:                           }
  927:                           print $client "ok\n";
  928:                         } else {
  929:                           print $client "not_found\n";
  930:                         }
  931: 		       } else {
  932: 			print $client "rejected\n";
  933:                        }
  934: # ----------------------------------------------------------------- unsubscribe
  935:                    } elsif ($userinput =~ /^unsub/) {
  936:                        my ($cmd,$fname)=split(/:/,$userinput);
  937:                        if (-e $fname) {
  938:                            if (unlink("$fname.$hostid{$clientip}")) {
  939:                               print $client "ok\n";
  940: 			   } else {
  941:                               print $client "not_subscribed\n";
  942: 			   }
  943:                        } else {
  944: 			   print $client "not_found\n";
  945:                        }
  946: # ------------------------------------------------------------------- subscribe
  947:                    } elsif ($userinput =~ /^sub/) {
  948:                        my ($cmd,$fname)=split(/:/,$userinput);
  949:                        my $ownership=ishome($fname);
  950:                        if ($ownership eq 'owner') {
  951:                         if (-e $fname) {
  952: 			 if (-d $fname) {
  953: 			   print $client "directory\n";
  954:                          } else {
  955:                            $now=time;
  956:                            { 
  957: 			    my $sh;
  958:                             if ($sh=
  959:                              IO::File->new(">$fname.$hostid{$clientip}")) {
  960:                                print $sh "$clientip:$now\n";
  961: 			    }
  962: 			   }
  963:                            unless ($fname=~/\.meta$/) {
  964: 			       unlink("$fname.meta.$hostid{$clientip}");
  965:                            }
  966:                            $fname=~s/\/home\/httpd\/html\/res/raw/;
  967:                            $fname="http://$thisserver/".$fname;
  968:                            print $client "$fname\n";
  969: 		         }
  970:                         } else {
  971: 		      	   print $client "not_found\n";
  972:                         }
  973: 		       } else {
  974:                         print $client "rejected\n";
  975: 		       }
  976: # ------------------------------------------------------------------------- log
  977:                    } elsif ($userinput =~ /^log/) {
  978:                        my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
  979:                        chomp($what);
  980:                        my $proname=propath($udom,$uname);
  981:                        my $now=time;
  982:                        {
  983: 			 my $hfh;
  984: 			 if ($hfh=IO::File->new(">>$proname/activity.log")) { 
  985:                             print $hfh "$now:$hostid{$clientip}:$what\n";
  986:                             print $client "ok\n"; 
  987: 			} else {
  988:                             print $client "error:$!\n";
  989: 		        }
  990: 		       }
  991: # ------------------------------------------------------------------------- put
  992:                    } elsif ($userinput =~ /^put/) {
  993:                       my ($cmd,$udom,$uname,$namespace,$what)
  994:                           =split(/:/,$userinput);
  995:                       $namespace=~s/\//\_/g;
  996:                       $namespace=~s/\W//g;
  997:                       if ($namespace ne 'roles') {
  998:                        chomp($what);
  999:                        my $proname=propath($udom,$uname);
 1000:                        my $now=time;
 1001:                        unless ($namespace=~/^nohist\_/) {
 1002: 			   my $hfh;
 1003: 			   if (
 1004:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1005: 			       ) { print $hfh "P:$now:$what\n"; }
 1006: 		       }
 1007:                        my @pairs=split(/\&/,$what);
 1008:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1009:                            foreach $pair (@pairs) {
 1010: 			       ($key,$value)=split(/=/,$pair);
 1011:                                $hash{$key}=$value;
 1012:                            }
 1013: 			   if (untie(%hash)) {
 1014:                               print $client "ok\n";
 1015:                            } else {
 1016:                               print $client "error:$!\n";
 1017:                            }
 1018:                        } else {
 1019:                            print $client "error:$!\n";
 1020:                        }
 1021: 		      } else {
 1022:                           print $client "refused\n";
 1023:                       }
 1024: # -------------------------------------------------------------------- rolesput
 1025:                    } elsif ($userinput =~ /^rolesput/) {
 1026: 		    if ($wasenc==1) {
 1027:                        my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
 1028:                           =split(/:/,$userinput);
 1029:                        my $namespace='roles';
 1030:                        chomp($what);
 1031:                        my $proname=propath($udom,$uname);
 1032:                        my $now=time;
 1033:                        {
 1034: 			   my $hfh;
 1035: 			   if (
 1036:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1037: 			       ) { 
 1038:                                   print $hfh "P:$now:$exedom:$exeuser:$what\n";
 1039:                                  }
 1040: 		       }
 1041:                        my @pairs=split(/\&/,$what);
 1042:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1043:                            foreach $pair (@pairs) {
 1044: 			       ($key,$value)=split(/=/,$pair);
 1045:                                $hash{$key}=$value;
 1046:                            }
 1047: 			   if (untie(%hash)) {
 1048:                               print $client "ok\n";
 1049:                            } else {
 1050:                               print $client "error:$!\n";
 1051:                            }
 1052:                        } else {
 1053:                            print $client "error:$!\n";
 1054:                        }
 1055: 		      } else {
 1056:                           print $client "refused\n";
 1057:                       }
 1058: # ------------------------------------------------------------------------- get
 1059:                    } elsif ($userinput =~ /^get/) {
 1060:                        my ($cmd,$udom,$uname,$namespace,$what)
 1061:                           =split(/:/,$userinput);
 1062:                        $namespace=~s/\//\_/g;
 1063:                        $namespace=~s/\W//g;
 1064:                        chomp($what);
 1065:                        my @queries=split(/\&/,$what);
 1066:                        my $proname=propath($udom,$uname);
 1067:                        my $qresult='';
 1068:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1069:                            for ($i=0;$i<=$#queries;$i++) {
 1070:                                $qresult.="$hash{$queries[$i]}&";
 1071:                            }
 1072: 			   if (untie(%hash)) {
 1073: 		              $qresult=~s/\&$//;
 1074:                               print $client "$qresult\n";
 1075:                            } else {
 1076:                               print $client "error:$!\n";
 1077:                            }
 1078:                        } else {
 1079:                            print $client "error:$!\n";
 1080:                        }
 1081: # ------------------------------------------------------------------------ eget
 1082:                    } elsif ($userinput =~ /^eget/) {
 1083:                        my ($cmd,$udom,$uname,$namespace,$what)
 1084:                           =split(/:/,$userinput);
 1085:                        $namespace=~s/\//\_/g;
 1086:                        $namespace=~s/\W//g;
 1087:                        chomp($what);
 1088:                        my @queries=split(/\&/,$what);
 1089:                        my $proname=propath($udom,$uname);
 1090:                        my $qresult='';
 1091:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1092:                            for ($i=0;$i<=$#queries;$i++) {
 1093:                                $qresult.="$hash{$queries[$i]}&";
 1094:                            }
 1095: 			   if (untie(%hash)) {
 1096: 		              $qresult=~s/\&$//;
 1097:                               if ($cipher) {
 1098:                                 my $cmdlength=length($qresult);
 1099:                                 $qresult.="         ";
 1100:                                 my $encqresult='';
 1101:                                 for 
 1102: 				(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 1103:                                  $encqresult.=
 1104:                                  unpack("H16",
 1105:                                  $cipher->encrypt(substr($qresult,$encidx,8)));
 1106:                                 }
 1107:                                 print $client "enc:$cmdlength:$encqresult\n";
 1108: 			      } else {
 1109: 			        print $client "error:no_key\n";
 1110:                               }
 1111:                            } else {
 1112:                               print $client "error:$!\n";
 1113:                            }
 1114:                        } else {
 1115:                            print $client "error:$!\n";
 1116:                        }
 1117: # ------------------------------------------------------------------------- del
 1118:                    } elsif ($userinput =~ /^del/) {
 1119:                        my ($cmd,$udom,$uname,$namespace,$what)
 1120:                           =split(/:/,$userinput);
 1121:                        $namespace=~s/\//\_/g;
 1122:                        $namespace=~s/\W//g;
 1123:                        chomp($what);
 1124:                        my $proname=propath($udom,$uname);
 1125:                        my $now=time;
 1126:                        unless ($namespace=~/^nohist\_/) {
 1127: 			   my $hfh;
 1128: 			   if (
 1129:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1130: 			       ) { print $hfh "D:$now:$what\n"; }
 1131: 		       }
 1132:                        my @keys=split(/\&/,$what);
 1133:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1134:                            foreach $key (@keys) {
 1135:                                delete($hash{$key});
 1136:                            }
 1137: 			   if (untie(%hash)) {
 1138:                               print $client "ok\n";
 1139:                            } else {
 1140:                               print $client "error:$!\n";
 1141:                            }
 1142:                        } else {
 1143:                            print $client "error:$!\n";
 1144:                        }
 1145: # ------------------------------------------------------------------------ keys
 1146:                    } elsif ($userinput =~ /^keys/) {
 1147:                        my ($cmd,$udom,$uname,$namespace)
 1148:                           =split(/:/,$userinput);
 1149:                        $namespace=~s/\//\_/g;
 1150:                        $namespace=~s/\W//g;
 1151:                        my $proname=propath($udom,$uname);
 1152:                        my $qresult='';
 1153:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1154:                            foreach $key (keys %hash) {
 1155:                                $qresult.="$key&";
 1156:                            }
 1157: 			   if (untie(%hash)) {
 1158: 		              $qresult=~s/\&$//;
 1159:                               print $client "$qresult\n";
 1160:                            } else {
 1161:                               print $client "error:$!\n";
 1162:                            }
 1163:                        } else {
 1164:                            print $client "error:$!\n";
 1165:                        }
 1166: # ------------------------------------------------------------------------ dump
 1167:                    } elsif ($userinput =~ /^dump/) {
 1168:                        my ($cmd,$udom,$uname,$namespace,$regexp)
 1169:                           =split(/:/,$userinput);
 1170:                        $namespace=~s/\//\_/g;
 1171:                        $namespace=~s/\W//g;
 1172:                        if (defined($regexp)) {
 1173:                           $regexp=&unescape($regexp);
 1174: 		       } else {
 1175:                           $regexp='.';
 1176: 		       }
 1177:                        my $proname=propath($udom,$uname);
 1178:                        my $qresult='';
 1179:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1180:                            foreach $key (keys %hash) {
 1181:                                if (eval('$key=~/$regexp/')) {
 1182:                                   $qresult.="$key=$hash{$key}&";
 1183: 			       }
 1184:                            }
 1185: 			   if (untie(%hash)) {
 1186: 		              $qresult=~s/\&$//;
 1187:                               print $client "$qresult\n";
 1188:                            } else {
 1189:                               print $client "error:$!\n";
 1190:                            }
 1191:                        } else {
 1192:                            print $client "error:$!\n";
 1193:                        }
 1194: # ----------------------------------------------------------------------- store
 1195:                    } elsif ($userinput =~ /^store/) {
 1196:                       my ($cmd,$udom,$uname,$namespace,$rid,$what)
 1197:                           =split(/:/,$userinput);
 1198:                       $namespace=~s/\//\_/g;
 1199:                       $namespace=~s/\W//g;
 1200:                       if ($namespace ne 'roles') {
 1201:                        chomp($what);
 1202:                        my $proname=propath($udom,$uname);
 1203:                        my $now=time;
 1204:                        unless ($namespace=~/^nohist\_/) {
 1205: 			   my $hfh;
 1206: 			   if (
 1207:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1208: 			       ) { print $hfh "P:$now:$rid:$what\n"; }
 1209: 		       }
 1210:                        my @pairs=split(/\&/,$what);
 1211:                          
 1212:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1213:                            my @previouskeys=split(/&/,$hash{"keys:$rid"});
 1214:                            my $key;
 1215:                            $hash{"version:$rid"}++;
 1216:                            my $version=$hash{"version:$rid"};
 1217:                            my $allkeys=''; 
 1218:                            foreach $pair (@pairs) {
 1219: 			       ($key,$value)=split(/=/,$pair);
 1220:                                $allkeys.=$key.':';
 1221:                                $hash{"$version:$rid:$key"}=$value;
 1222:                            }
 1223:                            $hash{"$version:$rid:timestamp"}=$now;
 1224:                            $allkeys.='timestamp';
 1225:                            $hash{"$version:keys:$rid"}=$allkeys;
 1226: 			   if (untie(%hash)) {
 1227:                               print $client "ok\n";
 1228:                            } else {
 1229:                               print $client "error:$!\n";
 1230:                            }
 1231:                        } else {
 1232:                            print $client "error:$!\n";
 1233:                        }
 1234: 		      } else {
 1235:                           print $client "refused\n";
 1236:                       }
 1237: # --------------------------------------------------------------------- restore
 1238:                    } elsif ($userinput =~ /^restore/) {
 1239:                        my ($cmd,$udom,$uname,$namespace,$rid)
 1240:                           =split(/:/,$userinput);
 1241:                        $namespace=~s/\//\_/g;
 1242:                        $namespace=~s/\W//g;
 1243:                        chomp($rid);
 1244:                        my $proname=propath($udom,$uname);
 1245:                        my $qresult='';
 1246:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1247:                 	   my $version=$hash{"version:$rid"};
 1248:                            $qresult.="version=$version&";
 1249:                            my $scope;
 1250:                            for ($scope=1;$scope<=$version;$scope++) {
 1251: 			      my $vkeys=$hash{"$scope:keys:$rid"};
 1252:                               my @keys=split(/:/,$vkeys);
 1253:                               my $key;
 1254:                               $qresult.="$scope:keys=$vkeys&";
 1255:                               foreach $key (@keys) {
 1256: 	     $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 1257:                               }                                  
 1258:                            }
 1259: 			   if (untie(%hash)) {
 1260: 		              $qresult=~s/\&$//;
 1261:                               print $client "$qresult\n";
 1262:                            } else {
 1263:                               print $client "error:$!\n";
 1264:                            }
 1265:                        } else {
 1266:                            print $client "error:$!\n";
 1267:                        }
 1268: # ------------------------------------------------------------------- querysend
 1269:                    } elsif ($userinput =~ /^querysend/) {
 1270:                        my ($cmd,$query,
 1271: 			   $custom,$customshow)=split(/:/,$userinput);
 1272: 		       $query=~s/\n*$//g;
 1273: 		       unless ($custom or $customshow) {
 1274: 			   print $client "".
 1275: 			       sqlreply("$hostid{$clientip}\&$query")."\n";
 1276: 		       }
 1277: 		       else {
 1278: 			   print $client "".
 1279: 			       sqlreply("$hostid{$clientip}\&$query".
 1280: 					"\&$custom"."\&$customshow")."\n";
 1281: 		       }
 1282: # ------------------------------------------------------------------ queryreply
 1283:                    } elsif ($userinput =~ /^queryreply/) {
 1284:                        my ($cmd,$id,$reply)=split(/:/,$userinput); 
 1285: 		       my $store;
 1286:                        my $execdir=$perlvar{'lonDaemons'};
 1287:                        if ($store=IO::File->new(">$execdir/tmp/$id")) {
 1288: 			   $reply=~s/\&/\n/g;
 1289: 			   print $store $reply;
 1290: 			   close $store;
 1291: 			   my $store2=IO::File->new(">$execdir/tmp/$id.end");
 1292: 			   print $store2 "done\n";
 1293: 			   close $store2;
 1294: 			   print $client "ok\n";
 1295: 		       }
 1296: 		       else {
 1297: 			   print $client "error:$!\n";
 1298: 		       }
 1299: # ----------------------------------------------------------------------- idput
 1300:                    } elsif ($userinput =~ /^idput/) {
 1301:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1302:                        chomp($what);
 1303:                        $udom=~s/\W//g;
 1304:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1305:                        my $now=time;
 1306:                        {
 1307: 			   my $hfh;
 1308: 			   if (
 1309:                              $hfh=IO::File->new(">>$proname.hist")
 1310: 			       ) { print $hfh "P:$now:$what\n"; }
 1311: 		       }
 1312:                        my @pairs=split(/\&/,$what);
 1313:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT,0640)) {
 1314:                            foreach $pair (@pairs) {
 1315: 			       ($key,$value)=split(/=/,$pair);
 1316:                                $hash{$key}=$value;
 1317:                            }
 1318: 			   if (untie(%hash)) {
 1319:                               print $client "ok\n";
 1320:                            } else {
 1321:                               print $client "error:$!\n";
 1322:                            }
 1323:                        } else {
 1324:                            print $client "error:$!\n";
 1325:                        }
 1326: # ----------------------------------------------------------------------- idget
 1327:                    } elsif ($userinput =~ /^idget/) {
 1328:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1329:                        chomp($what);
 1330:                        $udom=~s/\W//g;
 1331:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1332:                        my @queries=split(/\&/,$what);
 1333:                        my $qresult='';
 1334:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER,0640)) {
 1335:                            for ($i=0;$i<=$#queries;$i++) {
 1336:                                $qresult.="$hash{$queries[$i]}&";
 1337:                            }
 1338: 			   if (untie(%hash)) {
 1339: 		              $qresult=~s/\&$//;
 1340:                               print $client "$qresult\n";
 1341:                            } else {
 1342:                               print $client "error:$!\n";
 1343:                            }
 1344:                        } else {
 1345:                            print $client "error:$!\n";
 1346:                        }
 1347: # ---------------------------------------------------------------------- tmpput
 1348:                    } elsif ($userinput =~ /^tmpput/) {
 1349:                        my ($cmd,$what)=split(/:/,$userinput);
 1350: 		       my $store;
 1351:                        $tmpsnum++;
 1352:                        my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 1353:                        $id=~s/\W/\_/g;
 1354:                        $what=~s/\n//g;
 1355:                        my $execdir=$perlvar{'lonDaemons'};
 1356:                        if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 1357: 			   print $store $what;
 1358: 			   close $store;
 1359: 			   print $client "$id\n";
 1360: 		       }
 1361: 		       else {
 1362: 			   print $client "error:$!\n";
 1363: 		       }
 1364: 
 1365: # ---------------------------------------------------------------------- tmpget
 1366:                    } elsif ($userinput =~ /^tmpget/) {
 1367:                        my ($cmd,$id)=split(/:/,$userinput);
 1368:                        chomp($id);
 1369:                        $id=~s/\W/\_/g;
 1370:                        my $store;
 1371:                        my $execdir=$perlvar{'lonDaemons'};
 1372:                        if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 1373:                            my $reply=<$store>;
 1374: 			   print $client "$reply\n";
 1375:                            close $store;
 1376: 		       }
 1377: 		       else {
 1378: 			   print $client "error:$!\n";
 1379: 		       }
 1380: 
 1381: # -------------------------------------------------------------------------- ls
 1382:                    } elsif ($userinput =~ /^ls/) {
 1383:                        my ($cmd,$ulsdir)=split(/:/,$userinput);
 1384:                        my $ulsout='';
 1385:                        my $ulsfn;
 1386:                        if (-e $ulsdir) {
 1387: 			if (opendir(LSDIR,$ulsdir)) {
 1388:                           while ($ulsfn=readdir(LSDIR)) {
 1389: 			     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1390:                              $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1391:                           }
 1392:                           closedir(LSDIR);
 1393: 		        }
 1394: 		       } else {
 1395:                           $ulsout='no_such_dir';
 1396:                        }
 1397:                        if ($ulsout eq '') { $ulsout='empty'; }
 1398:                        print $client "$ulsout\n";
 1399: # ------------------------------------------------------------------ Hanging up
 1400:                    } elsif (($userinput =~ /^exit/) ||
 1401:                             ($userinput =~ /^init/)) {
 1402:                        &logthis(
 1403:       "Client $clientip ($hostid{$clientip}) hanging up: $userinput");
 1404:                        print $client "bye\n";
 1405:                        $client->close();
 1406: 		       last;
 1407: # ------------------------------------------------------------- unknown command
 1408:                    } else {
 1409:                        # unknown command
 1410:                        print $client "unknown_cmd\n";
 1411:                    }
 1412: # -------------------------------------------------------------------- complete
 1413: 		   alarm(0);
 1414:                    &status('Listening to '.$hostid{$clientip});
 1415: 	       }
 1416: # --------------------------------------------- client unknown or fishy, refuse
 1417:             } else {
 1418: 	        print $client "refused\n";
 1419:                 $client->close();
 1420:                 &logthis("<font color=blue>WARNING: "
 1421:                 ."Rejected client $clientip, closing connection</font>");
 1422:             }              
 1423:             &logthis("<font color=red>CRITICAL: "
 1424:                     ."Disconnect from $clientip ($hostid{$clientip})</font>");
 1425: # =============================================================================
 1426:         }
 1427:     
 1428:         # tidy up gracefully and finish
 1429:     
 1430:         $client->close();
 1431:         $server->close();
 1432: 
 1433:         # this exit is VERY important, otherwise the child will become
 1434:         # a producer of more and more children, forking yourself into
 1435:         # process death.
 1436:         exit;
 1437:     }
 1438: }
 1439: 
 1440: # ----------------------------------- POD (plain old documentation, CPAN style)
 1441: 
 1442: =head1 NAME
 1443: 
 1444: lond - "LON Daemon" Server (port "LOND" 5663)
 1445: 
 1446: =head1 SYNOPSIS
 1447: 
 1448: Should only be run as user=www.  Invoked by loncron.
 1449: 
 1450: =head1 DESCRIPTION
 1451: 
 1452: Preforker - server who forks first. Runs as a daemon. HUPs.
 1453: Uses IDEA encryption
 1454: 
 1455: =head1 README
 1456: 
 1457: Not yet written.
 1458: 
 1459: =head1 PREREQUISITES
 1460: 
 1461: IO::Socket
 1462: IO::File
 1463: Apache::File
 1464: Symbol
 1465: POSIX
 1466: Crypt::IDEA
 1467: LWP::UserAgent()
 1468: GDBM_File
 1469: Authen::Krb4
 1470: 
 1471: =head1 COREQUISITES
 1472: 
 1473: =head1 OSNAMES
 1474: 
 1475: linux
 1476: 
 1477: =head1 SCRIPT CATEGORIES
 1478: 
 1479: Server/Process
 1480: 
 1481: =cut
 1482: 
 1483: 
 1484: 
 1485: 

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