File:  [LON-CAPA] / loncom / lond
Revision 1.110: download - view: text, annotated - select for diffs
Sun Mar 2 03:58:55 2003 UTC (21 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Fixes possible security problem.

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

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