File:  [LON-CAPA] / loncom / lond
Revision 1.103.2.1: download - view: text, annotated - select for diffs
Fri Mar 14 21:25:44 2003 UTC (21 years, 7 months ago) by albertel
Branches: version_0_6
CVS tags: version_0_6_2
- backport of 1.113 (lond parent can get stuck trying to send mail)

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

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