File:  [LON-CAPA] / loncom / lond
Revision 1.105: download - view: text, annotated - select for diffs
Mon Jan 13 21:52:11 2003 UTC (21 years, 3 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added new lond command: dumpcurrent.
Added lonnet::dumpcurrent
Modified spreadsheet.pm to use dumpcurrent to retrieve user data.
Some logging information is active, some is not.  More testing required.

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

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