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