File:  [LON-CAPA] / loncom / lond
Revision 1.61: download - view: text, annotated - select for diffs
Thu Dec 20 17:43:05 2001 UTC (22 years, 4 months ago) by harris41
Branches: MAIN
CVS tags: HEAD
adding POD; removing void context map statements -Scott Harrison

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

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