File:  [LON-CAPA] / loncom / lond
Revision 1.106: download - view: text, annotated - select for diffs
Wed Jan 15 04:43:14 2003 UTC (21 years, 9 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Turn into non-preforking daemon... testing

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

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