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