Annotation of loncom/lond, revision 1.162
1.1 albertel 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60 www 4: #
1.162 ! matthew 5: # $Id: lond,v 1.161 2003/11/11 12:39:14 foxr Exp $
1.60 www 6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
13: # the Free Software Foundation; either version 2 of the License, or
14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
1.161 foxr 27:
28:
1.60 www 29: # http://www.lon-capa.org/
30: #
1.54 harris41 31:
1.134 albertel 32: use strict;
1.80 harris41 33: use lib '/home/httpd/lib/perl/';
34: use LONCAPA::Configuration;
35:
1.1 albertel 36: use IO::Socket;
37: use IO::File;
1.126 albertel 38: #use Apache::File;
1.1 albertel 39: use Symbol;
40: use POSIX;
41: use Crypt::IDEA;
42: use LWP::UserAgent();
1.3 www 43: use GDBM_File;
44: use Authen::Krb4;
1.91 albertel 45: use Authen::Krb5;
1.49 albertel 46: use lib '/home/httpd/lib/perl/';
47: use localauth;
1.143 foxr 48: use File::Copy;
1.1 albertel 49:
1.77 foxr 50: my $DEBUG = 0; # Non zero to enable debug log entries.
51:
1.57 www 52: my $status='';
53: my $lastlog='';
54:
1.162 ! matthew 55: my $VERSION='$Revision: 1.161 $'; #' stupid emacs
1.121 albertel 56: my $remoteVERSION;
1.115 albertel 57: my $currenthostid;
58: my $currentdomainid;
1.134 albertel 59:
60: my $client;
1.140 foxr 61: my $clientip;
1.161 foxr 62: my $clientname;
1.140 foxr 63:
1.134 albertel 64: my $server;
65: my $thisserver;
66:
1.161 foxr 67: #
68: # Connection type is:
69: # client - All client actions are allowed
70: # manager - only management functions allowed.
71: # both - Both management and client actions are allowed
72: #
73:
74: my $ConnectionType;
75:
1.134 albertel 76: my %hostid;
77: my %hostdom;
78: my %hostip;
1.161 foxr 79:
80: my %managers; # Ip -> manager names
81:
1.141 foxr 82: my %perlvar; # Will have the apache conf defined perl vars.
1.134 albertel 83:
1.96 foxr 84: #
85: # The array below are password error strings."
86: #
1.97 foxr 87: my $lastpwderror = 13; # Largest error number from lcpasswd.
1.96 foxr 88: my @passwderrors = ("ok",
89: "lcpasswd must be run as user 'www'",
90: "lcpasswd got incorrect number of arguments",
91: "lcpasswd did not get the right nubmer of input text lines",
92: "lcpasswd too many simultaneous pwd changes in progress",
93: "lcpasswd User does not exist.",
94: "lcpasswd Incorrect current passwd",
95: "lcpasswd Unable to su to root.",
96: "lcpasswd Cannot set new passwd.",
97: "lcpasswd Username has invalid characters",
1.97 foxr 98: "lcpasswd Invalid characters in password",
99: "11", "12",
100: "lcpasswd Password mismatch");
101:
102:
103: # The array below are lcuseradd error strings.:
104:
105: my $lastadderror = 13;
106: my @adderrors = ("ok",
107: "User ID mismatch, lcuseradd must run as user www",
108: "lcuseradd Incorrect number of command line parameters must be 3",
109: "lcuseradd Incorrect number of stdinput lines, must be 3",
110: "lcuseradd Too many other simultaneous pwd changes in progress",
111: "lcuseradd User does not exist",
1.153 www 112: "lcuseradd Unable to make www member of users's group",
1.97 foxr 113: "lcuseradd Unable to su to root",
114: "lcuseradd Unable to set password",
1.153 www 115: "lcuseradd Usrname has invalid characters",
1.97 foxr 116: "lcuseradd Password has an invalid character",
117: "lcuseradd User already exists",
118: "lcuseradd Could not add user.",
119: "lcuseradd Password mismatch");
120:
1.96 foxr 121:
122: #
1.140 foxr 123: # GetCertificate: Given a transaction that requires a certificate,
124: # this function will extract the certificate from the transaction
125: # request. Note that at this point, the only concept of a certificate
126: # is the hostname to which we are connected.
127: #
128: # Parameter:
129: # request - The request sent by our client (this parameterization may
130: # need to change when we really use a certificate granting
131: # authority.
132: #
133: sub GetCertificate {
134: my $request = shift;
135:
136: return $clientip;
137: }
1.161 foxr 138:
139: #
140: # Return true if client is a manager.
141: #
142: sub isManager {
143: return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
144: }
145: #
146: # Return tru if client can do client functions
147: #
148: sub isClient {
149: return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
150: }
151:
152:
1.156 foxr 153: #
154: # ReadManagerTable: Reads in the current manager table. For now this is
155: # done on each manager authentication because:
156: # - These authentications are not frequent
157: # - This allows dynamic changes to the manager table
158: # without the need to signal to the lond.
159: #
160:
161: sub ReadManagerTable {
162:
163: # Clean out the old table first..
164:
165: foreach my $key (keys %managers) {
166: delete $managers{$key};
167: }
168:
169: my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
170: if (!open (MANAGERS, $tablename)) {
171: logthis('<font color="red">No manager table. Nobody can manage!!</font>');
172: return;
173: }
174: while(my $host = <MANAGERS>) {
175: chomp($host);
1.161 foxr 176: if (!defined $hostip{$host}) { # This is a non cluster member
177:
178: # The entry is of the form:
179: # cluname:hostname
180: # cluname - A 'cluster hostname' is needed in order to negotiate
181: # the host key.
182: # hostname- The dns name of the host.
183: #
184:
185: my($cluname, $dnsname) = split(/:/, $host);
186: open(MGRPIPE, "/usr/bin/host $dnsname |") || die "Can't make host pipeline";
187: my $dnsinfo = <MGRPIPE>;
188: chomp $dnsinfo;
189: close MGRPIPE;
190: my($jname, $jhas, $jaddress, $hostip) = split(/ /, $dnsinfo);
191: $managers{$hostip} = $cluname;
1.156 foxr 192: } else {
1.161 foxr 193: $managers{$hostip{$host}} = $host; # Use info from cluster tab if clumemeber
1.156 foxr 194: }
195: }
196: }
1.140 foxr 197:
198: #
199: # ValidManager: Determines if a given certificate represents a valid manager.
200: # in this primitive implementation, the 'certificate' is
201: # just the connecting loncapa client name. This is checked
202: # against a valid client list in the configuration.
203: #
204: #
205: sub ValidManager {
206: my $certificate = shift;
207:
1.156 foxr 208: ReadManagerTable;
209:
210: my $hostname = $hostid{$certificate};
211:
212:
213: if ($hostname ne undef) {
214: if($managers{$hostname} ne undef) {
215: &logthis('<font color="yellow">Authenticating manager'.
216: " $hostname</font>");
217: return 1;
218: } else {
219: &logthis('<font color="red" failed manager authentication '.
220: $hostname." is not a valid manager host</font>");
221: return 0;
222: }
1.140 foxr 223: } else {
224: &logthis('<font color="red"> Failed manager authentication '.
225: "$certificate </font>");
1.156 foxr 226: return 0;
1.140 foxr 227: }
228: }
229: #
1.143 foxr 230: # CopyFile: Called as part of the process of installing a
231: # new configuration file. This function copies an existing
232: # file to a backup file.
233: # Parameters:
234: # oldfile - Name of the file to backup.
235: # newfile - Name of the backup file.
236: # Return:
237: # 0 - Failure (errno has failure reason).
238: # 1 - Success.
239: #
240: sub CopyFile {
241: my $oldfile = shift;
242: my $newfile = shift;
243:
244: # The file must exist:
245:
246: if(-e $oldfile) {
247:
248: # Read the old file.
249:
250: my $oldfh = IO::File->new("< $oldfile");
251: if(!$oldfh) {
252: return 0;
253: }
254: my @contents = <$oldfh>; # Suck in the entire file.
255:
256: # write the backup file:
257:
258: my $newfh = IO::File->new("> $newfile");
259: if(!(defined $newfh)){
260: return 0;
261: }
262: my $lines = scalar @contents;
263: for (my $i =0; $i < $lines; $i++) {
264: print $newfh ($contents[$i]);
265: }
266:
267: $oldfh->close;
268: $newfh->close;
269:
270: chmod(0660, $newfile);
271:
272: return 1;
273:
274: } else {
275: return 0;
276: }
277: }
1.157 foxr 278: #
279: # Host files are passed out with externally visible host IPs.
280: # If, for example, we are behind a fire-wall or NAT host, our
281: # internally visible IP may be different than the externally
282: # visible IP. Therefore, we always adjust the contents of the
283: # host file so that the entry for ME is the IP that we believe
284: # we have. At present, this is defined as the entry that
285: # DNS has for us. If by some chance we are not able to get a
286: # DNS translation for us, then we assume that the host.tab file
287: # is correct.
288: # BUGBUGBUG - in the future, we really should see if we can
289: # easily query the interface(s) instead.
290: # Parameter(s):
291: # contents - The contents of the host.tab to check.
292: # Returns:
293: # newcontents - The adjusted contents.
294: #
295: #
296: sub AdjustHostContents {
297: my $contents = shift;
298: my $adjusted;
299: my $me = $perlvar{'lonHostID'};
300:
301: foreach my $line (split(/\n/,$contents)) {
302: if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
303: chomp($line);
304: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
305: if ($id eq $me) {
306: open(PIPE, " /usr/bin/host $name |") || die "Cant' make host pipeline";
307: my $hostinfo = <PIPE>;
308: close PIPE;
309:
310: my ($hostname, $has, $address, $ipnew) = split(/ /,$hostinfo);
311: &logthis('<font color="green">'.
312: "hostname = $hostname me = $me, name = $name actual ip = $ipnew </font>");
313:
314: if ($hostname eq $name) { # Lookup succeeded..
315: &logthis('<font color="green"> look up ok <font>');
316: $ip = $ipnew;
317: } else {
318: &logthis('<font color="green"> Lookup failed: '
319: .$hostname." ne $name </font>");
320: }
321: # Reconstruct the host line and append to adjusted:
322:
323: my $newline = "$id:$domain:$role:$name:$ip";
324: if($maxcon ne "") { # Not all hosts have loncnew tuning params
325: $newline .= ":$maxcon:$idleto:$mincon";
326: }
327: $adjusted .= $newline."\n";
328:
329: } else { # Not me, pass unmodified.
330: $adjusted .= $line."\n";
331: }
332: } else { # Blank or comment never re-written.
333: $adjusted .= $line."\n"; # Pass blanks and comments as is.
334: }
335: }
336: return $adjusted;
337: }
1.143 foxr 338: #
339: # InstallFile: Called to install an administrative file:
340: # - The file is created with <name>.tmp
341: # - The <name>.tmp file is then mv'd to <name>
342: # This lugubrious procedure is done to ensure that we are never without
343: # a valid, even if dated, version of the file regardless of who crashes
344: # and when the crash occurs.
345: #
346: # Parameters:
347: # Name of the file
348: # File Contents.
349: # Return:
350: # nonzero - success.
351: # 0 - failure and $! has an errno.
352: #
353: sub InstallFile {
354: my $Filename = shift;
355: my $Contents = shift;
356: my $TempFile = $Filename.".tmp";
357:
358: # Open the file for write:
359:
360: my $fh = IO::File->new("> $TempFile"); # Write to temp.
361: if(!(defined $fh)) {
362: &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
363: return 0;
364: }
365: # write the contents of the file:
366:
367: print $fh ($Contents);
368: $fh->close; # In case we ever have a filesystem w. locking
369:
370: chmod(0660, $TempFile);
371:
372: # Now we can move install the file in position.
373:
374: move($TempFile, $Filename);
375:
376: return 1;
377: }
378:
379: #
1.141 foxr 380: # PushFile: Called to do an administrative push of a file.
381: # - Ensure the file being pushed is one we support.
382: # - Backup the old file to <filename.saved>
383: # - Separate the contents of the new file out from the
384: # rest of the request.
385: # - Write the new file.
386: # Parameter:
387: # Request - The entire user request. This consists of a : separated
388: # string pushfile:tablename:contents.
389: # NOTE: The contents may have :'s in it as well making things a bit
390: # more interesting... but not much.
391: # Returns:
392: # String to send to client ("ok" or "refused" if bad file).
393: #
394: sub PushFile {
395: my $request = shift;
396: my ($command, $filename, $contents) = split(":", $request, 3);
397:
398: # At this point in time, pushes for only the following tables are
399: # supported:
400: # hosts.tab ($filename eq host).
401: # domain.tab ($filename eq domain).
402: # Construct the destination filename or reject the request.
403: #
404: # lonManage is supposed to ensure this, however this session could be
405: # part of some elaborate spoof that managed somehow to authenticate.
406: #
407:
408: my $tablefile = $perlvar{'lonTabDir'}.'/'; # need to precede with dir.
409: if ($filename eq "host") {
410: $tablefile .= "hosts.tab";
411: } elsif ($filename eq "domain") {
412: $tablefile .= "domain.tab";
413: } else {
414: return "refused";
415: }
416: #
417: # >copy< the old table to the backup table
418: # don't rename in case system crashes/reboots etc. in the time
419: # window between a rename and write.
420: #
421: my $backupfile = $tablefile;
422: $backupfile =~ s/\.tab$/.old/;
1.143 foxr 423: if(!CopyFile($tablefile, $backupfile)) {
424: &logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
425: return "error:$!";
426: }
1.141 foxr 427: &logthis('<font color="green"> Pushfile: backed up '
428: .$tablefile." to $backupfile</font>");
429:
1.157 foxr 430: # If the file being pushed is the host file, we adjust the entry for ourself so that the
431: # IP will be our current IP as looked up in dns. Note this is only 99% good as it's possible
432: # to conceive of conditions where we don't have a DNS entry locally. This is possible in a
433: # network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
434: # that possibilty.
435:
436: if($filename eq "host") {
437: $contents = AdjustHostContents($contents);
438: }
439:
1.141 foxr 440: # Install the new file:
441:
1.143 foxr 442: if(!InstallFile($tablefile, $contents)) {
443: &logthis('<font color="red"> Pushfile: unable to install '
1.145 foxr 444: .$tablefile." $! </font>");
1.143 foxr 445: return "error:$!";
446: }
447: else {
448: &logthis('<font color="green"> Installed new '.$tablefile
449: ."</font>");
450:
451: }
452:
1.141 foxr 453:
454: # Indicate success:
455:
456: return "ok";
457:
458: }
1.145 foxr 459:
460: #
461: # Called to re-init either lonc or lond.
462: #
463: # Parameters:
464: # request - The full request by the client. This is of the form
465: # reinit:<process>
466: # where <process> is allowed to be either of
467: # lonc or lond
468: #
469: # Returns:
470: # The string to be sent back to the client either:
471: # ok - Everything worked just fine.
472: # error:why - There was a failure and why describes the reason.
473: #
474: #
475: sub ReinitProcess {
476: my $request = shift;
477:
1.146 foxr 478:
479: # separate the request (reinit) from the process identifier and
480: # validate it producing the name of the .pid file for the process.
481: #
482: #
483: my ($junk, $process) = split(":", $request);
1.147 foxr 484: my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146 foxr 485: if($process eq 'lonc') {
486: $processpidfile = $processpidfile."lonc.pid";
1.147 foxr 487: if (!open(PIDFILE, "< $processpidfile")) {
488: return "error:Open failed for $processpidfile";
489: }
490: my $loncpid = <PIDFILE>;
491: close(PIDFILE);
492: logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
493: ."</font>");
494: kill("USR2", $loncpid);
1.146 foxr 495: } elsif ($process eq 'lond') {
1.147 foxr 496: logthis('<font color="red"> Reinitializing self (lond) </font>');
497: &UpdateHosts; # Lond is us!!
1.146 foxr 498: } else {
499: &logthis('<font color="yellow" Invalid reinit request for '.$process
500: ."</font>");
501: return "error:Invalid process identifier $process";
502: }
1.145 foxr 503: return 'ok';
504: }
505:
1.141 foxr 506: #
1.96 foxr 507: # Convert an error return code from lcpasswd to a string value.
508: #
509: sub lcpasswdstrerror {
510: my $ErrorCode = shift;
1.97 foxr 511: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 512: return "lcpasswd Unrecognized error return value ".$ErrorCode;
513: } else {
1.98 foxr 514: return $passwderrors[$ErrorCode];
1.96 foxr 515: }
516: }
517:
1.97 foxr 518: #
519: # Convert an error return code from lcuseradd to a string value:
520: #
521: sub lcuseraddstrerror {
522: my $ErrorCode = shift;
523: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
524: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
525: } else {
1.98 foxr 526: return $adderrors[$ErrorCode];
1.97 foxr 527: }
528: }
529:
1.23 harris41 530: # grabs exception and records it to log before exiting
531: sub catchexception {
1.27 albertel 532: my ($error)=@_;
1.25 www 533: $SIG{'QUIT'}='DEFAULT';
534: $SIG{__DIE__}='DEFAULT';
1.23 harris41 535: &logthis("<font color=red>CRITICAL: "
1.134 albertel 536: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27 albertel 537: ."a crash with this error msg->[$error]</font>");
1.57 www 538: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 539: if ($client) { print $client "error: $error\n"; }
1.59 www 540: $server->close();
1.27 albertel 541: die($error);
1.23 harris41 542: }
543:
1.63 www 544: sub timeout {
545: &logthis("<font color=ref>CRITICAL: TIME OUT ".$$."</font>");
546: &catchexception('Timeout');
547: }
1.22 harris41 548: # -------------------------------- Set signal handlers to record abnormal exits
549:
550: $SIG{'QUIT'}=\&catchexception;
551: $SIG{__DIE__}=\&catchexception;
552:
1.81 matthew 553: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 554: &status("Read loncapa.conf and loncapa_apache.conf");
555: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 556: %perlvar=%{$perlvarref};
1.80 harris41 557: undef $perlvarref;
1.19 www 558:
1.35 harris41 559: # ----------------------------- Make sure this process is running from user=www
560: my $wwwid=getpwnam('www');
561: if ($wwwid!=$<) {
1.134 albertel 562: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
563: my $subj="LON: $currenthostid User ID mismatch";
1.37 harris41 564: system("echo 'User ID mismatch. lond must be run as user www.' |\
1.35 harris41 565: mailto $emailto -s '$subj' > /dev/null");
566: exit 1;
567: }
568:
1.19 www 569: # --------------------------------------------- Check if other instance running
570:
571: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
572:
573: if (-e $pidfile) {
574: my $lfh=IO::File->new("$pidfile");
575: my $pide=<$lfh>;
576: chomp($pide);
1.29 harris41 577: if (kill 0 => $pide) { die "already running"; }
1.19 www 578: }
1.1 albertel 579:
580: # ------------------------------------------------------------- Read hosts file
581:
582:
583:
584: # establish SERVER socket, bind and listen.
585: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
586: Type => SOCK_STREAM,
587: Proto => 'tcp',
588: Reuse => 1,
589: Listen => 10 )
1.29 harris41 590: or die "making socket: $@\n";
1.1 albertel 591:
592: # --------------------------------------------------------- Do global variables
593:
594: # global variables
595:
1.134 albertel 596: my %children = (); # keys are current child process IDs
597: my $children = 0; # current number of children
1.1 albertel 598:
599: sub REAPER { # takes care of dead children
600: $SIG{CHLD} = \&REAPER;
601: my $pid = wait;
1.67 albertel 602: if (defined($children{$pid})) {
603: &logthis("Child $pid died");
604: $children --;
605: delete $children{$pid};
606: } else {
607: &logthis("Unknown Child $pid died");
608: }
1.1 albertel 609: }
610:
611: sub HUNTSMAN { # signal handler for SIGINT
612: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
613: kill 'INT' => keys %children;
1.59 www 614: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 615: my $execdir=$perlvar{'lonDaemons'};
616: unlink("$execdir/logs/lond.pid");
1.9 www 617: &logthis("<font color=red>CRITICAL: Shutting down</font>");
1.1 albertel 618: exit; # clean up with dignity
619: }
620:
621: sub HUPSMAN { # signal handler for SIGHUP
622: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
623: kill 'INT' => keys %children;
1.59 www 624: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.9 www 625: &logthis("<font color=red>CRITICAL: Restarting</font>");
1.134 albertel 626: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 627: unlink("$execdir/logs/lond.pid");
1.1 albertel 628: exec("$execdir/lond"); # here we go again
629: }
630:
1.144 foxr 631: #
1.148 foxr 632: # Kill off hashes that describe the host table prior to re-reading it.
633: # Hashes affected are:
634: # %hostid, %hostdom %hostip
635: #
636: sub KillHostHashes {
637: foreach my $key (keys %hostid) {
638: delete $hostid{$key};
639: }
640: foreach my $key (keys %hostdom) {
641: delete $hostdom{$key};
642: }
643: foreach my $key (keys %hostip) {
644: delete $hostip{$key};
645: }
646: }
647: #
648: # Read in the host table from file and distribute it into the various hashes:
649: #
650: # - %hostid - Indexed by IP, the loncapa hostname.
651: # - %hostdom - Indexed by loncapa hostname, the domain.
652: # - %hostip - Indexed by hostid, the Ip address of the host.
653: sub ReadHostTable {
654:
655: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
656:
657: while (my $configline=<CONFIG>) {
658: my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
659: chomp($ip); $ip=~s/\D+$//;
660: $hostid{$ip}=$id;
661: $hostdom{$id}=$domain;
662: $hostip{$id}=$ip;
663: if ($id eq $perlvar{'lonHostID'}) { $thisserver=$name; }
664: }
665: close(CONFIG);
666: }
667: #
668: # Reload the Apache daemon's state.
1.150 foxr 669: # This is done by invoking /home/httpd/perl/apachereload
670: # a setuid perl script that can be root for us to do this job.
1.148 foxr 671: #
672: sub ReloadApache {
1.150 foxr 673: my $execdir = $perlvar{'lonDaemons'};
674: my $script = $execdir."/apachereload";
675: system($script);
1.148 foxr 676: }
677:
678: #
1.144 foxr 679: # Called in response to a USR2 signal.
680: # - Reread hosts.tab
681: # - All children connected to hosts that were removed from hosts.tab
682: # are killed via SIGINT
683: # - All children connected to previously existing hosts are sent SIGUSR1
684: # - Our internal hosts hash is updated to reflect the new contents of
685: # hosts.tab causing connections from hosts added to hosts.tab to
686: # now be honored.
687: #
688: sub UpdateHosts {
1.147 foxr 689: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 690: #
691: # The %children hash has the set of IP's we currently have children
692: # on. These need to be matched against records in the hosts.tab
693: # Any ip's no longer in the table get killed off they correspond to
694: # either dropped or changed hosts. Note that the re-read of the table
695: # will take care of new and changed hosts as connections come into being.
696:
697:
698: KillHostHashes;
699: ReadHostTable;
700:
701: foreach my $child (keys %children) {
702: my $childip = $children{$child};
703: if(!$hostid{$childip}) {
1.149 foxr 704: logthis('<font color="blue"> UpdateHosts killing child '
705: ." $child for ip $childip </font>");
1.148 foxr 706: kill('INT', $child);
1.149 foxr 707: } else {
708: logthis('<font color="green"> keeping child for ip '
709: ." $childip (pid=$child) </font>");
1.148 foxr 710: }
711: }
712: ReloadApache;
1.144 foxr 713: }
714:
1.148 foxr 715:
1.57 www 716: sub checkchildren {
717: &initnewstatus();
718: &logstatus();
719: &logthis('Going to check on the children');
1.134 albertel 720: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 721: foreach (sort keys %children) {
1.57 www 722: sleep 1;
723: unless (kill 'USR1' => $_) {
724: &logthis ('Child '.$_.' is dead');
725: &logstatus($$.' is dead');
726: }
1.61 harris41 727: }
1.63 www 728: sleep 5;
1.113 albertel 729: $SIG{ALRM} = sub { die "timeout" };
730: $SIG{__DIE__} = 'DEFAULT';
1.63 www 731: foreach (sort keys %children) {
732: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 733: eval {
734: alarm(300);
1.63 www 735: &logthis('Child '.$_.' did not respond');
1.67 albertel 736: kill 9 => $_;
1.131 albertel 737: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
738: #$subj="LON: $currenthostid killed lond process $_";
739: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
740: #$execdir=$perlvar{'lonDaemons'};
741: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.113 albertel 742: alarm(0);
743: }
1.63 www 744: }
745: }
1.113 albertel 746: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 747: $SIG{__DIE__} = \&catchexception;
1.57 www 748: }
749:
1.1 albertel 750: # --------------------------------------------------------------------- Logging
751:
752: sub logthis {
753: my $message=shift;
754: my $execdir=$perlvar{'lonDaemons'};
755: my $fh=IO::File->new(">>$execdir/logs/lond.log");
756: my $now=time;
757: my $local=localtime($now);
1.58 www 758: $lastlog=$local.': '.$message;
1.1 albertel 759: print $fh "$local ($$): $message\n";
760: }
761:
1.77 foxr 762: # ------------------------- Conditional log if $DEBUG true.
763: sub Debug {
764: my $message = shift;
765: if($DEBUG) {
766: &logthis($message);
767: }
768: }
1.161 foxr 769:
770: #
771: # Sub to do replies to client.. this gives a hook for some
772: # debug tracing too:
773: # Parameters:
774: # fd - File open on client.
775: # reply - Text to send to client.
776: # request - Original request from client.
777: #
778: sub Reply {
779: my $fd = shift;
780: my $reply = shift;
781: my $request = shift;
782:
783: print $fd $reply;
784: Debug("Request was $request Reply was $reply");
785:
786: }
1.57 www 787: # ------------------------------------------------------------------ Log status
788:
789: sub logstatus {
790: my $docdir=$perlvar{'lonDocRoot'};
1.63 www 791: {
1.57 www 792: my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
1.115 albertel 793: print $fh $$."\t".$currenthostid."\t".$status."\t".$lastlog."\n";
1.63 www 794: $fh->close();
795: }
796: {
797: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
798: print $fh $status."\n".$lastlog."\n".time;
799: $fh->close();
800: }
1.57 www 801: }
802:
803: sub initnewstatus {
804: my $docdir=$perlvar{'lonDocRoot'};
805: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
806: my $now=time;
807: my $local=localtime($now);
808: print $fh "LOND status $local - parent $$\n\n";
1.64 www 809: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 810: while (my $filename=readdir(DIR)) {
1.64 www 811: unlink("$docdir/lon-status/londchld/$filename");
812: }
813: closedir(DIR);
1.57 www 814: }
815:
816: # -------------------------------------------------------------- Status setting
817:
818: sub status {
819: my $what=shift;
820: my $now=time;
821: my $local=localtime($now);
822: $status=$local.': '.$what;
1.103 www 823: $0='lond: '.$what.' '.$local;
1.57 www 824: }
1.11 www 825:
826: # -------------------------------------------------------- Escape Special Chars
827:
828: sub escape {
829: my $str=shift;
830: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
831: return $str;
832: }
833:
834: # ----------------------------------------------------- Un-Escape Special Chars
835:
836: sub unescape {
837: my $str=shift;
838: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
839: return $str;
840: }
841:
1.1 albertel 842: # ----------------------------------------------------------- Send USR1 to lonc
843:
844: sub reconlonc {
845: my $peerfile=shift;
846: &logthis("Trying to reconnect for $peerfile");
847: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
848: if (my $fh=IO::File->new("$loncfile")) {
849: my $loncpid=<$fh>;
850: chomp($loncpid);
851: if (kill 0 => $loncpid) {
852: &logthis("lonc at pid $loncpid responding, sending USR1");
853: kill USR1 => $loncpid;
854: } else {
1.9 www 855: &logthis(
856: "<font color=red>CRITICAL: "
857: ."lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 858: }
859: } else {
1.9 www 860: &logthis('<font color=red>CRITICAL: lonc not running, giving up</font>');
1.1 albertel 861: }
862: }
863:
864: # -------------------------------------------------- Non-critical communication
1.11 www 865:
1.1 albertel 866: sub subreply {
867: my ($cmd,$server)=@_;
868: my $peerfile="$perlvar{'lonSockDir'}/$server";
869: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
870: Type => SOCK_STREAM,
871: Timeout => 10)
872: or return "con_lost";
873: print $sclient "$cmd\n";
874: my $answer=<$sclient>;
875: chomp($answer);
876: if (!$answer) { $answer="con_lost"; }
877: return $answer;
878: }
879:
880: sub reply {
881: my ($cmd,$server)=@_;
882: my $answer;
1.115 albertel 883: if ($server ne $currenthostid) {
1.1 albertel 884: $answer=subreply($cmd,$server);
885: if ($answer eq 'con_lost') {
886: $answer=subreply("ping",$server);
887: if ($answer ne $server) {
1.115 albertel 888: &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1 albertel 889: &reconlonc("$perlvar{'lonSockDir'}/$server");
890: }
891: $answer=subreply($cmd,$server);
892: }
893: } else {
894: $answer='self_reply';
895: }
896: return $answer;
897: }
898:
1.13 www 899: # -------------------------------------------------------------- Talk to lonsql
900:
1.12 harris41 901: sub sqlreply {
902: my ($cmd)=@_;
903: my $answer=subsqlreply($cmd);
904: if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
905: return $answer;
906: }
907:
908: sub subsqlreply {
909: my ($cmd)=@_;
910: my $unixsock="mysqlsock";
911: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
912: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
913: Type => SOCK_STREAM,
914: Timeout => 10)
915: or return "con_lost";
916: print $sclient "$cmd\n";
917: my $answer=<$sclient>;
918: chomp($answer);
919: if (!$answer) { $answer="con_lost"; }
920: return $answer;
921: }
922:
1.1 albertel 923: # -------------------------------------------- Return path to profile directory
1.11 www 924:
1.1 albertel 925: sub propath {
926: my ($udom,$uname)=@_;
927: $udom=~s/\W//g;
928: $uname=~s/\W//g;
1.16 www 929: my $subdir=$uname.'__';
1.1 albertel 930: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
931: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
932: return $proname;
933: }
934:
935: # --------------------------------------- Is this the home server of an author?
1.11 www 936:
1.1 albertel 937: sub ishome {
938: my $author=shift;
939: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
940: my ($udom,$uname)=split(/\//,$author);
941: my $proname=propath($udom,$uname);
942: if (-e $proname) {
943: return 'owner';
944: } else {
945: return 'not_owner';
946: }
947: }
948:
949: # ======================================================= Continue main program
950: # ---------------------------------------------------- Fork once and dissociate
951:
1.134 albertel 952: my $fpid=fork;
1.1 albertel 953: exit if $fpid;
1.29 harris41 954: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 955:
1.29 harris41 956: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 957:
958: # ------------------------------------------------------- Write our PID on disk
959:
1.134 albertel 960: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 961: open (PIDSAVE,">$execdir/logs/lond.pid");
962: print PIDSAVE "$$\n";
963: close(PIDSAVE);
1.9 www 964: &logthis("<font color=red>CRITICAL: ---------- Starting ----------</font>");
1.57 www 965: &status('Starting');
1.1 albertel 966:
1.106 foxr 967:
1.1 albertel 968:
969: # ----------------------------------------------------- Install signal handlers
970:
1.57 www 971:
1.1 albertel 972: $SIG{CHLD} = \&REAPER;
973: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
974: $SIG{HUP} = \&HUPSMAN;
1.57 www 975: $SIG{USR1} = \&checkchildren;
1.144 foxr 976: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 977:
1.148 foxr 978: # Read the host hashes:
979:
980: ReadHostTable;
1.106 foxr 981:
982: # --------------------------------------------------------------
983: # Accept connections. When a connection comes in, it is validated
984: # and if good, a child process is created to process transactions
985: # along the connection.
986:
1.1 albertel 987: while (1) {
1.106 foxr 988: $client = $server->accept() or next;
989: make_new_child($client);
1.1 albertel 990: }
991:
992: sub make_new_child {
993: my $pid;
994: my $cipher;
995: my $sigset;
1.106 foxr 996:
997: $client = shift;
1.161 foxr 998: &logthis('<font color="green"> Attempting to start child ('.$client.
999: ")</font>");
1.1 albertel 1000: # block signal for fork
1001: $sigset = POSIX::SigSet->new(SIGINT);
1002: sigprocmask(SIG_BLOCK, $sigset)
1.29 harris41 1003: or die "Can't block SIGINT for fork: $!\n";
1.134 albertel 1004:
1.29 harris41 1005: die "fork: $!" unless defined ($pid = fork);
1.148 foxr 1006:
1007: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
1008: # connection liveness.
1009:
1010: #
1011: # Figure out who we're talking to so we can record the peer in
1012: # the pid hash.
1013: #
1014: my $caller = getpeername($client);
1015: my ($port,$iaddr)=unpack_sockaddr_in($caller);
1016: $clientip=inet_ntoa($iaddr);
1.1 albertel 1017:
1018: if ($pid) {
1019: # Parent records the child's birth and returns.
1020: sigprocmask(SIG_UNBLOCK, $sigset)
1.29 harris41 1021: or die "Can't unblock SIGINT for fork: $!\n";
1.148 foxr 1022: $children{$pid} = $clientip;
1.1 albertel 1023: $children++;
1.57 www 1024: &status('Started child '.$pid);
1.1 albertel 1025: return;
1026: } else {
1027: # Child can *not* return from this subroutine.
1028: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
1.126 albertel 1029: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
1030: #don't get intercepted
1.57 www 1031: $SIG{USR1}= \&logstatus;
1.63 www 1032: $SIG{ALRM}= \&timeout;
1.57 www 1033: $lastlog='Forked ';
1034: $status='Forked';
1035:
1.1 albertel 1036: # unblock signals
1037: sigprocmask(SIG_UNBLOCK, $sigset)
1.29 harris41 1038: or die "Can't unblock SIGINT for fork: $!\n";
1.13 www 1039:
1.134 albertel 1040: my $tmpsnum=0;
1.91 albertel 1041: #---------------------------------------------------- kerberos 5 initialization
1042: &Authen::Krb5::init_context();
1043: &Authen::Krb5::init_ets();
1044:
1.161 foxr 1045: &status('Accepted connection');
1.1 albertel 1046: # =============================================================================
1047: # do something with the connection
1048: # -----------------------------------------------------------------------------
1.148 foxr 1049: # see if we know client and check for spoof IP by challenge
1050:
1.161 foxr 1051: ReadManagerTable; # May also be a manager!!
1052:
1053: my $clientrec=($hostid{$clientip} ne undef);
1054: my $ismanager=($managers{$clientip} ne undef);
1055: $clientname = "[unknonwn]";
1056: if($clientrec) { # Establish client type.
1057: $ConnectionType = "client";
1058: $clientname = $hostid{$clientip};
1059: if($ismanager) {
1060: $ConnectionType = "both";
1061: }
1062: } else {
1063: $ConnectionType = "manager";
1064: $clientname = $managers{$clientip};
1065: }
1066: my $clientok;
1067: if ($clientrec || $ismanager) {
1068: &status("Waiting for init from $clientip $clientname");
1069: &logthis('<font color="yellow">INFO: Connection, '.
1070: $clientip.
1071: " ($clientname) connection type = $ConnectionType </font>" );
1072: &status("Connecting $clientip ($clientname))");
1073: my $remotereq=<$client>;
1074: $remotereq=~s/[^\w:]//g;
1075: if ($remotereq =~ /^init/) {
1076: &sethost("sethost:$perlvar{'lonHostID'}");
1077: my $challenge="$$".time;
1078: print $client "$challenge\n";
1079: &status(
1080: "Waiting for challenge reply from $clientip ($clientname)");
1081: $remotereq=<$client>;
1082: $remotereq=~s/\W//g;
1083: if ($challenge eq $remotereq) {
1084: $clientok=1;
1085: print $client "ok\n";
1086: } else {
1087: &logthis(
1088: "<font color=blue>WARNING: $clientip did not reply challenge</font>");
1089: &status('No challenge reply '.$clientip);
1090: }
1.2 www 1091: } else {
1.161 foxr 1092: &logthis(
1093: "<font color=blue>WARNING: "
1094: ."$clientip failed to initialize: >$remotereq< </font>");
1095: &status('No init '.$clientip);
1096: }
1097: } else {
1098: &logthis(
1099: "<font color=blue>WARNING: Unknown client $clientip</font>");
1100: &status('Hung up on '.$clientip);
1101: }
1102: if ($clientok) {
1.1 albertel 1103: # ---------------- New known client connecting, could mean machine online again
1.161 foxr 1104:
1105: foreach my $id (keys(%hostip)) {
1106: if ($hostip{$id} ne $clientip ||
1107: $hostip{$currenthostid} eq $clientip) {
1108: # no need to try to do recon's to myself
1109: next;
1.115 albertel 1110: }
1.161 foxr 1111: &reconlonc("$perlvar{'lonSockDir'}/$id");
1112: }
1113: &logthis("<font color=green>Established connection: $clientname</font>");
1114: &status('Will listen to '.$clientname);
1.1 albertel 1115: # ------------------------------------------------------------ Process requests
1.161 foxr 1116: while (my $userinput=<$client>) {
1.1 albertel 1117: chomp($userinput);
1.79 foxr 1118: Debug("Request = $userinput\n");
1.161 foxr 1119: &status('Processing '.$clientname.': '.$userinput);
1.1 albertel 1120: my $wasenc=0;
1.63 www 1121: alarm(120);
1.1 albertel 1122: # ------------------------------------------------------------ See if encrypted
1123: if ($userinput =~ /^enc/) {
1.161 foxr 1124: if ($cipher) {
1125: my ($cmd,$cmdlength,$encinput)=split(/:/,$userinput);
1126: $userinput='';
1127: for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
1128: $userinput.=
1129: $cipher->decrypt(
1130: pack("H16",substr($encinput,$encidx,16))
1131: );
1132: }
1133: $userinput=substr($userinput,0,$cmdlength);
1134: $wasenc=1;
1.1 albertel 1135: }
1136: }
1.161 foxr 1137:
1.1 albertel 1138: # ------------------------------------------------------------- Normal commands
1139: # ------------------------------------------------------------------------ ping
1.161 foxr 1140: if ($userinput =~ /^ping/) { # client only
1141: if(isClient) {
1142: print $client "$currenthostid\n";
1143: } else {
1144: Reply($client, "refused\n", $userinput);
1145: }
1.1 albertel 1146: # ------------------------------------------------------------------------ pong
1.161 foxr 1147: }elsif ($userinput =~ /^pong/) { # client only
1148: if(isClient) {
1149: my $reply=&reply("ping",$clientname);
1150: print $client "$currenthostid:$reply\n";
1151: } else {
1152: Reply($client, "refused\n", $userinput);
1153: }
1.1 albertel 1154: # ------------------------------------------------------------------------ ekey
1.161 foxr 1155: } elsif ($userinput =~ /^ekey/) { # ok for both clients & mgrs
1156: my $buildkey=time.$$.int(rand 100000);
1157: $buildkey=~tr/1-6/A-F/;
1158: $buildkey=int(rand 100000).$buildkey.int(rand 100000);
1159: my $key=$currenthostid.$clientname;
1160: $key=~tr/a-z/A-Z/;
1161: $key=~tr/G-P/0-9/;
1162: $key=~tr/Q-Z/0-9/;
1163: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
1164: $key=substr($key,0,32);
1165: my $cipherkey=pack("H32",$key);
1166: $cipher=new IDEA $cipherkey;
1167: print $client "$buildkey\n";
1.1 albertel 1168: # ------------------------------------------------------------------------ load
1.161 foxr 1169: } elsif ($userinput =~ /^load/) { # client only
1170: if (isClient) {
1171: my $loadavg;
1172: {
1173: my $loadfile=IO::File->new('/proc/loadavg');
1174: $loadavg=<$loadfile>;
1175: }
1176: $loadavg =~ s/\s.*//g;
1177: my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
1178: print $client "$loadpercent\n";
1179: } else {
1180: Reply($client, "refused\n", $userinput);
1181:
1182: }
1.127 albertel 1183: # -------------------------------------------------------------------- userload
1.161 foxr 1184: } elsif ($userinput =~ /^userload/) { # client only
1185: if(isClient) {
1186: my $userloadpercent=&userload();
1187: print $client "$userloadpercent\n";
1188: } else {
1189: Reply($client, "refused\n", $userinput);
1190:
1191: }
1.137 foxr 1192: #
1193: # Transactions requiring encryption:
1194: #
1.54 harris41 1195: # ----------------------------------------------------------------- currentauth
1.161 foxr 1196: } elsif ($userinput =~ /^currentauth/) {
1197: if (($wasenc==1) && isClient) { # Encoded & client only.
1198: my ($cmd,$udom,$uname)=split(/:/,$userinput);
1199: my $result = GetAuthType($udom, $uname);
1200: if($result eq "nouser") {
1201: print $client "unknown_user\n";
1202: }
1203: else {
1204: print $client "$result\n"
1205: }
1206: } else {
1207: Reply($client, "refused\n", $userinput);
1208:
1209: }
1.137 foxr 1210: #--------------------------------------------------------------------- pushfile
1.161 foxr 1211: } elsif($userinput =~ /^pushfile/) { # encoded & manager.
1212: if(($wasenc == 1) && isManager) {
1213: my $cert = GetCertificate($userinput);
1214: if(ValidManager($cert)) {
1215: my $reply = PushFile($userinput);
1216: print $client "$reply\n";
1217: } else {
1218: print $client "refused\n";
1219: }
1220: } else {
1221: Reply($client, "refused\n", $userinput);
1222:
1223: }
1.137 foxr 1224: #--------------------------------------------------------------------- reinit
1.161 foxr 1225: } elsif($userinput =~ /^reinit/) { # Encoded and manager
1226: if (($wasenc == 1) && isManager) {
1227: my $cert = GetCertificate($userinput);
1228: if(ValidManager($cert)) {
1229: chomp($userinput);
1230: my $reply = ReinitProcess($userinput);
1231: print $client "$reply\n";
1232: } else {
1233: print $client "refused\n";
1234: }
1235: } else {
1236: Reply($client, "refused\n", $userinput);
1237:
1238:
1239: }
1.1 albertel 1240: # ------------------------------------------------------------------------ auth
1.161 foxr 1241: } elsif ($userinput =~ /^auth/) { # Encoded and client only.
1242: if (($wasenc==1) && isClient) {
1243: my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
1244: chomp($upass);
1245: $upass=unescape($upass);
1246: my $proname=propath($udom,$uname);
1247: my $passfilename="$proname/passwd";
1248: if (-e $passfilename) {
1249: my $pf = IO::File->new($passfilename);
1250: my $realpasswd=<$pf>;
1251: chomp($realpasswd);
1252: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1253: my $pwdcorrect=0;
1254: if ($howpwd eq 'internal') {
1255: &Debug("Internal auth");
1256: $pwdcorrect=
1257: (crypt($upass,$contentpwd) eq $contentpwd);
1258: } elsif ($howpwd eq 'unix') {
1259: &Debug("Unix auth");
1260: if((getpwnam($uname))[1] eq "") { #no such user!
1261: $pwdcorrect = 0;
1262: } else {
1263: $contentpwd=(getpwnam($uname))[1];
1264: my $pwauth_path="/usr/local/sbin/pwauth";
1265: unless ($contentpwd eq 'x') {
1266: $pwdcorrect=
1267: (crypt($upass,$contentpwd) eq
1268: $contentpwd);
1269: }
1270:
1271: elsif (-e $pwauth_path) {
1272: open PWAUTH, "|$pwauth_path" or
1273: die "Cannot invoke authentication";
1274: print PWAUTH "$uname\n$upass\n";
1275: close PWAUTH;
1276: $pwdcorrect=!$?;
1277: }
1278: }
1279: } elsif ($howpwd eq 'krb4') {
1280: my $null=pack("C",0);
1281: unless ($upass=~/$null/) {
1282: my $krb4_error = &Authen::Krb4::get_pw_in_tkt
1283: ($uname,"",$contentpwd,'krbtgt',
1284: $contentpwd,1,$upass);
1285: if (!$krb4_error) {
1286: $pwdcorrect = 1;
1287: } else {
1288: $pwdcorrect=0;
1289: # log error if it is not a bad password
1290: if ($krb4_error != 62) {
1291: &logthis('krb4:'.$uname.','.$contentpwd.','.
1292: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
1293: }
1294: }
1295: }
1296: } elsif ($howpwd eq 'krb5') {
1297: my $null=pack("C",0);
1298: unless ($upass=~/$null/) {
1299: my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
1300: my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
1301: my $krbserver=&Authen::Krb5::parse_name($krbservice);
1302: my $credentials=&Authen::Krb5::cc_default();
1303: $credentials->initialize($krbclient);
1304: my $krbreturn =
1305: &Authen::Krb5::get_in_tkt_with_password(
1306: $krbclient,$krbserver,$upass,$credentials);
1.92 albertel 1307: # unless ($krbreturn) {
1308: # &logthis("Krb5 Error: ".
1309: # &Authen::Krb5::error());
1310: # }
1.161 foxr 1311: $pwdcorrect = ($krbreturn == 1);
1312: } else { $pwdcorrect=0; }
1313: } elsif ($howpwd eq 'localauth') {
1314: $pwdcorrect=&localauth::localauth($uname,$upass,
1315: $contentpwd);
1316: }
1317: if ($pwdcorrect) {
1318: print $client "authorized\n";
1319: } else {
1320: print $client "non_authorized\n";
1321: }
1322: } else {
1323: print $client "unknown_user\n";
1324: }
1325: } else {
1326: Reply($client, "refused\n", $userinput);
1327:
1328: }
1.1 albertel 1329: # ---------------------------------------------------------------------- passwd
1.161 foxr 1330: } elsif ($userinput =~ /^passwd/) { # encoded and client
1331: if (($wasenc==1) && isClient) {
1332: my
1333: ($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
1334: chomp($npass);
1335: $upass=&unescape($upass);
1336: $npass=&unescape($npass);
1337: &Debug("Trying to change password for $uname");
1338: my $proname=propath($udom,$uname);
1339: my $passfilename="$proname/passwd";
1340: if (-e $passfilename) {
1341: my $realpasswd;
1342: { my $pf = IO::File->new($passfilename);
1343: $realpasswd=<$pf>; }
1344: chomp($realpasswd);
1345: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1346: if ($howpwd eq 'internal') {
1347: &Debug("internal auth");
1348: if (crypt($upass,$contentpwd) eq $contentpwd) {
1349: my $salt=time;
1350: $salt=substr($salt,6,2);
1351: my $ncpass=crypt($npass,$salt);
1352: {
1353: my $pf;
1354: if ($pf = IO::File->new(">$passfilename")) {
1355: print $pf "internal:$ncpass\n";
1356: &logthis("Result of password change for $uname: pwchange_success");
1357: print $client "ok\n";
1358: } else {
1359: &logthis("Unable to open $uname passwd to change password");
1360: print $client "non_authorized\n";
1361: }
1362: }
1363:
1364: } else {
1365: print $client "non_authorized\n";
1366: }
1367: } elsif ($howpwd eq 'unix') {
1368: # Unix means we have to access /etc/password
1369: # one way or another.
1370: # First: Make sure the current password is
1371: # correct
1372: &Debug("auth is unix");
1373: $contentpwd=(getpwnam($uname))[1];
1374: my $pwdcorrect = "0";
1375: my $pwauth_path="/usr/local/sbin/pwauth";
1376: unless ($contentpwd eq 'x') {
1377: $pwdcorrect=
1378: (crypt($upass,$contentpwd) eq $contentpwd);
1379: } elsif (-e $pwauth_path) {
1380: open PWAUTH, "|$pwauth_path" or
1381: die "Cannot invoke authentication";
1382: print PWAUTH "$uname\n$upass\n";
1383: close PWAUTH;
1384: &Debug("exited pwauth with $? ($uname,$upass) ");
1385: $pwdcorrect=($? == 0);
1386: }
1387: if ($pwdcorrect) {
1388: my $execdir=$perlvar{'lonDaemons'};
1389: &Debug("Opening lcpasswd pipeline");
1390: my $pf = IO::File->new("|$execdir/lcpasswd > $perlvar{'lonDaemons'}/logs/lcpasswd.log");
1391: print $pf "$uname\n$npass\n$npass\n";
1392: close $pf;
1393: my $err = $?;
1394: my $result = ($err>0 ? 'pwchange_failure'
1395: : 'ok');
1396: &logthis("Result of password change for $uname: ".
1397: &lcpasswdstrerror($?));
1398: print $client "$result\n";
1399: } else {
1400: print $client "non_authorized\n";
1401: }
1402: } else {
1403: print $client "auth_mode_error\n";
1404: }
1405: } else {
1406: print $client "unknown_user\n";
1407: }
1408: } else {
1409: Reply($client, "refused\n", $userinput);
1410:
1411: }
1.31 www 1412: # -------------------------------------------------------------------- makeuser
1.161 foxr 1413: } elsif ($userinput =~ /^makeuser/) { # encoded and client.
1414: &Debug("Make user received");
1415: my $oldumask=umask(0077);
1416: if (($wasenc==1) && isClient) {
1417: my
1418: ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
1419: &Debug("cmd =".$cmd." $udom =".$udom.
1420: " uname=".$uname);
1421: chomp($npass);
1422: $npass=&unescape($npass);
1423: my $proname=propath($udom,$uname);
1424: my $passfilename="$proname/passwd";
1425: &Debug("Password file created will be:".
1426: $passfilename);
1427: if (-e $passfilename) {
1428: print $client "already_exists\n";
1429: } elsif ($udom ne $currentdomainid) {
1430: print $client "not_right_domain\n";
1431: } else {
1432: my @fpparts=split(/\//,$proname);
1433: my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
1434: my $fperror='';
1435: for (my $i=3;$i<=$#fpparts;$i++) {
1436: $fpnow.='/'.$fpparts[$i];
1437: unless (-e $fpnow) {
1438: unless (mkdir($fpnow,0777)) {
1439: $fperror="error: ".($!+0)
1440: ." mkdir failed while attempting "
1441: ."makeuser\n";
1442: }
1443: }
1444: }
1445: unless ($fperror) {
1446: my $result=&make_passwd_file($uname, $umode,$npass,
1447: $passfilename);
1448: print $client $result;
1449: } else {
1450: print $client "$fperror\n";
1451: }
1452: }
1453: } else {
1454: Reply($client, "refused\n", $userinput);
1455:
1456: }
1457: umask($oldumask);
1.55 harris41 1458: # -------------------------------------------------------------- changeuserauth
1.161 foxr 1459: } elsif ($userinput =~ /^changeuserauth/) { # encoded & client
1460: &Debug("Changing authorization");
1461: if (($wasenc==1) && isClient) {
1462: my
1463: ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
1464: chomp($npass);
1465: &Debug("cmd = ".$cmd." domain= ".$udom.
1466: "uname =".$uname." umode= ".$umode);
1467: $npass=&unescape($npass);
1468: my $proname=&propath($udom,$uname);
1469: my $passfilename="$proname/passwd";
1470: if ($udom ne $currentdomainid) {
1471: print $client "not_right_domain\n";
1472: } else {
1473: my $result=&make_passwd_file($uname, $umode,$npass,
1474: $passfilename);
1475: print $client $result;
1476: }
1477: } else {
1478: Reply($client, "refused\n", $userinput);
1479:
1480: }
1.1 albertel 1481: # ------------------------------------------------------------------------ home
1.161 foxr 1482: } elsif ($userinput =~ /^home/) { # client clear or encoded
1483: if(isClient) {
1484: my ($cmd,$udom,$uname)=split(/:/,$userinput);
1485: chomp($uname);
1486: my $proname=propath($udom,$uname);
1487: if (-e $proname) {
1488: print $client "found\n";
1489: } else {
1490: print $client "not_found\n";
1491: }
1492: } else {
1493: Reply($client, "refused\n", $userinput);
1494:
1495: }
1.1 albertel 1496: # ---------------------------------------------------------------------- update
1.161 foxr 1497: } elsif ($userinput =~ /^update/) { # client clear or encoded.
1498: if(isClient) {
1499: my ($cmd,$fname)=split(/:/,$userinput);
1500: my $ownership=ishome($fname);
1501: if ($ownership eq 'not_owner') {
1502: if (-e $fname) {
1503: my ($dev,$ino,$mode,$nlink,
1504: $uid,$gid,$rdev,$size,
1505: $atime,$mtime,$ctime,
1506: $blksize,$blocks)=stat($fname);
1507: my $now=time;
1508: my $since=$now-$atime;
1509: if ($since>$perlvar{'lonExpire'}) {
1510: my $reply=
1511: &reply("unsub:$fname","$clientname");
1512: unlink("$fname");
1513: } else {
1514: my $transname="$fname.in.transfer";
1515: my $remoteurl=
1516: &reply("sub:$fname","$clientname");
1517: my $response;
1518: {
1519: my $ua=new LWP::UserAgent;
1520: my $request=new HTTP::Request('GET',"$remoteurl");
1521: $response=$ua->request($request,$transname);
1522: }
1523: if ($response->is_error()) {
1524: unlink($transname);
1525: my $message=$response->status_line;
1526: &logthis(
1527: "LWP GET: $message for $fname ($remoteurl)");
1528: } else {
1529: if ($remoteurl!~/\.meta$/) {
1530: my $ua=new LWP::UserAgent;
1531: my $mrequest=
1532: new HTTP::Request('GET',$remoteurl.'.meta');
1533: my $mresponse=
1534: $ua->request($mrequest,$fname.'.meta');
1535: if ($mresponse->is_error()) {
1536: unlink($fname.'.meta');
1537: }
1538: }
1539: rename($transname,$fname);
1540: }
1541: }
1542: print $client "ok\n";
1543: } else {
1544: print $client "not_found\n";
1545: }
1546: } else {
1547: print $client "rejected\n";
1548: }
1549: } else {
1550: Reply($client, "refused\n", $userinput);
1551:
1552: }
1.85 www 1553: # -------------------------------------- fetch a user file from a remote server
1.161 foxr 1554: } elsif ($userinput =~ /^fetchuserfile/) { # Client clear or enc.
1555: if(isClient) {
1556: my ($cmd,$fname)=split(/:/,$userinput);
1557: my ($udom,$uname,$ufile)=split(/\//,$fname);
1558: my $udir=propath($udom,$uname).'/userfiles';
1559: unless (-e $udir) { mkdir($udir,0770); }
1560: if (-e $udir) {
1561: $ufile=~s/^[\.\~]+//;
1562: $ufile=~s/\///g;
1563: my $destname=$udir.'/'.$ufile;
1564: my $transname=$udir.'/'.$ufile.'.in.transit';
1565: my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
1566: my $response;
1567: {
1568: my $ua=new LWP::UserAgent;
1569: my $request=new HTTP::Request('GET',"$remoteurl");
1570: $response=$ua->request($request,$transname);
1571: }
1572: if ($response->is_error()) {
1573: unlink($transname);
1574: my $message=$response->status_line;
1575: &logthis("LWP GET: $message for $fname ($remoteurl)");
1576: print $client "failed\n";
1577: } else {
1578: if (!rename($transname,$destname)) {
1579: &logthis("Unable to move $transname to $destname");
1580: unlink($transname);
1581: print $client "failed\n";
1582: } else {
1583: print $client "ok\n";
1584: }
1585: }
1586: } else {
1587: print $client "not_home\n";
1588: }
1589: } else {
1590: Reply($client, "refused\n", $userinput);
1591:
1592: }
1.85 www 1593: # ------------------------------------------ authenticate access to a user file
1.161 foxr 1594: } elsif ($userinput =~ /^tokenauthuserfile/) { # Client only
1595: if(isClient) {
1596: my ($cmd,$fname,$session)=split(/:/,$userinput);
1597: chomp($session);
1598: my $reply='non_auth';
1599: if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
1600: $session.'.id')) {
1601: while (my $line=<ENVIN>) {
1602: if ($line=~/userfile\.$fname\=/) { $reply='ok'; }
1603: }
1604: close(ENVIN);
1605: print $client $reply."\n";
1606: } else {
1607: print $client "invalid_token\n";
1608: }
1609: } else {
1610: Reply($client, "refused\n", $userinput);
1611:
1612: }
1.1 albertel 1613: # ----------------------------------------------------------------- unsubscribe
1.161 foxr 1614: } elsif ($userinput =~ /^unsub/) {
1615: if(isClient) {
1616: my ($cmd,$fname)=split(/:/,$userinput);
1617: if (-e $fname) {
1618: print $client &unsub($client,$fname,$clientip);
1619: } else {
1620: print $client "not_found\n";
1621: }
1622: } else {
1623: Reply($client, "refused\n", $userinput);
1624:
1625: }
1.1 albertel 1626: # ------------------------------------------------------------------- subscribe
1.161 foxr 1627: } elsif ($userinput =~ /^sub/) {
1628: if(isClient) {
1629: print $client &subscribe($userinput,$clientip);
1630: } else {
1631: Reply($client, "refused\n", $userinput);
1632:
1633: }
1.102 www 1634: # ------------------------------------------------------------- current version
1.161 foxr 1635: } elsif ($userinput =~ /^currentversion/) {
1636: if(isClient) {
1637: my ($cmd,$fname)=split(/:/,$userinput);
1638: print $client ¤tversion($fname)."\n";
1639: } else {
1640: Reply($client, "refused\n", $userinput);
1641:
1642: }
1.12 harris41 1643: # ------------------------------------------------------------------------- log
1.161 foxr 1644: } elsif ($userinput =~ /^log/) {
1645: if(isClient) {
1646: my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
1647: chomp($what);
1648: my $proname=propath($udom,$uname);
1649: my $now=time;
1650: {
1651: my $hfh;
1652: if ($hfh=IO::File->new(">>$proname/activity.log")) {
1653: print $hfh "$now:$clientname:$what\n";
1654: print $client "ok\n";
1655: } else {
1656: print $client "error: ".($!+0)
1657: ." IO::File->new Failed "
1658: ."while attempting log\n";
1659: }
1660: }
1661: } else {
1662: Reply($client, "refused\n", $userinput);
1663:
1664: }
1.1 albertel 1665: # ------------------------------------------------------------------------- put
1.161 foxr 1666: } elsif ($userinput =~ /^put/) {
1667: if(isClient) {
1668: my ($cmd,$udom,$uname,$namespace,$what)
1669: =split(/:/,$userinput);
1670: $namespace=~s/\//\_/g;
1671: $namespace=~s/\W//g;
1672: if ($namespace ne 'roles') {
1673: chomp($what);
1674: my $proname=propath($udom,$uname);
1675: my $now=time;
1676: unless ($namespace=~/^nohist\_/) {
1677: my $hfh;
1678: if (
1679: $hfh=IO::File->new(">>$proname/$namespace.hist")
1680: ) { print $hfh "P:$now:$what\n"; }
1681: }
1682: my @pairs=split(/\&/,$what);
1683: my %hash;
1684: if (tie(%hash,'GDBM_File',
1685: "$proname/$namespace.db",
1686: &GDBM_WRCREAT(),0640)) {
1687: foreach my $pair (@pairs) {
1688: my ($key,$value)=split(/=/,$pair);
1689: $hash{$key}=$value;
1.162 ! matthew 1690: }
! 1691: if (untie(%hash)) {
! 1692: print $client "ok\n";
! 1693: } else {
! 1694: print $client "error: ".($!+0)
! 1695: ." untie(GDBM) failed ".
! 1696: "while attempting put\n";
! 1697: }
! 1698: } else {
! 1699: print $client "error: ".($!)
! 1700: ." tie(GDBM) Failed ".
! 1701: "while attempting put\n";
! 1702: }
! 1703: } else {
! 1704: print $client "refused\n";
! 1705: }
! 1706: } else {
! 1707: Reply($client, "refused\n", $userinput);
! 1708:
! 1709: }
! 1710: # ------------------------------------------------------------------- inc
! 1711: } elsif ($userinput =~ /^inc:/) {
! 1712: if(isClient) {
! 1713: my ($cmd,$udom,$uname,$namespace,$what)
! 1714: =split(/:/,$userinput);
! 1715: $namespace=~s/\//\_/g;
! 1716: $namespace=~s/\W//g;
! 1717: if ($namespace ne 'roles') {
! 1718: chomp($what);
! 1719: my $proname=propath($udom,$uname);
! 1720: my $now=time;
! 1721: unless ($namespace=~/^nohist\_/) {
! 1722: my $hfh;
! 1723: if (
! 1724: $hfh=IO::File->new(">>$proname/$namespace.hist")
! 1725: ) { print $hfh "P:$now:$what\n"; }
! 1726: }
! 1727: my @pairs=split(/\&/,$what);
! 1728: my %hash;
! 1729: if (tie(%hash,'GDBM_File',
! 1730: "$proname/$namespace.db",
! 1731: &GDBM_WRCREAT(),0640)) {
! 1732: foreach my $pair (@pairs) {
! 1733: my ($key,$value)=split(/=/,$pair);
! 1734: # We could check that we have a number...
! 1735: if (! defined($value) || $value eq '') {
! 1736: $value = 1;
! 1737: }
! 1738: $hash{$key}+=$value;
1.161 foxr 1739: }
1740: if (untie(%hash)) {
1741: print $client "ok\n";
1742: } else {
1743: print $client "error: ".($!+0)
1744: ." untie(GDBM) failed ".
1745: "while attempting put\n";
1746: }
1747: } else {
1748: print $client "error: ".($!)
1749: ." tie(GDBM) Failed ".
1750: "while attempting put\n";
1751: }
1752: } else {
1753: print $client "refused\n";
1754: }
1755: } else {
1756: Reply($client, "refused\n", $userinput);
1757:
1758: }
1.6 www 1759: # -------------------------------------------------------------------- rolesput
1.161 foxr 1760: } elsif ($userinput =~ /^rolesput/) {
1761: if(isClient) {
1762: &Debug("rolesput");
1763: if ($wasenc==1) {
1764: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
1765: =split(/:/,$userinput);
1766: &Debug("cmd = ".$cmd." exedom= ".$exedom.
1767: "user = ".$exeuser." udom=".$udom.
1768: "what = ".$what);
1769: my $namespace='roles';
1770: chomp($what);
1771: my $proname=propath($udom,$uname);
1772: my $now=time;
1773: {
1774: my $hfh;
1775: if (
1776: $hfh=IO::File->new(">>$proname/$namespace.hist")
1777: ) {
1778: print $hfh "P:$now:$exedom:$exeuser:$what\n";
1779: }
1780: }
1781: my @pairs=split(/\&/,$what);
1782: my %hash;
1783: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1784: foreach my $pair (@pairs) {
1785: my ($key,$value)=split(/=/,$pair);
1786: &ManagePermissions($key, $udom, $uname,
1787: &GetAuthType( $udom,
1788: $uname));
1789: $hash{$key}=$value;
1790: }
1791: if (untie(%hash)) {
1792: print $client "ok\n";
1793: } else {
1794: print $client "error: ".($!+0)
1795: ." untie(GDBM) Failed ".
1796: "while attempting rolesput\n";
1797: }
1798: } else {
1799: print $client "error: ".($!+0)
1800: ." tie(GDBM) Failed ".
1801: "while attempting rolesput\n";
1802: }
1803: } else {
1804: print $client "refused\n";
1805: }
1806: } else {
1807: Reply($client, "refused\n", $userinput);
1808:
1809: }
1.117 www 1810: # -------------------------------------------------------------------- rolesdel
1.161 foxr 1811: } elsif ($userinput =~ /^rolesdel/) {
1812: if(isClient) {
1813: &Debug("rolesdel");
1814: if ($wasenc==1) {
1815: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
1816: =split(/:/,$userinput);
1817: &Debug("cmd = ".$cmd." exedom= ".$exedom.
1818: "user = ".$exeuser." udom=".$udom.
1819: "what = ".$what);
1820: my $namespace='roles';
1821: chomp($what);
1822: my $proname=propath($udom,$uname);
1823: my $now=time;
1824: {
1825: my $hfh;
1826: if (
1827: $hfh=IO::File->new(">>$proname/$namespace.hist")
1828: ) {
1829: print $hfh "D:$now:$exedom:$exeuser:$what\n";
1830: }
1831: }
1832: my @rolekeys=split(/\&/,$what);
1833: my %hash;
1834: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1835: foreach my $key (@rolekeys) {
1836: delete $hash{$key};
1837: }
1838: if (untie(%hash)) {
1839: print $client "ok\n";
1840: } else {
1841: print $client "error: ".($!+0)
1842: ." untie(GDBM) Failed ".
1843: "while attempting rolesdel\n";
1844: }
1845: } else {
1846: print $client "error: ".($!+0)
1847: ." tie(GDBM) Failed ".
1848: "while attempting rolesdel\n";
1849: }
1850: } else {
1851: print $client "refused\n";
1852: }
1853: } else {
1854: Reply($client, "refused\n", $userinput);
1855:
1856: }
1.1 albertel 1857: # ------------------------------------------------------------------------- get
1.161 foxr 1858: } elsif ($userinput =~ /^get/) {
1859: if(isClient) {
1860: my ($cmd,$udom,$uname,$namespace,$what)
1861: =split(/:/,$userinput);
1862: $namespace=~s/\//\_/g;
1863: $namespace=~s/\W//g;
1864: chomp($what);
1865: my @queries=split(/\&/,$what);
1866: my $proname=propath($udom,$uname);
1867: my $qresult='';
1868: my %hash;
1869: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
1870: for (my $i=0;$i<=$#queries;$i++) {
1871: $qresult.="$hash{$queries[$i]}&";
1872: }
1873: if (untie(%hash)) {
1874: $qresult=~s/\&$//;
1875: print $client "$qresult\n";
1876: } else {
1877: print $client "error: ".($!+0)
1878: ." untie(GDBM) Failed ".
1879: "while attempting get\n";
1880: }
1881: } else {
1882: if ($!+0 == 2) {
1883: print $client "error:No such file or ".
1884: "GDBM reported bad block error\n";
1885: } else {
1886: print $client "error: ".($!+0)
1887: ." tie(GDBM) Failed ".
1888: "while attempting get\n";
1889: }
1890: }
1891: } else {
1892: Reply($client, "refused\n", $userinput);
1893:
1894: }
1.1 albertel 1895: # ------------------------------------------------------------------------ eget
1.161 foxr 1896: } elsif ($userinput =~ /^eget/) {
1897: if (isClient) {
1898: my ($cmd,$udom,$uname,$namespace,$what)
1899: =split(/:/,$userinput);
1900: $namespace=~s/\//\_/g;
1901: $namespace=~s/\W//g;
1902: chomp($what);
1903: my @queries=split(/\&/,$what);
1904: my $proname=propath($udom,$uname);
1905: my $qresult='';
1906: my %hash;
1907: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
1908: for (my $i=0;$i<=$#queries;$i++) {
1909: $qresult.="$hash{$queries[$i]}&";
1910: }
1911: if (untie(%hash)) {
1912: $qresult=~s/\&$//;
1913: if ($cipher) {
1914: my $cmdlength=length($qresult);
1915: $qresult.=" ";
1916: my $encqresult='';
1917: for
1918: (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
1919: $encqresult.=
1920: unpack("H16",
1921: $cipher->encrypt(substr($qresult,$encidx,8)));
1922: }
1923: print $client "enc:$cmdlength:$encqresult\n";
1924: } else {
1925: print $client "error:no_key\n";
1926: }
1927: } else {
1928: print $client "error: ".($!+0)
1929: ." untie(GDBM) Failed ".
1930: "while attempting eget\n";
1931: }
1932: } else {
1933: print $client "error: ".($!+0)
1934: ." tie(GDBM) Failed ".
1935: "while attempting eget\n";
1936: }
1937: } else {
1938: Reply($client, "refused\n", $userinput);
1939:
1940: }
1.1 albertel 1941: # ------------------------------------------------------------------------- del
1.161 foxr 1942: } elsif ($userinput =~ /^del/) {
1943: if(isClient) {
1944: my ($cmd,$udom,$uname,$namespace,$what)
1945: =split(/:/,$userinput);
1946: $namespace=~s/\//\_/g;
1947: $namespace=~s/\W//g;
1948: chomp($what);
1949: my $proname=propath($udom,$uname);
1950: my $now=time;
1951: unless ($namespace=~/^nohist\_/) {
1952: my $hfh;
1953: if (
1954: $hfh=IO::File->new(">>$proname/$namespace.hist")
1955: ) { print $hfh "D:$now:$what\n"; }
1956: }
1957: my @keys=split(/\&/,$what);
1958: my %hash;
1959: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1960: foreach my $key (@keys) {
1961: delete($hash{$key});
1962: }
1963: if (untie(%hash)) {
1964: print $client "ok\n";
1965: } else {
1966: print $client "error: ".($!+0)
1967: ." untie(GDBM) Failed ".
1968: "while attempting del\n";
1969: }
1970: } else {
1971: print $client "error: ".($!+0)
1972: ." tie(GDBM) Failed ".
1973: "while attempting del\n";
1974: }
1975: } else {
1976: Reply($client, "refused\n", $userinput);
1977:
1978: }
1.1 albertel 1979: # ------------------------------------------------------------------------ keys
1.161 foxr 1980: } elsif ($userinput =~ /^keys/) {
1981: if(isClient) {
1982: my ($cmd,$udom,$uname,$namespace)
1983: =split(/:/,$userinput);
1984: $namespace=~s/\//\_/g;
1985: $namespace=~s/\W//g;
1986: my $proname=propath($udom,$uname);
1987: my $qresult='';
1988: my %hash;
1989: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
1990: foreach my $key (keys %hash) {
1991: $qresult.="$key&";
1992: }
1993: if (untie(%hash)) {
1994: $qresult=~s/\&$//;
1995: print $client "$qresult\n";
1996: } else {
1997: print $client "error: ".($!+0)
1998: ." untie(GDBM) Failed ".
1999: "while attempting keys\n";
2000: }
2001: } else {
2002: print $client "error: ".($!+0)
2003: ." tie(GDBM) Failed ".
2004: "while attempting keys\n";
2005: }
2006: } else {
2007: Reply($client, "refused\n", $userinput);
2008:
2009: }
1.105 matthew 2010: # ----------------------------------------------------------------- dumpcurrent
1.161 foxr 2011: } elsif ($userinput =~ /^currentdump/) {
2012: if (isClient) {
2013: my ($cmd,$udom,$uname,$namespace)
2014: =split(/:/,$userinput);
2015: $namespace=~s/\//\_/g;
2016: $namespace=~s/\W//g;
2017: my $qresult='';
2018: my $proname=propath($udom,$uname);
2019: my %hash;
2020: if (tie(%hash,'GDBM_File',
2021: "$proname/$namespace.db",
2022: &GDBM_READER(),0640)) {
2023: # Structure of %data:
2024: # $data{$symb}->{$parameter}=$value;
2025: # $data{$symb}->{'v.'.$parameter}=$version;
2026: # since $parameter will be unescaped, we do not
2027: # have to worry about silly parameter names...
2028: my %data = ();
2029: while (my ($key,$value) = each(%hash)) {
2030: my ($v,$symb,$param) = split(/:/,$key);
2031: next if ($v eq 'version' || $symb eq 'keys');
2032: next if (exists($data{$symb}) &&
2033: exists($data{$symb}->{$param}) &&
2034: $data{$symb}->{'v.'.$param} > $v);
2035: $data{$symb}->{$param}=$value;
2036: $data{$symb}->{'v.'.$param}=$v;
2037: }
2038: if (untie(%hash)) {
2039: while (my ($symb,$param_hash) = each(%data)) {
2040: while(my ($param,$value) = each (%$param_hash)){
2041: next if ($param =~ /^v\./);
2042: $qresult.=$symb.':'.$param.'='.$value.'&';
2043: }
2044: }
2045: chop($qresult);
2046: print $client "$qresult\n";
2047: } else {
2048: print $client "error: ".($!+0)
2049: ." untie(GDBM) Failed ".
2050: "while attempting currentdump\n";
2051: }
2052: } else {
2053: print $client "error: ".($!+0)
2054: ." tie(GDBM) Failed ".
2055: "while attempting currentdump\n";
2056: }
2057: } else {
2058: Reply($client, "refused\n", $userinput);
2059: }
1.1 albertel 2060: # ------------------------------------------------------------------------ dump
1.161 foxr 2061: } elsif ($userinput =~ /^dump/) {
2062: if(isClient) {
2063: my ($cmd,$udom,$uname,$namespace,$regexp)
2064: =split(/:/,$userinput);
2065: $namespace=~s/\//\_/g;
2066: $namespace=~s/\W//g;
2067: if (defined($regexp)) {
2068: $regexp=&unescape($regexp);
2069: } else {
2070: $regexp='.';
2071: }
2072: my $qresult='';
2073: my $proname=propath($udom,$uname);
2074: my %hash;
2075: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2076: study($regexp);
2077: while (my ($key,$value) = each(%hash)) {
2078: if ($regexp eq '.') {
2079: $qresult.=$key.'='.$value.'&';
2080: } else {
2081: my $unescapeKey = &unescape($key);
2082: if (eval('$unescapeKey=~/$regexp/')) {
2083: $qresult.="$key=$value&";
2084: }
2085: }
2086: }
2087: if (untie(%hash)) {
2088: chop($qresult);
2089: print $client "$qresult\n";
2090: } else {
2091: print $client "error: ".($!+0)
2092: ." untie(GDBM) Failed ".
1.111 matthew 2093: "while attempting dump\n";
1.161 foxr 2094: }
2095: } else {
2096: print $client "error: ".($!+0)
2097: ." tie(GDBM) Failed ".
2098: "while attempting dump\n";
2099: }
2100: } else {
2101: Reply($client, "refused\n", $userinput);
2102:
2103: }
1.7 www 2104: # ----------------------------------------------------------------------- store
1.161 foxr 2105: } elsif ($userinput =~ /^store/) {
2106: if(isClient) {
2107: my ($cmd,$udom,$uname,$namespace,$rid,$what)
2108: =split(/:/,$userinput);
2109: $namespace=~s/\//\_/g;
2110: $namespace=~s/\W//g;
2111: if ($namespace ne 'roles') {
2112: chomp($what);
2113: my $proname=propath($udom,$uname);
2114: my $now=time;
2115: unless ($namespace=~/^nohist\_/) {
2116: my $hfh;
2117: if (
2118: $hfh=IO::File->new(">>$proname/$namespace.hist")
2119: ) { print $hfh "P:$now:$rid:$what\n"; }
2120: }
2121: my @pairs=split(/\&/,$what);
2122: my %hash;
2123: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2124: my @previouskeys=split(/&/,$hash{"keys:$rid"});
2125: my $key;
2126: $hash{"version:$rid"}++;
2127: my $version=$hash{"version:$rid"};
2128: my $allkeys='';
2129: foreach my $pair (@pairs) {
2130: my ($key,$value)=split(/=/,$pair);
2131: $allkeys.=$key.':';
2132: $hash{"$version:$rid:$key"}=$value;
2133: }
2134: $hash{"$version:$rid:timestamp"}=$now;
2135: $allkeys.='timestamp';
2136: $hash{"$version:keys:$rid"}=$allkeys;
2137: if (untie(%hash)) {
2138: print $client "ok\n";
2139: } else {
2140: print $client "error: ".($!+0)
2141: ." untie(GDBM) Failed ".
2142: "while attempting store\n";
2143: }
2144: } else {
2145: print $client "error: ".($!+0)
2146: ." tie(GDBM) Failed ".
2147: "while attempting store\n";
2148: }
2149: } else {
2150: print $client "refused\n";
2151: }
2152: } else {
2153: Reply($client, "refused\n", $userinput);
2154:
2155: }
1.7 www 2156: # --------------------------------------------------------------------- restore
1.161 foxr 2157: } elsif ($userinput =~ /^restore/) {
2158: if(isClient) {
2159: my ($cmd,$udom,$uname,$namespace,$rid)
2160: =split(/:/,$userinput);
2161: $namespace=~s/\//\_/g;
2162: $namespace=~s/\W//g;
2163: chomp($rid);
2164: my $proname=propath($udom,$uname);
2165: my $qresult='';
2166: my %hash;
2167: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2168: my $version=$hash{"version:$rid"};
2169: $qresult.="version=$version&";
2170: my $scope;
2171: for ($scope=1;$scope<=$version;$scope++) {
2172: my $vkeys=$hash{"$scope:keys:$rid"};
2173: my @keys=split(/:/,$vkeys);
2174: my $key;
2175: $qresult.="$scope:keys=$vkeys&";
2176: foreach $key (@keys) {
2177: $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
2178: }
2179: }
2180: if (untie(%hash)) {
2181: $qresult=~s/\&$//;
2182: print $client "$qresult\n";
2183: } else {
2184: print $client "error: ".($!+0)
2185: ." untie(GDBM) Failed ".
2186: "while attempting restore\n";
2187: }
2188: } else {
2189: print $client "error: ".($!+0)
2190: ." tie(GDBM) Failed ".
2191: "while attempting restore\n";
2192: }
2193: } else {
2194: Reply($client, "refused\n", $userinput);
2195:
2196: }
1.86 www 2197: # -------------------------------------------------------------------- chatsend
1.161 foxr 2198: } elsif ($userinput =~ /^chatsend/) {
2199: if(isClient) {
2200: my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
2201: &chatadd($cdom,$cnum,$newpost);
2202: print $client "ok\n";
2203: } else {
2204: Reply($client, "refused\n", $userinput);
2205:
2206: }
1.86 www 2207: # -------------------------------------------------------------------- chatretr
1.161 foxr 2208: } elsif ($userinput =~ /^chatretr/) {
2209: if(isClient) {
2210: my
2211: ($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
2212: my $reply='';
2213: foreach (&getchat($cdom,$cnum,$udom,$uname)) {
2214: $reply.=&escape($_).':';
2215: }
2216: $reply=~s/\:$//;
2217: print $client $reply."\n";
2218: } else {
2219: Reply($client, "refused\n", $userinput);
2220:
2221: }
1.12 harris41 2222: # ------------------------------------------------------------------- querysend
1.161 foxr 2223: } elsif ($userinput =~ /^querysend/) {
2224: if(isClient) {
2225: my ($cmd,$query,
2226: $arg1,$arg2,$arg3)=split(/\:/,$userinput);
2227: $query=~s/\n*$//g;
2228: print $client "".
2229: sqlreply("$clientname\&$query".
2230: "\&$arg1"."\&$arg2"."\&$arg3")."\n";
2231: } else {
2232: Reply($client, "refused\n", $userinput);
2233:
2234: }
1.12 harris41 2235: # ------------------------------------------------------------------ queryreply
1.161 foxr 2236: } elsif ($userinput =~ /^queryreply/) {
2237: if(isClient) {
2238: my ($cmd,$id,$reply)=split(/:/,$userinput);
2239: my $store;
2240: my $execdir=$perlvar{'lonDaemons'};
2241: if ($store=IO::File->new(">$execdir/tmp/$id")) {
2242: $reply=~s/\&/\n/g;
2243: print $store $reply;
2244: close $store;
2245: my $store2=IO::File->new(">$execdir/tmp/$id.end");
2246: print $store2 "done\n";
2247: close $store2;
2248: print $client "ok\n";
2249: }
2250: else {
2251: print $client "error: ".($!+0)
2252: ." IO::File->new Failed ".
2253: "while attempting queryreply\n";
2254: }
2255: } else {
2256: Reply($client, "refused\n", $userinput);
2257:
2258: }
1.118 www 2259: # ----------------------------------------------------------------- courseidput
1.161 foxr 2260: } elsif ($userinput =~ /^courseidput/) {
2261: if(isClient) {
2262: my ($cmd,$udom,$what)=split(/:/,$userinput);
2263: chomp($what);
2264: $udom=~s/\W//g;
2265: my $proname=
2266: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
2267: my $now=time;
2268: my @pairs=split(/\&/,$what);
2269: my %hash;
2270: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
2271: foreach my $pair (@pairs) {
2272: my ($key,$value)=split(/=/,$pair);
2273: $hash{$key}=$value.':'.$now;
2274: }
2275: if (untie(%hash)) {
2276: print $client "ok\n";
2277: } else {
2278: print $client "error: ".($!+0)
2279: ." untie(GDBM) Failed ".
2280: "while attempting courseidput\n";
2281: }
2282: } else {
2283: print $client "error: ".($!+0)
2284: ." tie(GDBM) Failed ".
2285: "while attempting courseidput\n";
2286: }
2287: } else {
2288: Reply($client, "refused\n", $userinput);
2289:
2290: }
1.118 www 2291: # ---------------------------------------------------------------- courseiddump
1.161 foxr 2292: } elsif ($userinput =~ /^courseiddump/) {
2293: if(isClient) {
2294: my ($cmd,$udom,$since,$description)
2295: =split(/:/,$userinput);
2296: if (defined($description)) {
2297: $description=&unescape($description);
2298: } else {
2299: $description='.';
2300: }
2301: unless (defined($since)) { $since=0; }
2302: my $qresult='';
2303: my $proname=
2304: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
2305: my %hash;
2306: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
2307: while (my ($key,$value) = each(%hash)) {
2308: my ($descr,$lasttime)=split(/\:/,$value);
2309: if ($lasttime<$since) { next; }
2310: if ($description eq '.') {
2311: $qresult.=$key.'='.$descr.'&';
2312: } else {
2313: my $unescapeVal = &unescape($descr);
2314: if (eval('$unescapeVal=~/$description/i')) {
2315: $qresult.="$key=$descr&";
2316: }
2317: }
2318: }
2319: if (untie(%hash)) {
2320: chop($qresult);
2321: print $client "$qresult\n";
2322: } else {
2323: print $client "error: ".($!+0)
2324: ." untie(GDBM) Failed ".
2325: "while attempting courseiddump\n";
2326: }
2327: } else {
2328: print $client "error: ".($!+0)
2329: ." tie(GDBM) Failed ".
2330: "while attempting courseiddump\n";
2331: }
2332: } else {
2333: Reply($client, "refused\n", $userinput);
2334:
2335: }
1.1 albertel 2336: # ----------------------------------------------------------------------- idput
1.161 foxr 2337: } elsif ($userinput =~ /^idput/) {
2338: if(isClient) {
2339: my ($cmd,$udom,$what)=split(/:/,$userinput);
2340: chomp($what);
2341: $udom=~s/\W//g;
2342: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
2343: my $now=time;
2344: {
2345: my $hfh;
2346: if (
2347: $hfh=IO::File->new(">>$proname.hist")
2348: ) { print $hfh "P:$now:$what\n"; }
2349: }
2350: my @pairs=split(/\&/,$what);
2351: my %hash;
2352: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
2353: foreach my $pair (@pairs) {
2354: my ($key,$value)=split(/=/,$pair);
2355: $hash{$key}=$value;
2356: }
2357: if (untie(%hash)) {
2358: print $client "ok\n";
2359: } else {
2360: print $client "error: ".($!+0)
2361: ." untie(GDBM) Failed ".
2362: "while attempting idput\n";
2363: }
2364: } else {
2365: print $client "error: ".($!+0)
2366: ." tie(GDBM) Failed ".
2367: "while attempting idput\n";
2368: }
2369: } else {
2370: Reply($client, "refused\n", $userinput);
2371:
2372: }
1.1 albertel 2373: # ----------------------------------------------------------------------- idget
1.161 foxr 2374: } elsif ($userinput =~ /^idget/) {
2375: if(isClient) {
2376: my ($cmd,$udom,$what)=split(/:/,$userinput);
2377: chomp($what);
2378: $udom=~s/\W//g;
2379: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
2380: my @queries=split(/\&/,$what);
2381: my $qresult='';
2382: my %hash;
2383: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
2384: for (my $i=0;$i<=$#queries;$i++) {
2385: $qresult.="$hash{$queries[$i]}&";
2386: }
2387: if (untie(%hash)) {
2388: $qresult=~s/\&$//;
2389: print $client "$qresult\n";
2390: } else {
2391: print $client "error: ".($!+0)
2392: ." untie(GDBM) Failed ".
2393: "while attempting idget\n";
2394: }
2395: } else {
2396: print $client "error: ".($!+0)
2397: ." tie(GDBM) Failed ".
2398: "while attempting idget\n";
2399: }
2400: } else {
2401: Reply($client, "refused\n", $userinput);
2402:
2403: }
1.13 www 2404: # ---------------------------------------------------------------------- tmpput
1.161 foxr 2405: } elsif ($userinput =~ /^tmpput/) {
2406: if(isClient) {
2407: my ($cmd,$what)=split(/:/,$userinput);
2408: my $store;
2409: $tmpsnum++;
2410: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
2411: $id=~s/\W/\_/g;
2412: $what=~s/\n//g;
2413: my $execdir=$perlvar{'lonDaemons'};
2414: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
2415: print $store $what;
2416: close $store;
2417: print $client "$id\n";
2418: }
2419: else {
2420: print $client "error: ".($!+0)
2421: ."IO::File->new Failed ".
2422: "while attempting tmpput\n";
2423: }
2424: } else {
2425: Reply($client, "refused\n", $userinput);
2426:
2427: }
2428:
1.13 www 2429: # ---------------------------------------------------------------------- tmpget
1.161 foxr 2430: } elsif ($userinput =~ /^tmpget/) {
2431: if(isClient) {
2432: my ($cmd,$id)=split(/:/,$userinput);
2433: chomp($id);
2434: $id=~s/\W/\_/g;
2435: my $store;
2436: my $execdir=$perlvar{'lonDaemons'};
2437: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
2438: my $reply=<$store>;
2439: print $client "$reply\n";
2440: close $store;
2441: }
2442: else {
2443: print $client "error: ".($!+0)
2444: ."IO::File->new Failed ".
2445: "while attempting tmpget\n";
2446: }
2447: } else {
2448: Reply($client, "refused\n", $userinput);
2449:
2450: }
1.110 www 2451: # ---------------------------------------------------------------------- tmpdel
1.161 foxr 2452: } elsif ($userinput =~ /^tmpdel/) {
2453: if(isClient) {
2454: my ($cmd,$id)=split(/:/,$userinput);
2455: chomp($id);
2456: $id=~s/\W/\_/g;
2457: my $execdir=$perlvar{'lonDaemons'};
2458: if (unlink("$execdir/tmp/$id.tmp")) {
2459: print $client "ok\n";
2460: } else {
2461: print $client "error: ".($!+0)
2462: ."Unlink tmp Failed ".
2463: "while attempting tmpdel\n";
2464: }
2465: } else {
2466: Reply($client, "refused\n", $userinput);
2467:
2468: }
1.5 www 2469: # -------------------------------------------------------------------------- ls
1.161 foxr 2470: } elsif ($userinput =~ /^ls/) {
2471: if(isClient) {
2472: my ($cmd,$ulsdir)=split(/:/,$userinput);
2473: my $ulsout='';
2474: my $ulsfn;
2475: if (-e $ulsdir) {
2476: if(-d $ulsdir) {
2477: if (opendir(LSDIR,$ulsdir)) {
2478: while ($ulsfn=readdir(LSDIR)) {
2479: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
2480: $ulsout.=$ulsfn.'&'.
2481: join('&',@ulsstats).':';
2482: }
2483: closedir(LSDIR);
2484: }
2485: } else {
2486: my @ulsstats=stat($ulsdir);
2487: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
2488: }
2489: } else {
2490: $ulsout='no_such_dir';
2491: }
2492: if ($ulsout eq '') { $ulsout='empty'; }
2493: print $client "$ulsout\n";
2494: } else {
2495: Reply($client, "refused\n", $userinput);
2496:
2497: }
1.136 www 2498: # ----------------------------------------------------------------- setannounce
1.161 foxr 2499: } elsif ($userinput =~ /^setannounce/) {
2500: if (isClient) {
2501: my ($cmd,$announcement)=split(/:/,$userinput);
2502: chomp($announcement);
2503: $announcement=&unescape($announcement);
2504: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
2505: '/announcement.txt')) {
2506: print $store $announcement;
2507: close $store;
2508: print $client "ok\n";
2509: } else {
2510: print $client "error: ".($!+0)."\n";
2511: }
2512: } else {
2513: Reply($client, "refused\n", $userinput);
2514:
2515: }
1.51 www 2516: # ------------------------------------------------------------------ Hanging up
1.161 foxr 2517: } elsif (($userinput =~ /^exit/) ||
2518: ($userinput =~ /^init/)) { # no restrictions.
2519: &logthis(
2520: "Client $clientip ($clientname) hanging up: $userinput");
2521: print $client "bye\n";
2522: $client->close();
2523: last;
2524:
2525: # ---------------------------------- set current host/domain
2526: } elsif ($userinput =~ /^sethost:/) {
2527: if (isClient) {
2528: print $client &sethost($userinput)."\n";
2529: } else {
2530: print $client "refused\n";
2531: }
2532: #---------------------------------- request file (?) version.
2533: } elsif ($userinput =~/^version:/) {
2534: if (isClient) {
2535: print $client &version($userinput)."\n";
2536: } else {
2537: print $client "refused\n";
2538: }
1.1 albertel 2539: # ------------------------------------------------------------- unknown command
1.161 foxr 2540:
2541: } else {
2542: # unknown command
2543: print $client "unknown_cmd\n";
2544: }
1.58 www 2545: # -------------------------------------------------------------------- complete
1.161 foxr 2546: alarm(0);
2547: &status('Listening to '.$clientname);
2548: }
1.59 www 2549: # --------------------------------------------- client unknown or fishy, refuse
1.161 foxr 2550: } else {
2551: print $client "refused\n";
2552: $client->close();
2553: &logthis("<font color=blue>WARNING: "
2554: ."Rejected client $clientip, closing connection</font>");
2555: }
2556: }
2557:
1.1 albertel 2558: # =============================================================================
1.161 foxr 2559:
2560: &logthis("<font color=red>CRITICAL: "
2561: ."Disconnect from $clientip ($clientname)</font>");
2562:
2563:
2564: # this exit is VERY important, otherwise the child will become
2565: # a producer of more and more children, forking yourself into
2566: # process death.
2567: exit;
1.106 foxr 2568:
1.78 foxr 2569: }
2570:
2571:
2572: #
2573: # Checks to see if the input roleput request was to set
2574: # an author role. If so, invokes the lchtmldir script to set
2575: # up a correct public_html
2576: # Parameters:
2577: # request - The request sent to the rolesput subchunk.
2578: # We're looking for /domain/_au
2579: # domain - The domain in which the user is having roles doctored.
2580: # user - Name of the user for which the role is being put.
2581: # authtype - The authentication type associated with the user.
2582: #
2583: sub ManagePermissions
2584: {
2585: my $request = shift;
2586: my $domain = shift;
2587: my $user = shift;
2588: my $authtype= shift;
2589:
2590: # See if the request is of the form /$domain/_au
1.134 albertel 2591: &logthis("ruequest is $request");
1.78 foxr 2592: if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
2593: my $execdir = $perlvar{'lonDaemons'};
2594: my $userhome= "/home/$user" ;
1.134 albertel 2595: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.78 foxr 2596: system("$execdir/lchtmldir $userhome $user $authtype");
2597: }
2598: }
2599: #
2600: # GetAuthType - Determines the authorization type of a user in a domain.
2601:
2602: # Returns the authorization type or nouser if there is no such user.
2603: #
2604: sub GetAuthType
2605: {
2606: my $domain = shift;
2607: my $user = shift;
2608:
1.79 foxr 2609: Debug("GetAuthType( $domain, $user ) \n");
1.78 foxr 2610: my $proname = &propath($domain, $user);
2611: my $passwdfile = "$proname/passwd";
2612: if( -e $passwdfile ) {
2613: my $pf = IO::File->new($passwdfile);
2614: my $realpassword = <$pf>;
2615: chomp($realpassword);
1.79 foxr 2616: Debug("Password info = $realpassword\n");
1.78 foxr 2617: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 2618: Debug("Authtype = $authtype, content = $contentpwd\n");
1.78 foxr 2619: my $availinfo = '';
1.91 albertel 2620: if($authtype eq 'krb4' or $authtype eq 'krb5') {
1.78 foxr 2621: $availinfo = $contentpwd;
2622: }
1.79 foxr 2623:
1.78 foxr 2624: return "$authtype:$availinfo";
2625: }
2626: else {
1.79 foxr 2627: Debug("Returning nouser");
1.78 foxr 2628: return "nouser";
2629: }
1.1 albertel 2630: }
2631:
1.84 albertel 2632: sub addline {
2633: my ($fname,$hostid,$ip,$newline)=@_;
2634: my $contents;
2635: my $found=0;
2636: my $expr='^'.$hostid.':'.$ip.':';
2637: $expr =~ s/\./\\\./g;
1.134 albertel 2638: my $sh;
1.84 albertel 2639: if ($sh=IO::File->new("$fname.subscription")) {
2640: while (my $subline=<$sh>) {
2641: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
2642: }
2643: $sh->close();
2644: }
2645: $sh=IO::File->new(">$fname.subscription");
2646: if ($contents) { print $sh $contents; }
2647: if ($newline) { print $sh $newline; }
2648: $sh->close();
2649: return $found;
1.86 www 2650: }
2651:
2652: sub getchat {
1.122 www 2653: my ($cdom,$cname,$udom,$uname)=@_;
1.87 www 2654: my %hash;
2655: my $proname=&propath($cdom,$cname);
2656: my @entries=();
1.88 albertel 2657: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
2658: &GDBM_READER(),0640)) {
2659: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
2660: untie %hash;
1.123 www 2661: }
1.124 www 2662: my @participants=();
1.134 albertel 2663: my $cutoff=time-60;
1.123 www 2664: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124 www 2665: &GDBM_WRCREAT(),0640)) {
2666: $hash{$uname.':'.$udom}=time;
1.123 www 2667: foreach (sort keys %hash) {
2668: if ($hash{$_}>$cutoff) {
1.124 www 2669: $participants[$#participants+1]='active_participant:'.$_;
1.123 www 2670: }
2671: }
2672: untie %hash;
1.86 www 2673: }
1.124 www 2674: return (@participants,@entries);
1.86 www 2675: }
2676:
2677: sub chatadd {
1.88 albertel 2678: my ($cdom,$cname,$newchat)=@_;
2679: my %hash;
2680: my $proname=&propath($cdom,$cname);
2681: my @entries=();
1.142 www 2682: my $time=time;
1.88 albertel 2683: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
2684: &GDBM_WRCREAT(),0640)) {
2685: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
2686: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
2687: my ($thentime,$idnum)=split(/\_/,$lastid);
2688: my $newid=$time.'_000000';
2689: if ($thentime==$time) {
2690: $idnum=~s/^0+//;
2691: $idnum++;
2692: $idnum=substr('000000'.$idnum,-6,6);
2693: $newid=$time.'_'.$idnum;
2694: }
2695: $hash{$newid}=$newchat;
2696: my $expired=$time-3600;
2697: foreach (keys %hash) {
2698: my ($thistime)=($_=~/(\d+)\_/);
2699: if ($thistime<$expired) {
1.89 www 2700: delete $hash{$_};
1.88 albertel 2701: }
2702: }
2703: untie %hash;
1.142 www 2704: }
2705: {
2706: my $hfh;
2707: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
2708: print $hfh "$time:".&unescape($newchat)."\n";
2709: }
1.86 www 2710: }
1.84 albertel 2711: }
2712:
2713: sub unsub {
2714: my ($fname,$clientip)=@_;
2715: my $result;
1.161 foxr 2716: if (unlink("$fname.$clientname")) {
1.84 albertel 2717: $result="ok\n";
2718: } else {
2719: $result="not_subscribed\n";
2720: }
2721: if (-e "$fname.subscription") {
1.161 foxr 2722: my $found=&addline($fname,$clientname,$clientip,'');
1.84 albertel 2723: if ($found) { $result="ok\n"; }
2724: } else {
2725: if ($result != "ok\n") { $result="not_subscribed\n"; }
2726: }
2727: return $result;
2728: }
2729:
1.101 www 2730: sub currentversion {
2731: my $fname=shift;
2732: my $version=-1;
2733: my $ulsdir='';
2734: if ($fname=~/^(.+)\/[^\/]+$/) {
2735: $ulsdir=$1;
2736: }
1.114 albertel 2737: my ($fnamere1,$fnamere2);
2738: # remove version if already specified
1.101 www 2739: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 2740: # get the bits that go before and after the version number
2741: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
2742: $fnamere1=$1;
2743: $fnamere2='.'.$2;
2744: }
1.101 www 2745: if (-e $fname) { $version=1; }
2746: if (-e $ulsdir) {
1.134 albertel 2747: if(-d $ulsdir) {
2748: if (opendir(LSDIR,$ulsdir)) {
2749: my $ulsfn;
2750: while ($ulsfn=readdir(LSDIR)) {
1.101 www 2751: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 2752: my $thisfile=$ulsdir.'/'.$ulsfn;
2753: unless (-l $thisfile) {
1.160 www 2754: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 2755: if ($1>$version) { $version=$1; }
2756: }
2757: }
2758: }
2759: closedir(LSDIR);
2760: $version++;
2761: }
2762: }
2763: }
2764: return $version;
1.101 www 2765: }
2766:
2767: sub thisversion {
2768: my $fname=shift;
2769: my $version=-1;
2770: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
2771: $version=$1;
2772: }
2773: return $version;
2774: }
2775:
1.84 albertel 2776: sub subscribe {
2777: my ($userinput,$clientip)=@_;
2778: my $result;
2779: my ($cmd,$fname)=split(/:/,$userinput);
2780: my $ownership=&ishome($fname);
2781: if ($ownership eq 'owner') {
1.101 www 2782: # explitly asking for the current version?
2783: unless (-e $fname) {
2784: my $currentversion=¤tversion($fname);
2785: if (&thisversion($fname)==$currentversion) {
2786: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
2787: my $root=$1;
2788: my $extension=$2;
2789: symlink($root.'.'.$extension,
2790: $root.'.'.$currentversion.'.'.$extension);
1.102 www 2791: unless ($extension=~/\.meta$/) {
2792: symlink($root.'.'.$extension.'.meta',
2793: $root.'.'.$currentversion.'.'.$extension.'.meta');
2794: }
1.101 www 2795: }
2796: }
2797: }
1.84 albertel 2798: if (-e $fname) {
2799: if (-d $fname) {
2800: $result="directory\n";
2801: } else {
1.161 foxr 2802: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 2803: my $now=time;
1.161 foxr 2804: my $found=&addline($fname,$clientname,$clientip,
2805: "$clientname:$clientip:$now\n");
1.84 albertel 2806: if ($found) { $result="$fname\n"; }
2807: # if they were subscribed to only meta data, delete that
2808: # subscription, when you subscribe to a file you also get
2809: # the metadata
2810: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
2811: $fname=~s/\/home\/httpd\/html\/res/raw/;
2812: $fname="http://$thisserver/".$fname;
2813: $result="$fname\n";
2814: }
2815: } else {
2816: $result="not_found\n";
2817: }
2818: } else {
2819: $result="rejected\n";
2820: }
2821: return $result;
2822: }
1.91 albertel 2823:
2824: sub make_passwd_file {
1.98 foxr 2825: my ($uname, $umode,$npass,$passfilename)=@_;
1.91 albertel 2826: my $result="ok\n";
2827: if ($umode eq 'krb4' or $umode eq 'krb5') {
2828: {
2829: my $pf = IO::File->new(">$passfilename");
2830: print $pf "$umode:$npass\n";
2831: }
2832: } elsif ($umode eq 'internal') {
2833: my $salt=time;
2834: $salt=substr($salt,6,2);
2835: my $ncpass=crypt($npass,$salt);
2836: {
2837: &Debug("Creating internal auth");
2838: my $pf = IO::File->new(">$passfilename");
2839: print $pf "internal:$ncpass\n";
2840: }
2841: } elsif ($umode eq 'localauth') {
2842: {
2843: my $pf = IO::File->new(">$passfilename");
2844: print $pf "localauth:$npass\n";
2845: }
2846: } elsif ($umode eq 'unix') {
2847: {
2848: my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
2849: {
2850: &Debug("Executing external: ".$execpath);
1.98 foxr 2851: &Debug("user = ".$uname.", Password =". $npass);
1.132 matthew 2852: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91 albertel 2853: print $se "$uname\n";
2854: print $se "$npass\n";
2855: print $se "$npass\n";
1.97 foxr 2856: }
2857: my $useraddok = $?;
2858: if($useraddok > 0) {
2859: &logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
1.91 albertel 2860: }
2861: my $pf = IO::File->new(">$passfilename");
2862: print $pf "unix:\n";
2863: }
2864: } elsif ($umode eq 'none') {
2865: {
2866: my $pf = IO::File->new(">$passfilename");
2867: print $pf "none:\n";
2868: }
2869: } else {
2870: $result="auth_mode_error\n";
2871: }
2872: return $result;
1.121 albertel 2873: }
2874:
2875: sub sethost {
2876: my ($remotereq) = @_;
2877: my (undef,$hostid)=split(/:/,$remotereq);
2878: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
2879: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
2880: $currenthostid=$hostid;
2881: $currentdomainid=$hostdom{$hostid};
2882: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
2883: } else {
2884: &logthis("Requested host id $hostid not an alias of ".
2885: $perlvar{'lonHostID'}." refusing connection");
2886: return 'unable_to_set';
2887: }
2888: return 'ok';
2889: }
2890:
2891: sub version {
2892: my ($userinput)=@_;
2893: $remoteVERSION=(split(/:/,$userinput))[1];
2894: return "version:$VERSION";
1.127 albertel 2895: }
2896:
1.128 albertel 2897: #There is a copy of this in lonnet.pm
1.127 albertel 2898: sub userload {
2899: my $numusers=0;
2900: {
2901: opendir(LONIDS,$perlvar{'lonIDsDir'});
2902: my $filename;
2903: my $curtime=time;
2904: while ($filename=readdir(LONIDS)) {
2905: if ($filename eq '.' || $filename eq '..') {next;}
1.138 albertel 2906: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159 albertel 2907: if ($curtime-$mtime < 1800) { $numusers++; }
1.127 albertel 2908: }
2909: closedir(LONIDS);
2910: }
2911: my $userloadpercent=0;
2912: my $maxuserload=$perlvar{'lonUserLoadLim'};
2913: if ($maxuserload) {
1.129 albertel 2914: $userloadpercent=100*$numusers/$maxuserload;
1.127 albertel 2915: }
1.130 albertel 2916: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127 albertel 2917: return $userloadpercent;
1.91 albertel 2918: }
2919:
1.61 harris41 2920: # ----------------------------------- POD (plain old documentation, CPAN style)
2921:
2922: =head1 NAME
2923:
2924: lond - "LON Daemon" Server (port "LOND" 5663)
2925:
2926: =head1 SYNOPSIS
2927:
1.74 harris41 2928: Usage: B<lond>
2929:
2930: Should only be run as user=www. This is a command-line script which
2931: is invoked by B<loncron>. There is no expectation that a typical user
2932: will manually start B<lond> from the command-line. (In other words,
2933: DO NOT START B<lond> YOURSELF.)
1.61 harris41 2934:
2935: =head1 DESCRIPTION
2936:
1.74 harris41 2937: There are two characteristics associated with the running of B<lond>,
2938: PROCESS MANAGEMENT (starting, stopping, handling child processes)
2939: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
2940: subscriptions, etc). These are described in two large
2941: sections below.
2942:
2943: B<PROCESS MANAGEMENT>
2944:
1.61 harris41 2945: Preforker - server who forks first. Runs as a daemon. HUPs.
2946: Uses IDEA encryption
2947:
1.74 harris41 2948: B<lond> forks off children processes that correspond to the other servers
2949: in the network. Management of these processes can be done at the
2950: parent process level or the child process level.
2951:
2952: B<logs/lond.log> is the location of log messages.
2953:
2954: The process management is now explained in terms of linux shell commands,
2955: subroutines internal to this code, and signal assignments:
2956:
2957: =over 4
2958:
2959: =item *
2960:
2961: PID is stored in B<logs/lond.pid>
2962:
2963: This is the process id number of the parent B<lond> process.
2964:
2965: =item *
2966:
2967: SIGTERM and SIGINT
2968:
2969: Parent signal assignment:
2970: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
2971:
2972: Child signal assignment:
2973: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
2974: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
2975: to restart a new child.)
2976:
2977: Command-line invocations:
2978: B<kill> B<-s> SIGTERM I<PID>
2979: B<kill> B<-s> SIGINT I<PID>
2980:
2981: Subroutine B<HUNTSMAN>:
2982: This is only invoked for the B<lond> parent I<PID>.
2983: This kills all the children, and then the parent.
2984: The B<lonc.pid> file is cleared.
2985:
2986: =item *
2987:
2988: SIGHUP
2989:
2990: Current bug:
2991: This signal can only be processed the first time
2992: on the parent process. Subsequent SIGHUP signals
2993: have no effect.
2994:
2995: Parent signal assignment:
2996: $SIG{HUP} = \&HUPSMAN;
2997:
2998: Child signal assignment:
2999: none (nothing happens)
3000:
3001: Command-line invocations:
3002: B<kill> B<-s> SIGHUP I<PID>
3003:
3004: Subroutine B<HUPSMAN>:
3005: This is only invoked for the B<lond> parent I<PID>,
3006: This kills all the children, and then the parent.
3007: The B<lond.pid> file is cleared.
3008:
3009: =item *
3010:
3011: SIGUSR1
3012:
3013: Parent signal assignment:
3014: $SIG{USR1} = \&USRMAN;
3015:
3016: Child signal assignment:
3017: $SIG{USR1}= \&logstatus;
3018:
3019: Command-line invocations:
3020: B<kill> B<-s> SIGUSR1 I<PID>
3021:
3022: Subroutine B<USRMAN>:
3023: When invoked for the B<lond> parent I<PID>,
3024: SIGUSR1 is sent to all the children, and the status of
3025: each connection is logged.
1.144 foxr 3026:
3027: =item *
3028:
3029: SIGUSR2
3030:
3031: Parent Signal assignment:
3032: $SIG{USR2} = \&UpdateHosts
3033:
3034: Child signal assignment:
3035: NONE
3036:
1.74 harris41 3037:
3038: =item *
3039:
3040: SIGCHLD
3041:
3042: Parent signal assignment:
3043: $SIG{CHLD} = \&REAPER;
3044:
3045: Child signal assignment:
3046: none
3047:
3048: Command-line invocations:
3049: B<kill> B<-s> SIGCHLD I<PID>
3050:
3051: Subroutine B<REAPER>:
3052: This is only invoked for the B<lond> parent I<PID>.
3053: Information pertaining to the child is removed.
3054: The socket port is cleaned up.
3055:
3056: =back
3057:
3058: B<SERVER-SIDE ACTIVITIES>
3059:
3060: Server-side information can be accepted in an encrypted or non-encrypted
3061: method.
3062:
3063: =over 4
3064:
3065: =item ping
3066:
3067: Query a client in the hosts.tab table; "Are you there?"
3068:
3069: =item pong
3070:
3071: Respond to a ping query.
3072:
3073: =item ekey
3074:
3075: Read in encrypted key, make cipher. Respond with a buildkey.
3076:
3077: =item load
3078:
3079: Respond with CPU load based on a computation upon /proc/loadavg.
3080:
3081: =item currentauth
3082:
3083: Reply with current authentication information (only over an
3084: encrypted channel).
3085:
3086: =item auth
3087:
3088: Only over an encrypted channel, reply as to whether a user's
3089: authentication information can be validated.
3090:
3091: =item passwd
3092:
3093: Allow for a password to be set.
3094:
3095: =item makeuser
3096:
3097: Make a user.
3098:
3099: =item passwd
3100:
3101: Allow for authentication mechanism and password to be changed.
3102:
3103: =item home
1.61 harris41 3104:
1.74 harris41 3105: Respond to a question "are you the home for a given user?"
3106:
3107: =item update
3108:
3109: Update contents of a subscribed resource.
3110:
3111: =item unsubscribe
3112:
3113: The server is unsubscribing from a resource.
3114:
3115: =item subscribe
3116:
3117: The server is subscribing to a resource.
3118:
3119: =item log
3120:
3121: Place in B<logs/lond.log>
3122:
3123: =item put
3124:
3125: stores hash in namespace
3126:
3127: =item rolesput
3128:
3129: put a role into a user's environment
3130:
3131: =item get
3132:
3133: returns hash with keys from array
3134: reference filled in from namespace
3135:
3136: =item eget
3137:
3138: returns hash with keys from array
3139: reference filled in from namesp (encrypts the return communication)
3140:
3141: =item rolesget
3142:
3143: get a role from a user's environment
3144:
3145: =item del
3146:
3147: deletes keys out of array from namespace
3148:
3149: =item keys
3150:
3151: returns namespace keys
3152:
3153: =item dump
3154:
3155: dumps the complete (or key matching regexp) namespace into a hash
3156:
3157: =item store
3158:
3159: stores hash permanently
3160: for this url; hashref needs to be given and should be a \%hashname; the
3161: remaining args aren't required and if they aren't passed or are '' they will
3162: be derived from the ENV
3163:
3164: =item restore
3165:
3166: returns a hash for a given url
3167:
3168: =item querysend
3169:
3170: Tells client about the lonsql process that has been launched in response
3171: to a sent query.
3172:
3173: =item queryreply
3174:
3175: Accept information from lonsql and make appropriate storage in temporary
3176: file space.
3177:
3178: =item idput
3179:
3180: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
3181: for each student, defined perhaps by the institutional Registrar.)
3182:
3183: =item idget
3184:
3185: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
3186: for each student, defined perhaps by the institutional Registrar.)
3187:
3188: =item tmpput
3189:
3190: Accept and store information in temporary space.
3191:
3192: =item tmpget
3193:
3194: Send along temporarily stored information.
3195:
3196: =item ls
3197:
3198: List part of a user's directory.
3199:
1.135 foxr 3200: =item pushtable
3201:
3202: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
3203: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
3204: must be restored manually in case of a problem with the new table file.
3205: pushtable requires that the request be encrypted and validated via
3206: ValidateManager. The form of the command is:
3207: enc:pushtable tablename <tablecontents> \n
3208: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
3209: cleartext newline.
3210:
1.74 harris41 3211: =item Hanging up (exit or init)
3212:
3213: What to do when a client tells the server that they (the client)
3214: are leaving the network.
3215:
3216: =item unknown command
3217:
3218: If B<lond> is sent an unknown command (not in the list above),
3219: it replys to the client "unknown_cmd".
1.135 foxr 3220:
1.74 harris41 3221:
3222: =item UNKNOWN CLIENT
3223:
3224: If the anti-spoofing algorithm cannot verify the client,
3225: the client is rejected (with a "refused" message sent
3226: to the client, and the connection is closed.
3227:
3228: =back
1.61 harris41 3229:
3230: =head1 PREREQUISITES
3231:
3232: IO::Socket
3233: IO::File
3234: Apache::File
3235: Symbol
3236: POSIX
3237: Crypt::IDEA
3238: LWP::UserAgent()
3239: GDBM_File
3240: Authen::Krb4
1.91 albertel 3241: Authen::Krb5
1.61 harris41 3242:
3243: =head1 COREQUISITES
3244:
3245: =head1 OSNAMES
3246:
3247: linux
3248:
3249: =head1 SCRIPT CATEGORIES
3250:
3251: Server/Process
3252:
3253: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>