File:  [LON-CAPA] / loncom / lond
Revision 1.90: download - view: text, annotated - select for diffs
Tue Aug 13 00:37:18 2002 UTC (21 years, 8 months ago) by stredwic
Branches: MAIN
CVS tags: version_0_5_1, version_0_5, HEAD
First, added unescaping of $key in lond dump command.
Next, I added a new way to download student course data.  There are now
two functions for storing data, DownloadStudentCourseData and
DownloadStudentCourseDataSeparate.  These two functions base their running
on input parameters.  The option parameters are whether or not to check
the date for downloading, whether or not to store all the dumped data or
extract out the data you want, whether or not to display a status window.
The extracting data parameter will be best utilized if someone adds in the
ability to send a list of what parameters are desired and perhaps some simple
commands to affect how that data is processed, like tries, sum would
sum record the sum of all the tries for a student.  This is just an idea.

Currently, I have all the statistics modules using the extract ability.
This slightly increases in download time, but drastically reduces cache
size.  Possible ideas include pushing the extract to the lond side with a
list of parameter/commands, or even downloading everything to a temp cache,
then extract the necessary data into the cache then removing the temp
cache.  There are lots of other possibilities, which can change the download
time, cache size, and other factors.  Now, only loncoursedata handles the
downloading of data to a hash.

lonstudentassessment was changed slightly to remove ' ' as a link if the
student actually hadn't attempted the problem.

lonproblemanalysis was updated for the new str2hash type functions.  There
are a couple of (cludges/fixes) for it.  Depending on whether or not the
str2hash type functions are changed, these may or may not need to be
updated.

lonproblemstatistics was drastically overhauled.  Most of the processing
was removed.  Now, it just does its few statistics functions and outputs
the table.  Currently, I broke the graph, discussion column, and
discriminant factor columns.  These will be fixed on the next commit soon.
There is also no caching done.  This will also be remedied soon.  The
problem that will need attention with caching is to know when to update
the statistics cached data when a student's course data is updated.

Lastly, I plan to add perhaps a toggle legend display button, another graph
button(percentage correct), a button to send the CSV format(not just display),
and add a toggle button for sorting within a sequence and sorting all
the problems.

Also, I changed the look and feel to be the same as the class list page.
Also, the displaying of sequence headers and child sequences are not
working.  This will be fixed, but thought will be put into how best to
make it look and have a similiar fill for all the table combinations.

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

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