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