File:  [LON-CAPA] / loncom / lond
Revision 1.111: download - view: text, annotated - select for diffs
Tue Mar 4 22:32:20 2003 UTC (21 years, 2 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Made error messages more verbose - I'm seeing a ton of the " tie(GDBM) Failed"
float by and I need to narrow down my search.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network
    3: # lond "LON Daemon" Server (port "LOND" 5663)
    4: #
    5: # $Id: lond,v 1.111 2003/03/04 22:32:20 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:                            print $client "error: ".($!+0)
 1143: 			       ." tie(GDBM) Failed ".
 1144:                                    "while attempting get\n";
 1145:                        }
 1146: # ------------------------------------------------------------------------ eget
 1147:                    } elsif ($userinput =~ /^eget/) {
 1148:                        my ($cmd,$udom,$uname,$namespace,$what)
 1149:                           =split(/:/,$userinput);
 1150:                        $namespace=~s/\//\_/g;
 1151:                        $namespace=~s/\W//g;
 1152:                        chomp($what);
 1153:                        my @queries=split(/\&/,$what);
 1154:                        my $proname=propath($udom,$uname);
 1155:                        my $qresult='';
 1156:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1157:                            for ($i=0;$i<=$#queries;$i++) {
 1158:                                $qresult.="$hash{$queries[$i]}&";
 1159:                            }
 1160: 			   if (untie(%hash)) {
 1161: 		              $qresult=~s/\&$//;
 1162:                               if ($cipher) {
 1163:                                 my $cmdlength=length($qresult);
 1164:                                 $qresult.="         ";
 1165:                                 my $encqresult='';
 1166:                                 for 
 1167: 				(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
 1168:                                  $encqresult.=
 1169:                                  unpack("H16",
 1170:                                  $cipher->encrypt(substr($qresult,$encidx,8)));
 1171:                                 }
 1172:                                 print $client "enc:$cmdlength:$encqresult\n";
 1173: 			      } else {
 1174: 			        print $client "error:no_key\n";
 1175:                               }
 1176:                            } else {
 1177:                               print $client "error: ".($!+0)
 1178: 				  ." untie(GDBM) Failed ".
 1179:                                       "while attempting eget\n";
 1180:                            }
 1181:                        } else {
 1182:                            print $client "error: ".($!+0)
 1183: 			       ." tie(GDBM) Failed ".
 1184:                                    "while attempting eget\n";
 1185:                        }
 1186: # ------------------------------------------------------------------------- del
 1187:                    } elsif ($userinput =~ /^del/) {
 1188:                        my ($cmd,$udom,$uname,$namespace,$what)
 1189:                           =split(/:/,$userinput);
 1190:                        $namespace=~s/\//\_/g;
 1191:                        $namespace=~s/\W//g;
 1192:                        chomp($what);
 1193:                        my $proname=propath($udom,$uname);
 1194:                        my $now=time;
 1195:                        unless ($namespace=~/^nohist\_/) {
 1196: 			   my $hfh;
 1197: 			   if (
 1198:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1199: 			       ) { print $hfh "D:$now:$what\n"; }
 1200: 		       }
 1201:                        my @keys=split(/\&/,$what);
 1202:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1203:                            foreach $key (@keys) {
 1204:                                delete($hash{$key});
 1205:                            }
 1206: 			   if (untie(%hash)) {
 1207:                               print $client "ok\n";
 1208:                            } else {
 1209:                               print $client "error: ".($!+0)
 1210: 				  ." untie(GDBM) Failed ".
 1211:                                       "while attempting del\n";
 1212:                            }
 1213:                        } else {
 1214:                            print $client "error: ".($!+0)
 1215: 			       ." tie(GDBM) Failed ".
 1216:                                    "while attempting del\n";
 1217:                        }
 1218: # ------------------------------------------------------------------------ keys
 1219:                    } elsif ($userinput =~ /^keys/) {
 1220:                        my ($cmd,$udom,$uname,$namespace)
 1221:                           =split(/:/,$userinput);
 1222:                        $namespace=~s/\//\_/g;
 1223:                        $namespace=~s/\W//g;
 1224:                        my $proname=propath($udom,$uname);
 1225:                        my $qresult='';
 1226:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1227:                            foreach $key (keys %hash) {
 1228:                                $qresult.="$key&";
 1229:                            }
 1230: 			   if (untie(%hash)) {
 1231: 		              $qresult=~s/\&$//;
 1232:                               print $client "$qresult\n";
 1233:                            } else {
 1234:                               print $client "error: ".($!+0)
 1235: 				  ." untie(GDBM) Failed ".
 1236:                                       "while attempting keys\n";
 1237:                            }
 1238:                        } else {
 1239:                            print $client "error: ".($!+0)
 1240: 			       ." tie(GDBM) Failed ".
 1241:                                    "while attempting keys\n";
 1242:                        }
 1243: # ----------------------------------------------------------------- dumpcurrent
 1244:                    } elsif ($userinput =~ /^currentdump/) {
 1245:                        my ($cmd,$udom,$uname,$namespace)
 1246:                           =split(/:/,$userinput);
 1247:                        $namespace=~s/\//\_/g;
 1248:                        $namespace=~s/\W//g;
 1249:                        my $qresult='';
 1250:                        my $proname=propath($udom,$uname);
 1251:                        if (tie(%hash,'GDBM_File',
 1252:                                "$proname/$namespace.db",
 1253:                                &GDBM_READER(),0640)) {
 1254:                            # Structure of %data:
 1255:                            # $data{$symb}->{$parameter}=$value;
 1256:                            # $data{$symb}->{'v.'.$parameter}=$version;
 1257:                            # since $parameter will be unescaped, we do not
 1258:                            # have to worry about silly parameter names...
 1259:                            my %data = ();
 1260:                            while (my ($key,$value) = each(%hash)) {
 1261:                               my ($v,$symb,$param) = split(/:/,$key);
 1262:                               next if ($v eq 'version' || $symb eq 'keys');
 1263:                               next if (exists($data{$symb}) && 
 1264:                                        exists($data{$symb}->{$param}) &&
 1265:                                        $data{$symb}->{'v.'.$param} > $v);
 1266:                               $data{$symb}->{$param}=$value;
 1267:                               $data{$symb}->{'v.'.$param}=$v;
 1268:                            }
 1269:                            if (untie(%hash)) {
 1270:                              while (my ($symb,$param_hash) = each(%data)) {
 1271:                                while(my ($param,$value) = each (%$param_hash)){
 1272:                                  next if ($param =~ /^v\./);
 1273:                                  $qresult.=$symb.':'.$param.'='.$value.'&';
 1274:                                }
 1275:                              }
 1276:                              chop($qresult);
 1277:                              print $client "$qresult\n";
 1278:                            } else {
 1279:                              print $client "error: ".($!+0)
 1280: 				 ." untie(GDBM) Failed ".
 1281:                                      "while attempting currentdump\n";
 1282:                            }
 1283:                        } else {
 1284:                            print $client "error: ".($!+0)
 1285: 			       ." tie(GDBM) Failed ".
 1286:                                       "while attempting currentdump\n";
 1287:                        }
 1288: # ------------------------------------------------------------------------ dump
 1289:                    } elsif ($userinput =~ /^dump/) {
 1290:                        my ($cmd,$udom,$uname,$namespace,$regexp)
 1291:                           =split(/:/,$userinput);
 1292:                        $namespace=~s/\//\_/g;
 1293:                        $namespace=~s/\W//g;
 1294:                        if (defined($regexp)) {
 1295:                           $regexp=&unescape($regexp);
 1296: 		       } else {
 1297:                           $regexp='.';
 1298: 		       }
 1299:                        my $qresult='';
 1300:                        my $proname=propath($udom,$uname);
 1301:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
 1302:                            study($regexp);
 1303:                            while (($key,$value) = each(%hash)) {
 1304:                                if ($regexp eq '.') {
 1305:                                    $qresult.=$key.'='.$value.'&';
 1306:                                } else {
 1307:                                    my $unescapeKey = &unescape($key);
 1308:                                    if (eval('$unescapeKey=~/$regexp/')) {
 1309:                                        $qresult.="$key=$value&";
 1310:                                    }
 1311:                                }
 1312:                            }
 1313:                            if (untie(%hash)) {
 1314:                                chop($qresult);
 1315:                                print $client "$qresult\n";
 1316:                            } else {
 1317:                                print $client "error: ".($!+0)
 1318: 				   ." untie(GDBM) Failed ".
 1319:                                        "while attempting dump\n";
 1320:                            }
 1321:                        } else {
 1322:                            print $client "error: ".($!+0)
 1323: 			       ." tie(GDBM) Failed ".
 1324:                                       "while attempting dump\n";
 1325:                        }
 1326: # ----------------------------------------------------------------------- store
 1327:                    } elsif ($userinput =~ /^store/) {
 1328:                       my ($cmd,$udom,$uname,$namespace,$rid,$what)
 1329:                           =split(/:/,$userinput);
 1330:                       $namespace=~s/\//\_/g;
 1331:                       $namespace=~s/\W//g;
 1332:                       if ($namespace ne 'roles') {
 1333:                        chomp($what);
 1334:                        my $proname=propath($udom,$uname);
 1335:                        my $now=time;
 1336:                        unless ($namespace=~/^nohist\_/) {
 1337: 			   my $hfh;
 1338: 			   if (
 1339:                              $hfh=IO::File->new(">>$proname/$namespace.hist")
 1340: 			       ) { print $hfh "P:$now:$rid:$what\n"; }
 1341: 		       }
 1342:                        my @pairs=split(/\&/,$what);
 1343:                          
 1344:     if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT,0640)) {
 1345:                            my @previouskeys=split(/&/,$hash{"keys:$rid"});
 1346:                            my $key;
 1347:                            $hash{"version:$rid"}++;
 1348:                            my $version=$hash{"version:$rid"};
 1349:                            my $allkeys=''; 
 1350:                            foreach $pair (@pairs) {
 1351: 			       ($key,$value)=split(/=/,$pair);
 1352:                                $allkeys.=$key.':';
 1353:                                $hash{"$version:$rid:$key"}=$value;
 1354:                            }
 1355:                            $hash{"$version:$rid:timestamp"}=$now;
 1356:                            $allkeys.='timestamp';
 1357:                            $hash{"$version:keys:$rid"}=$allkeys;
 1358: 			   if (untie(%hash)) {
 1359:                               print $client "ok\n";
 1360:                            } else {
 1361:                               print $client "error: ".($!+0)
 1362: 				  ." untie(GDBM) Failed ".
 1363:                                       "while attempting store\n";
 1364:                            }
 1365:                        } else {
 1366:                            print $client "error: ".($!+0)
 1367: 			       ." tie(GDBM) Failed ".
 1368:                                    "while attempting store\n";
 1369:                        }
 1370: 		      } else {
 1371:                           print $client "refused\n";
 1372:                       }
 1373: # --------------------------------------------------------------------- restore
 1374:                    } elsif ($userinput =~ /^restore/) {
 1375:                        my ($cmd,$udom,$uname,$namespace,$rid)
 1376:                           =split(/:/,$userinput);
 1377:                        $namespace=~s/\//\_/g;
 1378:                        $namespace=~s/\W//g;
 1379:                        chomp($rid);
 1380:                        my $proname=propath($udom,$uname);
 1381:                        my $qresult='';
 1382:       if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER,0640)) {
 1383:                 	   my $version=$hash{"version:$rid"};
 1384:                            $qresult.="version=$version&";
 1385:                            my $scope;
 1386:                            for ($scope=1;$scope<=$version;$scope++) {
 1387: 			      my $vkeys=$hash{"$scope:keys:$rid"};
 1388:                               my @keys=split(/:/,$vkeys);
 1389:                               my $key;
 1390:                               $qresult.="$scope:keys=$vkeys&";
 1391:                               foreach $key (@keys) {
 1392: 	     $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
 1393:                               }                                  
 1394:                            }
 1395: 			   if (untie(%hash)) {
 1396: 		              $qresult=~s/\&$//;
 1397:                               print $client "$qresult\n";
 1398:                            } else {
 1399:                               print $client "error: ".($!+0)
 1400: 				  ." untie(GDBM) Failed ".
 1401:                                       "while attempting restore\n";
 1402:                            }
 1403:                        } else {
 1404:                            print $client "error: ".($!+0)
 1405: 			       ." tie(GDBM) Failed ".
 1406:                                    "while attempting restore\n";
 1407:                        }
 1408: # -------------------------------------------------------------------- chatsend
 1409:                    } elsif ($userinput =~ /^chatsend/) {
 1410:                        my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
 1411:                        &chatadd($cdom,$cnum,$newpost);
 1412:                        print $client "ok\n";
 1413: # -------------------------------------------------------------------- chatretr
 1414:                    } elsif ($userinput =~ /^chatretr/) {
 1415:                        my ($cmd,$cdom,$cnum)=split(/\:/,$userinput);
 1416:                        my $reply='';
 1417:                        foreach (&getchat($cdom,$cnum)) {
 1418: 			   $reply.=&escape($_).':';
 1419:                        }
 1420:                        $reply=~s/\:$//;
 1421:                        print $client $reply."\n";
 1422: # ------------------------------------------------------------------- querysend
 1423:                    } elsif ($userinput =~ /^querysend/) {
 1424:                        my ($cmd,$query,
 1425: 			   $arg1,$arg2,$arg3)=split(/\:/,$userinput);
 1426: 		       $query=~s/\n*$//g;
 1427: 		       print $client "".
 1428: 			       sqlreply("$hostid{$clientip}\&$query".
 1429: 					"\&$arg1"."\&$arg2"."\&$arg3")."\n";
 1430: # ------------------------------------------------------------------ queryreply
 1431:                    } elsif ($userinput =~ /^queryreply/) {
 1432:                        my ($cmd,$id,$reply)=split(/:/,$userinput); 
 1433: 		       my $store;
 1434:                        my $execdir=$perlvar{'lonDaemons'};
 1435:                        if ($store=IO::File->new(">$execdir/tmp/$id")) {
 1436: 			   $reply=~s/\&/\n/g;
 1437: 			   print $store $reply;
 1438: 			   close $store;
 1439: 			   my $store2=IO::File->new(">$execdir/tmp/$id.end");
 1440: 			   print $store2 "done\n";
 1441: 			   close $store2;
 1442: 			   print $client "ok\n";
 1443: 		       }
 1444: 		       else {
 1445: 			   print $client "error: ".($!+0)
 1446: 			       ." IO::File->new Failed ".
 1447:                                    "while attempting queryreply\n";
 1448: 		       }
 1449: # ----------------------------------------------------------------------- idput
 1450:                    } elsif ($userinput =~ /^idput/) {
 1451:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1452:                        chomp($what);
 1453:                        $udom=~s/\W//g;
 1454:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1455:                        my $now=time;
 1456:                        {
 1457: 			   my $hfh;
 1458: 			   if (
 1459:                              $hfh=IO::File->new(">>$proname.hist")
 1460: 			       ) { print $hfh "P:$now:$what\n"; }
 1461: 		       }
 1462:                        my @pairs=split(/\&/,$what);
 1463:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT,0640)) {
 1464:                            foreach $pair (@pairs) {
 1465: 			       ($key,$value)=split(/=/,$pair);
 1466:                                $hash{$key}=$value;
 1467:                            }
 1468: 			   if (untie(%hash)) {
 1469:                               print $client "ok\n";
 1470:                            } else {
 1471:                               print $client "error: ".($!+0)
 1472: 				  ." untie(GDBM) Failed ".
 1473:                                       "while attempting idput\n";
 1474:                            }
 1475:                        } else {
 1476:                            print $client "error: ".($!+0)
 1477: 			       ." tie(GDBM) Failed ".
 1478:                                       "while attempting idput\n";
 1479:                        }
 1480: # ----------------------------------------------------------------------- idget
 1481:                    } elsif ($userinput =~ /^idget/) {
 1482:                        my ($cmd,$udom,$what)=split(/:/,$userinput);
 1483:                        chomp($what);
 1484:                        $udom=~s/\W//g;
 1485:                        my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
 1486:                        my @queries=split(/\&/,$what);
 1487:                        my $qresult='';
 1488:                  if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER,0640)) {
 1489:                            for ($i=0;$i<=$#queries;$i++) {
 1490:                                $qresult.="$hash{$queries[$i]}&";
 1491:                            }
 1492: 			   if (untie(%hash)) {
 1493: 		              $qresult=~s/\&$//;
 1494:                               print $client "$qresult\n";
 1495:                            } else {
 1496:                               print $client "error: ".($!+0)
 1497: 				  ." untie(GDBM) Failed ".
 1498:                                       "while attempting idget\n";
 1499:                            }
 1500:                        } else {
 1501:                            print $client "error: ".($!+0)
 1502: 			       ." tie(GDBM) Failed ".
 1503:                                    "while attempting idget\n";
 1504:                        }
 1505: # ---------------------------------------------------------------------- tmpput
 1506:                    } elsif ($userinput =~ /^tmpput/) {
 1507:                        my ($cmd,$what)=split(/:/,$userinput);
 1508: 		       my $store;
 1509:                        $tmpsnum++;
 1510:                        my $id=$$.'_'.$clientip.'_'.$tmpsnum;
 1511:                        $id=~s/\W/\_/g;
 1512:                        $what=~s/\n//g;
 1513:                        my $execdir=$perlvar{'lonDaemons'};
 1514:                        if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
 1515: 			   print $store $what;
 1516: 			   close $store;
 1517: 			   print $client "$id\n";
 1518: 		       }
 1519: 		       else {
 1520: 			   print $client "error: ".($!+0)
 1521: 			       ."IO::File->new Failed ".
 1522:                                    "while attempting tmpput\n";
 1523: 		       }
 1524: 
 1525: # ---------------------------------------------------------------------- tmpget
 1526:                    } elsif ($userinput =~ /^tmpget/) {
 1527:                        my ($cmd,$id)=split(/:/,$userinput);
 1528:                        chomp($id);
 1529:                        $id=~s/\W/\_/g;
 1530:                        my $store;
 1531:                        my $execdir=$perlvar{'lonDaemons'};
 1532:                        if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
 1533:                            my $reply=<$store>;
 1534: 			   print $client "$reply\n";
 1535:                            close $store;
 1536: 		       }
 1537: 		       else {
 1538: 			   print $client "error: ".($!+0)
 1539: 			       ."IO::File->new Failed ".
 1540:                                    "while attempting tmpget\n";
 1541: 		       }
 1542: 
 1543: # ---------------------------------------------------------------------- tmpdel
 1544:                    } elsif ($userinput =~ /^tmpdel/) {
 1545:                        my ($cmd,$id)=split(/:/,$userinput);
 1546:                        chomp($id);
 1547:                        $id=~s/\W/\_/g;
 1548:                        my $execdir=$perlvar{'lonDaemons'};
 1549:                        if (unlink("$execdir/tmp/$id.tmp")) {
 1550: 			   print $client "ok\n";
 1551: 		       } else {
 1552: 			   print $client "error: ".($!+0)
 1553: 			       ."Unlink tmp Failed ".
 1554:                                    "while attempting tmpdel\n";
 1555: 		       }
 1556: # -------------------------------------------------------------------------- ls
 1557:                    } elsif ($userinput =~ /^ls/) {
 1558:                        my ($cmd,$ulsdir)=split(/:/,$userinput);
 1559:                        my $ulsout='';
 1560:                        my $ulsfn;
 1561:                        if (-e $ulsdir) {
 1562:                            if(-d $ulsdir) {
 1563:                                if (opendir(LSDIR,$ulsdir)) {
 1564:                                    while ($ulsfn=readdir(LSDIR)) {
 1565:                                        my @ulsstats=stat($ulsdir.'/'.$ulsfn);
 1566:                                        $ulsout.=$ulsfn.'&'.
 1567:                                                 join('&',@ulsstats).':';
 1568:                                    }
 1569:                                    closedir(LSDIR);
 1570:                                }
 1571:                            } else {
 1572:                                my @ulsstats=stat($ulsdir);
 1573:                                $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
 1574:                            }
 1575:                        } else {
 1576:                           $ulsout='no_such_dir';
 1577:                        }
 1578:                        if ($ulsout eq '') { $ulsout='empty'; }
 1579:                        print $client "$ulsout\n";
 1580: # ------------------------------------------------------------------ Hanging up
 1581:                    } elsif (($userinput =~ /^exit/) ||
 1582:                             ($userinput =~ /^init/)) {
 1583:                        &logthis(
 1584:       "Client $clientip ($hostid{$clientip}) hanging up: $userinput");
 1585:                        print $client "bye\n";
 1586:                        $client->close();
 1587: 		       last;
 1588: # ------------------------------------------------------------- unknown command
 1589:                    } else {
 1590:                        # unknown command
 1591:                        print $client "unknown_cmd\n";
 1592:                    }
 1593: # -------------------------------------------------------------------- complete
 1594: 		   alarm(0);
 1595:                    &status('Listening to '.$hostid{$clientip});
 1596: 	       }
 1597: # --------------------------------------------- client unknown or fishy, refuse
 1598:             } else {
 1599: 	        print $client "refused\n";
 1600:                 $client->close();
 1601:                 &logthis("<font color=blue>WARNING: "
 1602:                 ."Rejected client $clientip, closing connection</font>");
 1603:             }
 1604: 	}             
 1605: 
 1606: # =============================================================================
 1607:        
 1608: 	&logthis("<font color=red>CRITICAL: "
 1609: 		 ."Disconnect from $clientip ($hostid{$clientip})</font>");    
 1610: 
 1611: 
 1612:         # this exit is VERY important, otherwise the child will become
 1613:         # a producer of more and more children, forking yourself into
 1614:         # process death.
 1615:         exit;
 1616:     
 1617: }
 1618: 
 1619: 
 1620: #
 1621: #   Checks to see if the input roleput request was to set
 1622: # an author role.  If so, invokes the lchtmldir script to set
 1623: # up a correct public_html 
 1624: # Parameters:
 1625: #    request   - The request sent to the rolesput subchunk.
 1626: #                We're looking for  /domain/_au
 1627: #    domain    - The domain in which the user is having roles doctored.
 1628: #    user      - Name of the user for which the role is being put.
 1629: #    authtype  - The authentication type associated with the user.
 1630: #
 1631: sub ManagePermissions
 1632: {
 1633:     my $request = shift;
 1634:     my $domain  = shift;
 1635:     my $user    = shift;
 1636:     my $authtype= shift;
 1637: 
 1638:     # See if the request is of the form /$domain/_au
 1639: 
 1640:     if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
 1641: 	my $execdir = $perlvar{'lonDaemons'};
 1642: 	my $userhome= "/home/$user" ;
 1643: 	Debug("system $execdir/lchtmldir $userhome $system $authtype");
 1644: 	system("$execdir/lchtmldir $userhome $user $authtype");
 1645:     }
 1646: }
 1647: #
 1648: #   GetAuthType - Determines the authorization type of a user in a domain.
 1649: 
 1650: #     Returns the authorization type or nouser if there is no such user.
 1651: #
 1652: sub GetAuthType 
 1653: {
 1654:     my $domain = shift;
 1655:     my $user   = shift;
 1656: 
 1657:     Debug("GetAuthType( $domain, $user ) \n");
 1658:     my $proname    = &propath($domain, $user); 
 1659:     my $passwdfile = "$proname/passwd";
 1660:     if( -e $passwdfile ) {
 1661: 	my $pf = IO::File->new($passwdfile);
 1662: 	my $realpassword = <$pf>;
 1663: 	chomp($realpassword);
 1664: 	Debug("Password info = $realpassword\n");
 1665: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
 1666: 	Debug("Authtype = $authtype, content = $contentpwd\n");
 1667: 	my $availinfo = '';
 1668: 	if($authtype eq 'krb4' or $authtype eq 'krb5') {
 1669: 	    $availinfo = $contentpwd;
 1670: 	}
 1671: 
 1672: 	return "$authtype:$availinfo";
 1673:     }
 1674:     else {
 1675: 	Debug("Returning nouser");
 1676: 	return "nouser";
 1677:     }
 1678: }
 1679: 
 1680: sub addline {
 1681:     my ($fname,$hostid,$ip,$newline)=@_;
 1682:     my $contents;
 1683:     my $found=0;
 1684:     my $expr='^'.$hostid.':'.$ip.':';
 1685:     $expr =~ s/\./\\\./g;
 1686:     if ($sh=IO::File->new("$fname.subscription")) {
 1687: 	while (my $subline=<$sh>) {
 1688: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
 1689: 	}
 1690: 	$sh->close();
 1691:     }
 1692:     $sh=IO::File->new(">$fname.subscription");
 1693:     if ($contents) { print $sh $contents; }
 1694:     if ($newline) { print $sh $newline; }
 1695:     $sh->close();
 1696:     return $found;
 1697: }
 1698: 
 1699: sub getchat {
 1700:     my ($cdom,$cname)=@_;
 1701:     my %hash;
 1702:     my $proname=&propath($cdom,$cname);
 1703:     my @entries=();
 1704:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 1705: 	    &GDBM_READER(),0640)) {
 1706: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 1707: 	untie %hash;
 1708:     }
 1709:     return @entries;
 1710: }
 1711: 
 1712: sub chatadd {
 1713:     my ($cdom,$cname,$newchat)=@_;
 1714:     my %hash;
 1715:     my $proname=&propath($cdom,$cname);
 1716:     my @entries=();
 1717:     if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
 1718: 	    &GDBM_WRCREAT(),0640)) {
 1719: 	@entries=map { $_.':'.$hash{$_} } sort keys %hash;
 1720: 	my $time=time;
 1721: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
 1722: 	my ($thentime,$idnum)=split(/\_/,$lastid);
 1723: 	my $newid=$time.'_000000';
 1724: 	if ($thentime==$time) {
 1725: 	    $idnum=~s/^0+//;
 1726: 	    $idnum++;
 1727: 	    $idnum=substr('000000'.$idnum,-6,6);
 1728: 	    $newid=$time.'_'.$idnum;
 1729: 	}
 1730: 	$hash{$newid}=$newchat;
 1731: 	my $expired=$time-3600;
 1732: 	foreach (keys %hash) {
 1733: 	    my ($thistime)=($_=~/(\d+)\_/);
 1734: 	    if ($thistime<$expired) {
 1735: 		delete $hash{$_};
 1736: 	    }
 1737: 	}
 1738: 	untie %hash;
 1739:     }
 1740: }
 1741: 
 1742: sub unsub {
 1743:     my ($fname,$clientip)=@_;
 1744:     my $result;
 1745:     if (unlink("$fname.$hostid{$clientip}")) {
 1746: 	$result="ok\n";
 1747:     } else {
 1748: 	$result="not_subscribed\n";
 1749:     }
 1750:     if (-e "$fname.subscription") {
 1751: 	my $found=&addline($fname,$hostid{$clientip},$clientip,'');
 1752: 	if ($found) { $result="ok\n"; }
 1753:     } else {
 1754: 	if ($result != "ok\n") { $result="not_subscribed\n"; }
 1755:     }
 1756:     return $result;
 1757: }
 1758: 
 1759: sub currentversion {
 1760:     my $fname=shift;
 1761:     my $version=-1;
 1762:     my $ulsdir='';
 1763:     if ($fname=~/^(.+)\/[^\/]+$/) {
 1764:        $ulsdir=$1;
 1765:     }
 1766:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
 1767:     $fname=~s/\.(\w+(?:\.meta)*)$/\.\(\\d\+\)\.$1\$/;
 1768: 
 1769:     if (-e $fname) { $version=1; }
 1770:     if (-e $ulsdir) {
 1771:        if(-d $ulsdir) {
 1772:           if (opendir(LSDIR,$ulsdir)) {
 1773:              while ($ulsfn=readdir(LSDIR)) {
 1774: # see if this is a regular file (ignore links produced earlier)
 1775:                  my $thisfile=$ulsdir.'/'.$ulsfn;
 1776:                  unless (-l $thisfile) {
 1777: 		    if ($thisfile=~/$fname/) {
 1778: 		        if ($1>$version) { $version=$1; }
 1779:                     }
 1780: 		 }
 1781:              }
 1782:              closedir(LSDIR);
 1783:              $version++;
 1784:           }
 1785:       }
 1786:    }
 1787:    return $version;
 1788: }
 1789: 
 1790: sub thisversion {
 1791:     my $fname=shift;
 1792:     my $version=-1;
 1793:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
 1794: 	$version=$1;
 1795:     }
 1796:     return $version;
 1797: }
 1798: 
 1799: sub subscribe {
 1800:     my ($userinput,$clientip)=@_;
 1801:     my $result;
 1802:     my ($cmd,$fname)=split(/:/,$userinput);
 1803:     my $ownership=&ishome($fname);
 1804:     if ($ownership eq 'owner') {
 1805: # explitly asking for the current version?
 1806:         unless (-e $fname) {
 1807:             my $currentversion=&currentversion($fname);
 1808: 	    if (&thisversion($fname)==$currentversion) {
 1809:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
 1810: 		    my $root=$1;
 1811:                     my $extension=$2;
 1812:                     symlink($root.'.'.$extension,
 1813:                             $root.'.'.$currentversion.'.'.$extension);
 1814:                     unless ($extension=~/\.meta$/) {
 1815:                        symlink($root.'.'.$extension.'.meta',
 1816:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
 1817: 		    }
 1818:                 }
 1819:             }
 1820:         }
 1821: 	if (-e $fname) {
 1822: 	    if (-d $fname) {
 1823: 		$result="directory\n";
 1824: 	    } else {
 1825: 		if (-e "$fname.$hostid{$clientip}") {&unsub($fname,$clientip);}
 1826: 		$now=time;
 1827: 		my $found=&addline($fname,$hostid{$clientip},$clientip,
 1828: 				   "$hostid{$clientip}:$clientip:$now\n");
 1829: 		if ($found) { $result="$fname\n"; }
 1830: 		# if they were subscribed to only meta data, delete that
 1831:                 # subscription, when you subscribe to a file you also get
 1832:                 # the metadata
 1833: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
 1834: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
 1835: 		$fname="http://$thisserver/".$fname;
 1836: 		$result="$fname\n";
 1837: 	    }
 1838: 	} else {
 1839: 	    $result="not_found\n";
 1840: 	}
 1841:     } else {
 1842: 	$result="rejected\n";
 1843:     }
 1844:     return $result;
 1845: }
 1846: 
 1847: sub make_passwd_file {
 1848:     my ($uname, $umode,$npass,$passfilename)=@_;
 1849:     my $result="ok\n";
 1850:     if ($umode eq 'krb4' or $umode eq 'krb5') {
 1851: 	{
 1852: 	    my $pf = IO::File->new(">$passfilename");
 1853: 	    print $pf "$umode:$npass\n";
 1854: 	}
 1855:     } elsif ($umode eq 'internal') {
 1856: 	my $salt=time;
 1857: 	$salt=substr($salt,6,2);
 1858: 	my $ncpass=crypt($npass,$salt);
 1859: 	{
 1860: 	    &Debug("Creating internal auth");
 1861: 	    my $pf = IO::File->new(">$passfilename");
 1862: 	    print $pf "internal:$ncpass\n"; 
 1863: 	}
 1864:     } elsif ($umode eq 'localauth') {
 1865: 	{
 1866: 	    my $pf = IO::File->new(">$passfilename");
 1867: 	    print $pf "localauth:$npass\n";
 1868: 	}
 1869:     } elsif ($umode eq 'unix') {
 1870: 	{
 1871: 	    my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
 1872: 	    {
 1873: 		&Debug("Executing external: ".$execpath);
 1874: 		&Debug("user  = ".$uname.", Password =". $npass);
 1875: 		my $se = IO::File->new("|$execpath > /home/www/lcuseradd.log");
 1876: 		print $se "$uname\n";
 1877: 		print $se "$npass\n";
 1878: 		print $se "$npass\n";
 1879: 	    }
 1880: 	    my $useraddok = $?;
 1881: 	    if($useraddok > 0) {
 1882: 		&logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
 1883: 	    }
 1884: 	    my $pf = IO::File->new(">$passfilename");
 1885: 	    print $pf "unix:\n";
 1886: 	}
 1887:     } elsif ($umode eq 'none') {
 1888: 	{
 1889: 	    my $pf = IO::File->new(">$passfilename");
 1890: 	    print $pf "none:\n";
 1891: 	}
 1892:     } else {
 1893: 	$result="auth_mode_error\n";
 1894:     }
 1895:     return $result;
 1896: }
 1897: 
 1898: # ----------------------------------- POD (plain old documentation, CPAN style)
 1899: 
 1900: =head1 NAME
 1901: 
 1902: lond - "LON Daemon" Server (port "LOND" 5663)
 1903: 
 1904: =head1 SYNOPSIS
 1905: 
 1906: Usage: B<lond>
 1907: 
 1908: Should only be run as user=www.  This is a command-line script which
 1909: is invoked by B<loncron>.  There is no expectation that a typical user
 1910: will manually start B<lond> from the command-line.  (In other words,
 1911: DO NOT START B<lond> YOURSELF.)
 1912: 
 1913: =head1 DESCRIPTION
 1914: 
 1915: There are two characteristics associated with the running of B<lond>,
 1916: PROCESS MANAGEMENT (starting, stopping, handling child processes)
 1917: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
 1918: subscriptions, etc).  These are described in two large
 1919: sections below.
 1920: 
 1921: B<PROCESS MANAGEMENT>
 1922: 
 1923: Preforker - server who forks first. Runs as a daemon. HUPs.
 1924: Uses IDEA encryption
 1925: 
 1926: B<lond> forks off children processes that correspond to the other servers
 1927: in the network.  Management of these processes can be done at the
 1928: parent process level or the child process level.
 1929: 
 1930: B<logs/lond.log> is the location of log messages.
 1931: 
 1932: The process management is now explained in terms of linux shell commands,
 1933: subroutines internal to this code, and signal assignments:
 1934: 
 1935: =over 4
 1936: 
 1937: =item *
 1938: 
 1939: PID is stored in B<logs/lond.pid>
 1940: 
 1941: This is the process id number of the parent B<lond> process.
 1942: 
 1943: =item *
 1944: 
 1945: SIGTERM and SIGINT
 1946: 
 1947: Parent signal assignment:
 1948:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
 1949: 
 1950: Child signal assignment:
 1951:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
 1952: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
 1953:  to restart a new child.)
 1954: 
 1955: Command-line invocations:
 1956:  B<kill> B<-s> SIGTERM I<PID>
 1957:  B<kill> B<-s> SIGINT I<PID>
 1958: 
 1959: Subroutine B<HUNTSMAN>:
 1960:  This is only invoked for the B<lond> parent I<PID>.
 1961: This kills all the children, and then the parent.
 1962: The B<lonc.pid> file is cleared.
 1963: 
 1964: =item *
 1965: 
 1966: SIGHUP
 1967: 
 1968: Current bug:
 1969:  This signal can only be processed the first time
 1970: on the parent process.  Subsequent SIGHUP signals
 1971: have no effect.
 1972: 
 1973: Parent signal assignment:
 1974:  $SIG{HUP}  = \&HUPSMAN;
 1975: 
 1976: Child signal assignment:
 1977:  none (nothing happens)
 1978: 
 1979: Command-line invocations:
 1980:  B<kill> B<-s> SIGHUP I<PID>
 1981: 
 1982: Subroutine B<HUPSMAN>:
 1983:  This is only invoked for the B<lond> parent I<PID>,
 1984: This kills all the children, and then the parent.
 1985: The B<lond.pid> file is cleared.
 1986: 
 1987: =item *
 1988: 
 1989: SIGUSR1
 1990: 
 1991: Parent signal assignment:
 1992:  $SIG{USR1} = \&USRMAN;
 1993: 
 1994: Child signal assignment:
 1995:  $SIG{USR1}= \&logstatus;
 1996: 
 1997: Command-line invocations:
 1998:  B<kill> B<-s> SIGUSR1 I<PID>
 1999: 
 2000: Subroutine B<USRMAN>:
 2001:  When invoked for the B<lond> parent I<PID>,
 2002: SIGUSR1 is sent to all the children, and the status of
 2003: each connection is logged.
 2004: 
 2005: =item *
 2006: 
 2007: SIGCHLD
 2008: 
 2009: Parent signal assignment:
 2010:  $SIG{CHLD} = \&REAPER;
 2011: 
 2012: Child signal assignment:
 2013:  none
 2014: 
 2015: Command-line invocations:
 2016:  B<kill> B<-s> SIGCHLD I<PID>
 2017: 
 2018: Subroutine B<REAPER>:
 2019:  This is only invoked for the B<lond> parent I<PID>.
 2020: Information pertaining to the child is removed.
 2021: The socket port is cleaned up.
 2022: 
 2023: =back
 2024: 
 2025: B<SERVER-SIDE ACTIVITIES>
 2026: 
 2027: Server-side information can be accepted in an encrypted or non-encrypted
 2028: method.
 2029: 
 2030: =over 4
 2031: 
 2032: =item ping
 2033: 
 2034: Query a client in the hosts.tab table; "Are you there?"
 2035: 
 2036: =item pong
 2037: 
 2038: Respond to a ping query.
 2039: 
 2040: =item ekey
 2041: 
 2042: Read in encrypted key, make cipher.  Respond with a buildkey.
 2043: 
 2044: =item load
 2045: 
 2046: Respond with CPU load based on a computation upon /proc/loadavg.
 2047: 
 2048: =item currentauth
 2049: 
 2050: Reply with current authentication information (only over an
 2051: encrypted channel).
 2052: 
 2053: =item auth
 2054: 
 2055: Only over an encrypted channel, reply as to whether a user's
 2056: authentication information can be validated.
 2057: 
 2058: =item passwd
 2059: 
 2060: Allow for a password to be set.
 2061: 
 2062: =item makeuser
 2063: 
 2064: Make a user.
 2065: 
 2066: =item passwd
 2067: 
 2068: Allow for authentication mechanism and password to be changed.
 2069: 
 2070: =item home
 2071: 
 2072: Respond to a question "are you the home for a given user?"
 2073: 
 2074: =item update
 2075: 
 2076: Update contents of a subscribed resource.
 2077: 
 2078: =item unsubscribe
 2079: 
 2080: The server is unsubscribing from a resource.
 2081: 
 2082: =item subscribe
 2083: 
 2084: The server is subscribing to a resource.
 2085: 
 2086: =item log
 2087: 
 2088: Place in B<logs/lond.log>
 2089: 
 2090: =item put
 2091: 
 2092: stores hash in namespace
 2093: 
 2094: =item rolesput
 2095: 
 2096: put a role into a user's environment
 2097: 
 2098: =item get
 2099: 
 2100: returns hash with keys from array
 2101: reference filled in from namespace
 2102: 
 2103: =item eget
 2104: 
 2105: returns hash with keys from array
 2106: reference filled in from namesp (encrypts the return communication)
 2107: 
 2108: =item rolesget
 2109: 
 2110: get a role from a user's environment
 2111: 
 2112: =item del
 2113: 
 2114: deletes keys out of array from namespace
 2115: 
 2116: =item keys
 2117: 
 2118: returns namespace keys
 2119: 
 2120: =item dump
 2121: 
 2122: dumps the complete (or key matching regexp) namespace into a hash
 2123: 
 2124: =item store
 2125: 
 2126: stores hash permanently
 2127: for this url; hashref needs to be given and should be a \%hashname; the
 2128: remaining args aren't required and if they aren't passed or are '' they will
 2129: be derived from the ENV
 2130: 
 2131: =item restore
 2132: 
 2133: returns a hash for a given url
 2134: 
 2135: =item querysend
 2136: 
 2137: Tells client about the lonsql process that has been launched in response
 2138: to a sent query.
 2139: 
 2140: =item queryreply
 2141: 
 2142: Accept information from lonsql and make appropriate storage in temporary
 2143: file space.
 2144: 
 2145: =item idput
 2146: 
 2147: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
 2148: for each student, defined perhaps by the institutional Registrar.)
 2149: 
 2150: =item idget
 2151: 
 2152: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
 2153: for each student, defined perhaps by the institutional Registrar.)
 2154: 
 2155: =item tmpput
 2156: 
 2157: Accept and store information in temporary space.
 2158: 
 2159: =item tmpget
 2160: 
 2161: Send along temporarily stored information.
 2162: 
 2163: =item ls
 2164: 
 2165: List part of a user's directory.
 2166: 
 2167: =item Hanging up (exit or init)
 2168: 
 2169: What to do when a client tells the server that they (the client)
 2170: are leaving the network.
 2171: 
 2172: =item unknown command
 2173: 
 2174: If B<lond> is sent an unknown command (not in the list above),
 2175: it replys to the client "unknown_cmd".
 2176: 
 2177: =item UNKNOWN CLIENT
 2178: 
 2179: If the anti-spoofing algorithm cannot verify the client,
 2180: the client is rejected (with a "refused" message sent
 2181: to the client, and the connection is closed.
 2182: 
 2183: =back
 2184: 
 2185: =head1 PREREQUISITES
 2186: 
 2187: IO::Socket
 2188: IO::File
 2189: Apache::File
 2190: Symbol
 2191: POSIX
 2192: Crypt::IDEA
 2193: LWP::UserAgent()
 2194: GDBM_File
 2195: Authen::Krb4
 2196: Authen::Krb5
 2197: 
 2198: =head1 COREQUISITES
 2199: 
 2200: =head1 OSNAMES
 2201: 
 2202: linux
 2203: 
 2204: =head1 SCRIPT CATEGORIES
 2205: 
 2206: Server/Process
 2207: 
 2208: =cut

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