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