File:  [LON-CAPA] / loncom / lond
Revision 1.116: download - view: text, annotated - select for diffs
Sat Mar 22 17:13:40 2003 UTC (21 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- I seem to never remember that the D in lonHostID is capitalized

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

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