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