Annotation of loncom/lond, revision 1.133

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

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