File:  [LON-CAPA] / loncom / lond
Revision 1.112: download - view: text, annotated - select for diffs
Fri Mar 7 15:04:00 2003 UTC (21 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Since GDBM does not bother to check to see if the file it wants exists before
trying to open it a 'bad block error' will result when a non-existant file
is tied.  lond now reports: "error:No such file or GDBM reported bad block
error\n" when this occurs on a 'get' call so we don't bother logging the
error every time a file is requested that does not exist.
&Apache::lonnet::EXT() in particular expects an error of this form.

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

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