File:  [LON-CAPA] / loncom / lond
Revision 1.107: download - view: text, annotated - select for diffs
Wed Jan 15 19:34:02 2003 UTC (21 years, 3 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Rename dumpcurrent to currentdump
lond: fixed 1D10T bug in code.  $value was used instead of $v (version).
lonspreadsheet: now call lonnet::currentdump, removed debugging code and
                code that was commented out.
lonnet:renamed dumpcurrent to currentdump.  currentdump will now deal
       transparently with old lond's that do not support currentdump.

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

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