Annotation of loncom/lond, revision 1.117

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

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