File:
[LON-CAPA] /
loncom /
lond
Revision
1.213:
download - view:
text,
annotated -
select for diffs
Tue Jul 27 10:50:37 2004 UTC (20 years, 1 month ago) by
foxr
Branches:
MAIN
CVS tags:
HEAD
Added dispatch logic and comments about how to use it. For now if
no match, dispatch logic falls though to the big bad ugly if/elsif chain.
1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
4: #
5: # $Id: lond,v 1.213 2004/07/27 10:50:37 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 localenroll;
49: use File::Copy;
50: use LONCAPA::ConfigFileEdit;
51: use LONCAPA::lonlocal;
52: use LONCAPA::lonssl;
53:
54: my $DEBUG = 0; # Non zero to enable debug log entries.
55:
56: my $status='';
57: my $lastlog='';
58:
59: my $VERSION='$Revision: 1.213 $'; #' stupid emacs
60: my $remoteVERSION;
61: my $currenthostid;
62: my $currentdomainid;
63:
64: my $client;
65: my $clientip; # IP address of client.
66: my $clientdns; # DNS name of client.
67: my $clientname; # LonCAPA name of client.
68:
69: my $server;
70: my $thisserver; # DNS of us.
71:
72: my $keymode;
73:
74: my $cipher; # Cipher key negotiated with client
75: my $tmpsnum = 0; # Id of tmpputs.
76:
77: #
78: # Connection type is:
79: # client - All client actions are allowed
80: # manager - only management functions allowed.
81: # both - Both management and client actions are allowed
82: #
83:
84: my $ConnectionType;
85:
86: my %hostid; # ID's for hosts in cluster by ip.
87: my %hostdom; # LonCAPA domain for hosts in cluster.
88: my %hostip; # IPs for hosts in cluster.
89: my %hostdns; # ID's of hosts looked up by DNS name.
90:
91: my %managers; # Ip -> manager names
92:
93: my %perlvar; # Will have the apache conf defined perl vars.
94:
95: #
96: # The hash below is used for command dispatching, and is therefore keyed on the request keyword.
97: # Each element of the hash contains a reference to an array that contains:
98: # A reference to a sub that executes the request corresponding to the keyword.
99: # A flag that is true if the request must be encoded to be acceptable.
100: # A mask with bits as follows:
101: # CLIENT_OK - Set when the function is allowed by ordinary clients
102: # MANAGER_OK - Set when the function is allowed to manager clients.
103: #
104: my $CLIENT_OK = 1;
105: my $MANAGER_OK = 2;
106: my %Dispatcher;
107:
108:
109: #
110: # The array below are password error strings."
111: #
112: my $lastpwderror = 13; # Largest error number from lcpasswd.
113: my @passwderrors = ("ok",
114: "lcpasswd must be run as user 'www'",
115: "lcpasswd got incorrect number of arguments",
116: "lcpasswd did not get the right nubmer of input text lines",
117: "lcpasswd too many simultaneous pwd changes in progress",
118: "lcpasswd User does not exist.",
119: "lcpasswd Incorrect current passwd",
120: "lcpasswd Unable to su to root.",
121: "lcpasswd Cannot set new passwd.",
122: "lcpasswd Username has invalid characters",
123: "lcpasswd Invalid characters in password",
124: "11", "12",
125: "lcpasswd Password mismatch");
126:
127:
128: # The array below are lcuseradd error strings.:
129:
130: my $lastadderror = 13;
131: my @adderrors = ("ok",
132: "User ID mismatch, lcuseradd must run as user www",
133: "lcuseradd Incorrect number of command line parameters must be 3",
134: "lcuseradd Incorrect number of stdinput lines, must be 3",
135: "lcuseradd Too many other simultaneous pwd changes in progress",
136: "lcuseradd User does not exist",
137: "lcuseradd Unable to make www member of users's group",
138: "lcuseradd Unable to su to root",
139: "lcuseradd Unable to set password",
140: "lcuseradd Usrname has invalid characters",
141: "lcuseradd Password has an invalid character",
142: "lcuseradd User already exists",
143: "lcuseradd Could not add user.",
144: "lcuseradd Password mismatch");
145:
146:
147:
148: #
149: # Statistics that are maintained and dislayed in the status line.
150: #
151: my $Transactions = 0; # Number of attempted transactions.
152: my $Failures = 0; # Number of transcations failed.
153:
154: # ResetStatistics:
155: # Resets the statistics counters:
156: #
157: sub ResetStatistics {
158: $Transactions = 0;
159: $Failures = 0;
160: }
161:
162:
163:
164: #------------------------------------------------------------------------
165: #
166: # LocalConnection
167: # Completes the formation of a locally authenticated connection.
168: # This function will ensure that the 'remote' client is really the
169: # local host. If not, the connection is closed, and the function fails.
170: # If so, initcmd is parsed for the name of a file containing the
171: # IDEA session key. The fie is opened, read, deleted and the session
172: # key returned to the caller.
173: #
174: # Parameters:
175: # $Socket - Socket open on client.
176: # $initcmd - The full text of the init command.
177: #
178: # Implicit inputs:
179: # $clientdns - The DNS name of the remote client.
180: # $thisserver - Our DNS name.
181: #
182: # Returns:
183: # IDEA session key on success.
184: # undef on failure.
185: #
186: sub LocalConnection {
187: my ($Socket, $initcmd) = @_;
188: Debug("Attempting local connection: $initcmd client: $clientdns me: $thisserver");
189: if($clientdns ne $thisserver) {
190: &logthis('<font color="red"> LocalConnection rejecting non local: '
191: ."$clientdns ne $thisserver </font>");
192: close $Socket;
193: return undef;
194: }
195: else {
196: chomp($initcmd); # Get rid of \n in filename.
197: my ($init, $type, $name) = split(/:/, $initcmd);
198: Debug(" Init command: $init $type $name ");
199:
200: # Require that $init = init, and $type = local: Otherwise
201: # the caller is insane:
202:
203: if(($init ne "init") && ($type ne "local")) {
204: &logthis('<font color = "red"> LocalConnection: caller is insane! '
205: ."init = $init, and type = $type </font>");
206: close($Socket);;
207: return undef;
208:
209: }
210: # Now get the key filename:
211:
212: my $IDEAKey = lonlocal::ReadKeyFile($name);
213: return $IDEAKey;
214: }
215: }
216: #------------------------------------------------------------------------------
217: #
218: # SSLConnection
219: # Completes the formation of an ssh authenticated connection. The
220: # socket is promoted to an ssl socket. If this promotion and the associated
221: # certificate exchange are successful, the IDEA key is generated and sent
222: # to the remote peer via the SSL tunnel. The IDEA key is also returned to
223: # the caller after the SSL tunnel is torn down.
224: #
225: # Parameters:
226: # Name Type Purpose
227: # $Socket IO::Socket::INET Plaintext socket.
228: #
229: # Returns:
230: # IDEA key on success.
231: # undef on failure.
232: #
233: sub SSLConnection {
234: my $Socket = shift;
235:
236: Debug("SSLConnection: ");
237: my $KeyFile = lonssl::KeyFile();
238: if(!$KeyFile) {
239: my $err = lonssl::LastError();
240: &logthis("<font color=\"red\"> CRITICAL"
241: ."Can't get key file $err </font>");
242: return undef;
243: }
244: my ($CACertificate,
245: $Certificate) = lonssl::CertificateFile();
246:
247:
248: # If any of the key, certificate or certificate authority
249: # certificate filenames are not defined, this can't work.
250:
251: if((!$Certificate) || (!$CACertificate)) {
252: my $err = lonssl::LastError();
253: &logthis("<font color=\"red\"> CRITICAL"
254: ."Can't get certificates: $err </font>");
255:
256: return undef;
257: }
258: Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
259:
260: # Indicate to our peer that we can procede with
261: # a transition to ssl authentication:
262:
263: print $Socket "ok:ssl\n";
264:
265: Debug("Approving promotion -> ssl");
266: # And do so:
267:
268: my $SSLSocket = lonssl::PromoteServerSocket($Socket,
269: $CACertificate,
270: $Certificate,
271: $KeyFile);
272: if(! ($SSLSocket) ) { # SSL socket promotion failed.
273: my $err = lonssl::LastError();
274: &logthis("<font color=\"red\"> CRITICAL "
275: ."SSL Socket promotion failed: $err </font>");
276: return undef;
277: }
278: Debug("SSL Promotion successful");
279:
280: #
281: # The only thing we'll use the socket for is to send the IDEA key
282: # to the peer:
283:
284: my $Key = lonlocal::CreateCipherKey();
285: print $SSLSocket "$Key\n";
286:
287: lonssl::Close($SSLSocket);
288:
289: Debug("Key exchange complete: $Key");
290:
291: return $Key;
292: }
293: #
294: # InsecureConnection:
295: # If insecure connections are allowd,
296: # exchange a challenge with the client to 'validate' the
297: # client (not really, but that's the protocol):
298: # We produce a challenge string that's sent to the client.
299: # The client must then echo the challenge verbatim to us.
300: #
301: # Parameter:
302: # Socket - Socket open on the client.
303: # Returns:
304: # 1 - success.
305: # 0 - failure (e.g.mismatch or insecure not allowed).
306: #
307: sub InsecureConnection {
308: my $Socket = shift;
309:
310: # Don't even start if insecure connections are not allowed.
311:
312: if(! $perlvar{londAllowInsecure}) { # Insecure connections not allowed.
313: return 0;
314: }
315:
316: # Fabricate a challenge string and send it..
317:
318: my $challenge = "$$".time; # pid + time.
319: print $Socket "$challenge\n";
320: &status("Waiting for challenge reply");
321:
322: my $answer = <$Socket>;
323: $answer =~s/\W//g;
324: if($challenge eq $answer) {
325: return 1;
326: }
327: else {
328: logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
329: &status("No challenge reqply");
330: return 0;
331: }
332:
333:
334: }
335:
336: #
337: # GetCertificate: Given a transaction that requires a certificate,
338: # this function will extract the certificate from the transaction
339: # request. Note that at this point, the only concept of a certificate
340: # is the hostname to which we are connected.
341: #
342: # Parameter:
343: # request - The request sent by our client (this parameterization may
344: # need to change when we really use a certificate granting
345: # authority.
346: #
347: sub GetCertificate {
348: my $request = shift;
349:
350: return $clientip;
351: }
352:
353: #
354: # Return true if client is a manager.
355: #
356: sub isManager {
357: return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
358: }
359: #
360: # Return tru if client can do client functions
361: #
362: sub isClient {
363: return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
364: }
365:
366:
367: #
368: # ReadManagerTable: Reads in the current manager table. For now this is
369: # done on each manager authentication because:
370: # - These authentications are not frequent
371: # - This allows dynamic changes to the manager table
372: # without the need to signal to the lond.
373: #
374:
375: sub ReadManagerTable {
376:
377: # Clean out the old table first..
378:
379: foreach my $key (keys %managers) {
380: delete $managers{$key};
381: }
382:
383: my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
384: if (!open (MANAGERS, $tablename)) {
385: logthis('<font color="red">No manager table. Nobody can manage!!</font>');
386: return;
387: }
388: while(my $host = <MANAGERS>) {
389: chomp($host);
390: if ($host =~ "^#") { # Comment line.
391: next;
392: }
393: if (!defined $hostip{$host}) { # This is a non cluster member
394: # The entry is of the form:
395: # cluname:hostname
396: # cluname - A 'cluster hostname' is needed in order to negotiate
397: # the host key.
398: # hostname- The dns name of the host.
399: #
400: my($cluname, $dnsname) = split(/:/, $host);
401:
402: my $ip = gethostbyname($dnsname);
403: if(defined($ip)) { # bad names don't deserve entry.
404: my $hostip = inet_ntoa($ip);
405: $managers{$hostip} = $cluname;
406: logthis('<font color="green"> registering manager '.
407: "$dnsname as $cluname with $hostip </font>\n");
408: }
409: } else {
410: logthis('<font color="green"> existing host'." $host</font>\n");
411: $managers{$hostip{$host}} = $host; # Use info from cluster tab if clumemeber
412: }
413: }
414: }
415:
416: #
417: # ValidManager: Determines if a given certificate represents a valid manager.
418: # in this primitive implementation, the 'certificate' is
419: # just the connecting loncapa client name. This is checked
420: # against a valid client list in the configuration.
421: #
422: #
423: sub ValidManager {
424: my $certificate = shift;
425:
426: return isManager;
427: }
428: #
429: # CopyFile: Called as part of the process of installing a
430: # new configuration file. This function copies an existing
431: # file to a backup file.
432: # Parameters:
433: # oldfile - Name of the file to backup.
434: # newfile - Name of the backup file.
435: # Return:
436: # 0 - Failure (errno has failure reason).
437: # 1 - Success.
438: #
439: sub CopyFile {
440:
441: my ($oldfile, $newfile) = @_;
442:
443: # The file must exist:
444:
445: if(-e $oldfile) {
446:
447: # Read the old file.
448:
449: my $oldfh = IO::File->new("< $oldfile");
450: if(!$oldfh) {
451: return 0;
452: }
453: my @contents = <$oldfh>; # Suck in the entire file.
454:
455: # write the backup file:
456:
457: my $newfh = IO::File->new("> $newfile");
458: if(!(defined $newfh)){
459: return 0;
460: }
461: my $lines = scalar @contents;
462: for (my $i =0; $i < $lines; $i++) {
463: print $newfh ($contents[$i]);
464: }
465:
466: $oldfh->close;
467: $newfh->close;
468:
469: chmod(0660, $newfile);
470:
471: return 1;
472:
473: } else {
474: return 0;
475: }
476: }
477: #
478: # Host files are passed out with externally visible host IPs.
479: # If, for example, we are behind a fire-wall or NAT host, our
480: # internally visible IP may be different than the externally
481: # visible IP. Therefore, we always adjust the contents of the
482: # host file so that the entry for ME is the IP that we believe
483: # we have. At present, this is defined as the entry that
484: # DNS has for us. If by some chance we are not able to get a
485: # DNS translation for us, then we assume that the host.tab file
486: # is correct.
487: # BUGBUGBUG - in the future, we really should see if we can
488: # easily query the interface(s) instead.
489: # Parameter(s):
490: # contents - The contents of the host.tab to check.
491: # Returns:
492: # newcontents - The adjusted contents.
493: #
494: #
495: sub AdjustHostContents {
496: my $contents = shift;
497: my $adjusted;
498: my $me = $perlvar{'lonHostID'};
499:
500: foreach my $line (split(/\n/,$contents)) {
501: if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
502: chomp($line);
503: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
504: if ($id eq $me) {
505: my $ip = gethostbyname($name);
506: my $ipnew = inet_ntoa($ip);
507: $ip = $ipnew;
508: # Reconstruct the host line and append to adjusted:
509:
510: my $newline = "$id:$domain:$role:$name:$ip";
511: if($maxcon ne "") { # Not all hosts have loncnew tuning params
512: $newline .= ":$maxcon:$idleto:$mincon";
513: }
514: $adjusted .= $newline."\n";
515:
516: } else { # Not me, pass unmodified.
517: $adjusted .= $line."\n";
518: }
519: } else { # Blank or comment never re-written.
520: $adjusted .= $line."\n"; # Pass blanks and comments as is.
521: }
522: }
523: return $adjusted;
524: }
525: #
526: # InstallFile: Called to install an administrative file:
527: # - The file is created with <name>.tmp
528: # - The <name>.tmp file is then mv'd to <name>
529: # This lugubrious procedure is done to ensure that we are never without
530: # a valid, even if dated, version of the file regardless of who crashes
531: # and when the crash occurs.
532: #
533: # Parameters:
534: # Name of the file
535: # File Contents.
536: # Return:
537: # nonzero - success.
538: # 0 - failure and $! has an errno.
539: #
540: sub InstallFile {
541:
542: my ($Filename, $Contents) = @_;
543: my $TempFile = $Filename.".tmp";
544:
545: # Open the file for write:
546:
547: my $fh = IO::File->new("> $TempFile"); # Write to temp.
548: if(!(defined $fh)) {
549: &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
550: return 0;
551: }
552: # write the contents of the file:
553:
554: print $fh ($Contents);
555: $fh->close; # In case we ever have a filesystem w. locking
556:
557: chmod(0660, $TempFile);
558:
559: # Now we can move install the file in position.
560:
561: move($TempFile, $Filename);
562:
563: return 1;
564: }
565:
566:
567: #
568: # ConfigFileFromSelector: converts a configuration file selector
569: # (one of host or domain at this point) into a
570: # configuration file pathname.
571: #
572: # Parameters:
573: # selector - Configuration file selector.
574: # Returns:
575: # Full path to the file or undef if the selector is invalid.
576: #
577: sub ConfigFileFromSelector {
578: my $selector = shift;
579: my $tablefile;
580:
581: my $tabledir = $perlvar{'lonTabDir'}.'/';
582: if ($selector eq "hosts") {
583: $tablefile = $tabledir."hosts.tab";
584: } elsif ($selector eq "domain") {
585: $tablefile = $tabledir."domain.tab";
586: } else {
587: return undef;
588: }
589: return $tablefile;
590:
591: }
592: #
593: # PushFile: Called to do an administrative push of a file.
594: # - Ensure the file being pushed is one we support.
595: # - Backup the old file to <filename.saved>
596: # - Separate the contents of the new file out from the
597: # rest of the request.
598: # - Write the new file.
599: # Parameter:
600: # Request - The entire user request. This consists of a : separated
601: # string pushfile:tablename:contents.
602: # NOTE: The contents may have :'s in it as well making things a bit
603: # more interesting... but not much.
604: # Returns:
605: # String to send to client ("ok" or "refused" if bad file).
606: #
607: sub PushFile {
608: my $request = shift;
609: my ($command, $filename, $contents) = split(":", $request, 3);
610:
611: # At this point in time, pushes for only the following tables are
612: # supported:
613: # hosts.tab ($filename eq host).
614: # domain.tab ($filename eq domain).
615: # Construct the destination filename or reject the request.
616: #
617: # lonManage is supposed to ensure this, however this session could be
618: # part of some elaborate spoof that managed somehow to authenticate.
619: #
620:
621:
622: my $tablefile = ConfigFileFromSelector($filename);
623: if(! (defined $tablefile)) {
624: return "refused";
625: }
626: #
627: # >copy< the old table to the backup table
628: # don't rename in case system crashes/reboots etc. in the time
629: # window between a rename and write.
630: #
631: my $backupfile = $tablefile;
632: $backupfile =~ s/\.tab$/.old/;
633: if(!CopyFile($tablefile, $backupfile)) {
634: &logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
635: return "error:$!";
636: }
637: &logthis('<font color="green"> Pushfile: backed up '
638: .$tablefile." to $backupfile</font>");
639:
640: # If the file being pushed is the host file, we adjust the entry for ourself so that the
641: # IP will be our current IP as looked up in dns. Note this is only 99% good as it's possible
642: # to conceive of conditions where we don't have a DNS entry locally. This is possible in a
643: # network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
644: # that possibilty.
645:
646: if($filename eq "host") {
647: $contents = AdjustHostContents($contents);
648: }
649:
650: # Install the new file:
651:
652: if(!InstallFile($tablefile, $contents)) {
653: &logthis('<font color="red"> Pushfile: unable to install '
654: .$tablefile." $! </font>");
655: return "error:$!";
656: }
657: else {
658: &logthis('<font color="green"> Installed new '.$tablefile
659: ."</font>");
660:
661: }
662:
663:
664: # Indicate success:
665:
666: return "ok";
667:
668: }
669:
670: #
671: # Called to re-init either lonc or lond.
672: #
673: # Parameters:
674: # request - The full request by the client. This is of the form
675: # reinit:<process>
676: # where <process> is allowed to be either of
677: # lonc or lond
678: #
679: # Returns:
680: # The string to be sent back to the client either:
681: # ok - Everything worked just fine.
682: # error:why - There was a failure and why describes the reason.
683: #
684: #
685: sub ReinitProcess {
686: my $request = shift;
687:
688:
689: # separate the request (reinit) from the process identifier and
690: # validate it producing the name of the .pid file for the process.
691: #
692: #
693: my ($junk, $process) = split(":", $request);
694: my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
695: if($process eq 'lonc') {
696: $processpidfile = $processpidfile."lonc.pid";
697: if (!open(PIDFILE, "< $processpidfile")) {
698: return "error:Open failed for $processpidfile";
699: }
700: my $loncpid = <PIDFILE>;
701: close(PIDFILE);
702: logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
703: ."</font>");
704: kill("USR2", $loncpid);
705: } elsif ($process eq 'lond') {
706: logthis('<font color="red"> Reinitializing self (lond) </font>');
707: &UpdateHosts; # Lond is us!!
708: } else {
709: &logthis('<font color="yellow" Invalid reinit request for '.$process
710: ."</font>");
711: return "error:Invalid process identifier $process";
712: }
713: return 'ok';
714: }
715: # Validate a line in a configuration file edit script:
716: # Validation includes:
717: # - Ensuring the command is valid.
718: # - Ensuring the command has sufficient parameters
719: # Parameters:
720: # scriptline - A line to validate (\n has been stripped for what it's worth).
721: #
722: # Return:
723: # 0 - Invalid scriptline.
724: # 1 - Valid scriptline
725: # NOTE:
726: # Only the command syntax is checked, not the executability of the
727: # command.
728: #
729: sub isValidEditCommand {
730: my $scriptline = shift;
731:
732: # Line elements are pipe separated:
733:
734: my ($command, $key, $newline) = split(/\|/, $scriptline);
735: &logthis('<font color="green"> isValideditCommand checking: '.
736: "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
737:
738: if ($command eq "delete") {
739: #
740: # key with no newline.
741: #
742: if( ($key eq "") || ($newline ne "")) {
743: return 0; # Must have key but no newline.
744: } else {
745: return 1; # Valid syntax.
746: }
747: } elsif ($command eq "replace") {
748: #
749: # key and newline:
750: #
751: if (($key eq "") || ($newline eq "")) {
752: return 0;
753: } else {
754: return 1;
755: }
756: } elsif ($command eq "append") {
757: if (($key ne "") && ($newline eq "")) {
758: return 1;
759: } else {
760: return 0;
761: }
762: } else {
763: return 0; # Invalid command.
764: }
765: return 0; # Should not get here!!!
766: }
767: #
768: # ApplyEdit - Applies an edit command to a line in a configuration
769: # file. It is the caller's responsiblity to validate the
770: # edit line.
771: # Parameters:
772: # $directive - A single edit directive to apply.
773: # Edit directives are of the form:
774: # append|newline - Appends a new line to the file.
775: # replace|key|newline - Replaces the line with key value 'key'
776: # delete|key - Deletes the line with key value 'key'.
777: # $editor - A config file editor object that contains the
778: # file being edited.
779: #
780: sub ApplyEdit {
781:
782: my ($directive, $editor) = @_;
783:
784: # Break the directive down into its command and its parameters
785: # (at most two at this point. The meaning of the parameters, if in fact
786: # they exist depends on the command).
787:
788: my ($command, $p1, $p2) = split(/\|/, $directive);
789:
790: if($command eq "append") {
791: $editor->Append($p1); # p1 - key p2 null.
792: } elsif ($command eq "replace") {
793: $editor->ReplaceLine($p1, $p2); # p1 - key p2 = newline.
794: } elsif ($command eq "delete") {
795: $editor->DeleteLine($p1); # p1 - key p2 null.
796: } else { # Should not get here!!!
797: die "Invalid command given to ApplyEdit $command"
798: }
799: }
800: #
801: # AdjustOurHost:
802: # Adjusts a host file stored in a configuration file editor object
803: # for the true IP address of this host. This is necessary for hosts
804: # that live behind a firewall.
805: # Those hosts have a publicly distributed IP of the firewall, but
806: # internally must use their actual IP. We assume that a given
807: # host only has a single IP interface for now.
808: # Formal Parameters:
809: # editor - The configuration file editor to adjust. This
810: # editor is assumed to contain a hosts.tab file.
811: # Strategy:
812: # - Figure out our hostname.
813: # - Lookup the entry for this host.
814: # - Modify the line to contain our IP
815: # - Do a replace for this host.
816: sub AdjustOurHost {
817: my $editor = shift;
818:
819: # figure out who I am.
820:
821: my $myHostName = $perlvar{'lonHostID'}; # LonCAPA hostname.
822:
823: # Get my host file entry.
824:
825: my $ConfigLine = $editor->Find($myHostName);
826: if(! (defined $ConfigLine)) {
827: die "AdjustOurHost - no entry for me in hosts file $myHostName";
828: }
829: # figure out my IP:
830: # Use the config line to get my hostname.
831: # Use gethostbyname to translate that into an IP address.
832: #
833: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
834: my $BinaryIp = gethostbyname($name);
835: my $ip = inet_ntoa($ip);
836: #
837: # Reassemble the config line from the elements in the list.
838: # Note that if the loncnew items were not present before, they will
839: # be now even if they would be empty
840: #
841: my $newConfigLine = $id;
842: foreach my $item ($domain, $role, $name, $ip, $maxcon, $idleto, $mincon) {
843: $newConfigLine .= ":".$item;
844: }
845: # Replace the line:
846:
847: $editor->ReplaceLine($id, $newConfigLine);
848:
849: }
850: #
851: # ReplaceConfigFile:
852: # Replaces a configuration file with the contents of a
853: # configuration file editor object.
854: # This is done by:
855: # - Copying the target file to <filename>.old
856: # - Writing the new file to <filename>.tmp
857: # - Moving <filename.tmp> -> <filename>
858: # This laborious process ensures that the system is never without
859: # a configuration file that's at least valid (even if the contents
860: # may be dated).
861: # Parameters:
862: # filename - Name of the file to modify... this is a full path.
863: # editor - Editor containing the file.
864: #
865: sub ReplaceConfigFile {
866:
867: my ($filename, $editor) = @_;
868:
869: CopyFile ($filename, $filename.".old");
870:
871: my $contents = $editor->Get(); # Get the contents of the file.
872:
873: InstallFile($filename, $contents);
874: }
875: #
876: #
877: # Called to edit a configuration table file
878: # Parameters:
879: # request - The entire command/request sent by lonc or lonManage
880: # Return:
881: # The reply to send to the client.
882: #
883: sub EditFile {
884: my $request = shift;
885:
886: # Split the command into it's pieces: edit:filetype:script
887:
888: my ($request, $filetype, $script) = split(/:/, $request,3); # : in script
889:
890: # Check the pre-coditions for success:
891:
892: if($request != "edit") { # Something is amiss afoot alack.
893: return "error:edit request detected, but request != 'edit'\n";
894: }
895: if( ($filetype ne "hosts") &&
896: ($filetype ne "domain")) {
897: return "error:edit requested with invalid file specifier: $filetype \n";
898: }
899:
900: # Split the edit script and check it's validity.
901:
902: my @scriptlines = split(/\n/, $script); # one line per element.
903: my $linecount = scalar(@scriptlines);
904: for(my $i = 0; $i < $linecount; $i++) {
905: chomp($scriptlines[$i]);
906: if(!isValidEditCommand($scriptlines[$i])) {
907: return "error:edit with bad script line: '$scriptlines[$i]' \n";
908: }
909: }
910:
911: # Execute the edit operation.
912: # - Create a config file editor for the appropriate file and
913: # - execute each command in the script:
914: #
915: my $configfile = ConfigFileFromSelector($filetype);
916: if (!(defined $configfile)) {
917: return "refused\n";
918: }
919: my $editor = ConfigFileEdit->new($configfile);
920:
921: for (my $i = 0; $i < $linecount; $i++) {
922: ApplyEdit($scriptlines[$i], $editor);
923: }
924: # If the file is the host file, ensure that our host is
925: # adjusted to have our ip:
926: #
927: if($filetype eq "host") {
928: AdjustOurHost($editor);
929: }
930: # Finally replace the current file with our file.
931: #
932: ReplaceConfigFile($configfile, $editor);
933:
934: return "ok\n";
935: }
936:
937: #---------------------------------------------------------------
938: #
939: # Manipulation of hash based databases (factoring out common code
940: # for later use as we refactor.
941: #
942: # Ties a domain level resource file to a hash.
943: # If requested a history entry is created in the associated hist file.
944: #
945: # Parameters:
946: # domain - Name of the domain in which the resource file lives.
947: # namespace - Name of the hash within that domain.
948: # how - How to tie the hash (e.g. GDBM_WRCREAT()).
949: # loghead - Optional parameter, if present a log entry is created
950: # in the associated history file and this is the first part
951: # of that entry.
952: # logtail - Goes along with loghead, The actual logentry is of the
953: # form $loghead:<timestamp>:logtail.
954: # Returns:
955: # Reference to a hash bound to the db file or alternatively undef
956: # if the tie failed.
957: #
958: sub tie_domain_hash {
959: my ($domain,$namespace,$how,$loghead,$logtail) = @_;
960:
961: # Filter out any whitespace in the domain name:
962:
963: $domain =~ s/\W//g;
964:
965: # We have enough to go on to tie the hash:
966:
967: my $user_top_dir = $perlvar{'lonUsersDir'};
968: my $domain_dir = $user_top_dir."/$domain";
969: my $resource_file = $domain_dir."/$namespace.db";
970: my %hash;
971: if(tie(%hash, 'GDBM_File', $resource_file, $how, 0640)) {
972: if (defined($loghead)) { # Need to log the operation.
973: my $logFh = IO::File->new(">>$domain_dir/$namespace.hist");
974: if($logFh) {
975: my $timestamp = time;
976: print $logFh "$loghead:$timestamp:$logtail\n";
977: }
978: $logFh->close;
979: }
980: return \%hash; # Return the tied hash.
981: } else {
982: return undef; # Tie failed.
983: }
984: }
985:
986: #
987: # Ties a user's resource file to a hash.
988: # If necessary, an appropriate history
989: # log file entry is made as well.
990: # This sub factors out common code from the subs that manipulate
991: # the various gdbm files that keep keyword value pairs.
992: # Parameters:
993: # domain - Name of the domain the user is in.
994: # user - Name of the 'current user'.
995: # namespace - Namespace representing the file to tie.
996: # how - What the tie is done to (e.g. GDBM_WRCREAT().
997: # loghead - Optional first part of log entry if there may be a
998: # history file.
999: # what - Optional tail of log entry if there may be a history
1000: # file.
1001: # Returns:
1002: # hash to which the database is tied. It's up to the caller to untie.
1003: # undef if the has could not be tied.
1004: #
1005: sub tie_user_hash {
1006: my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
1007:
1008: $namespace=~s/\//\_/g; # / -> _
1009: $namespace=~s/\W//g; # whitespace eliminated.
1010: my $proname = propath($domain, $user);
1011:
1012: # Tie the database.
1013:
1014: my %hash;
1015: if(tie(%hash, 'GDBM_File', "$proname/$namespace.db",
1016: $how, 0640)) {
1017: # If this is a namespace for which a history is kept,
1018: # make the history log entry:
1019: if (($namespace =~/^nohist\_/) && (defined($loghead))) {
1020: my $args = scalar @_;
1021: Debug(" Opening history: $namespace $args");
1022: my $hfh = IO::File->new(">>$proname/$namespace.hist");
1023: if($hfh) {
1024: my $now = time;
1025: print $hfh "$loghead:$now:$what\n";
1026: }
1027: $hfh->close;
1028: }
1029: return \%hash;
1030: } else {
1031: return undef;
1032: }
1033:
1034: }
1035: #---------------------------------------------------------------
1036: #
1037: # Getting, decoding and dispatching requests:
1038: #
1039:
1040: #
1041: # Get a Request:
1042: # Gets a Request message from the client. The transaction
1043: # is defined as a 'line' of text. We remove the new line
1044: # from the text line.
1045: #
1046: sub get_request {
1047: my $input = <$client>;
1048: chomp($input);
1049:
1050: Debug("get_request: Request = $input\n");
1051:
1052: &status('Processing '.$clientname.':'.$input);
1053:
1054: return $input;
1055: }
1056: #---------------------------------------------------------------
1057: #
1058: # Process a request. This sub should shrink as each action
1059: # gets farmed out into a separat sub that is registered
1060: # with the dispatch hash.
1061: #
1062: # Parameters:
1063: # user_input - The request received from the client (lonc).
1064: # Returns:
1065: # true to keep processing, false if caller should exit.
1066: #
1067: sub process_request {
1068: my ($userinput) = @_; # Easier for now to break style than to
1069: # fix all the userinput -> user_input.
1070: my $wasenc = 0; # True if request was encrypted.
1071: # ------------------------------------------------------------ See if encrypted
1072: if ($userinput =~ /^enc/) {
1073: $userinput = decipher($userinput);
1074: $wasenc=1;
1075: if(!$userinput) { # Cipher not defined.
1076: &Failure($client, "error: Encrypted data without negotated key");
1077: return 0;
1078: }
1079: }
1080: Debug("process_request: $userinput\n");
1081:
1082: #
1083: # The 'correct way' to add a command to lond is now to
1084: # write a sub to execute it and Add it to the command dispatch
1085: # hash via a call to register_handler.. The comments to that
1086: # sub should give you enough to go on to show how to do this
1087: # along with the examples that are building up as this code
1088: # is getting refactored. Until all branches of the
1089: # if/elseif monster below have been factored out into
1090: # separate procesor subs, if the dispatch hash is missing
1091: # the command keyword, we will fall through to the remainder
1092: # of the if/else chain below in order to keep this thing in
1093: # working order throughout the transmogrification.
1094:
1095: my ($command, $tail) = split(/:/, $userinput, 2);
1096: chomp($command);
1097: chomp($tail);
1098: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
1099:
1100: &Debug("Command received: $command, encoded = $wasenc");
1101:
1102: if(defined $Dispatcher{$command}) {
1103:
1104: my $dispatch_info = $Dispatcher{$command};
1105: my $handler = $$dispatch_info[0];
1106: my $need_encode = $$dispatch_info[1];
1107: my $client_types = $$dispatch_info[2];
1108: Debug("Matched dispatch hash: mustencode: $need_encode "
1109: ."ClientType $client_types");
1110:
1111: # Validate the request:
1112:
1113: my $ok = 1;
1114: my $requesterprivs = 0;
1115: if(&isClient()) {
1116: $requesterprivs |= $CLIENT_OK;
1117: }
1118: if(&isManager()) {
1119: $requesterprivs |= $MANAGER_OK;
1120: }
1121: if($need_encode && (!$wasenc)) {
1122: Debug("Must encode but wasn't: $need_encode $wasenc");
1123: $ok = 0;
1124: }
1125: if(($client_types & $requesterprivs) == 0) {
1126: Debug("Client not privileged to do this operation");
1127: $ok = 0;
1128: }
1129:
1130: if($ok) {
1131: Debug("Dispatching to handler $command $tail");
1132: my $keep_going = &$handler($command, $tail, $client);
1133: return $keep_going;
1134: } else {
1135: Debug("Refusing to dispatch because client did not match requirements");
1136: Failure($client, "refused\n", $userinput);
1137: return 1;
1138: }
1139:
1140: }
1141:
1142: # ------------------------------------------------------------- Normal commands
1143: # ------------------------------------------------------------------------ ping
1144: if ($userinput =~ /^ping/) { # client only
1145: if(isClient) {
1146: print $client "$currenthostid\n";
1147: } else {
1148: Reply($client, "refused\n", $userinput);
1149: }
1150: # ------------------------------------------------------------------------ pong
1151: }elsif ($userinput =~ /^pong/) { # client only
1152: if(isClient) {
1153: my $reply=&reply("ping",$clientname);
1154: print $client "$currenthostid:$reply\n";
1155: } else {
1156: Reply($client, "refused\n", $userinput);
1157: }
1158: # ------------------------------------------------------------------------ ekey
1159: } elsif ($userinput =~ /^ekey/) { # ok for both clients & mgrs
1160: my $buildkey=time.$$.int(rand 100000);
1161: $buildkey=~tr/1-6/A-F/;
1162: $buildkey=int(rand 100000).$buildkey.int(rand 100000);
1163: my $key=$currenthostid.$clientname;
1164: $key=~tr/a-z/A-Z/;
1165: $key=~tr/G-P/0-9/;
1166: $key=~tr/Q-Z/0-9/;
1167: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
1168: $key=substr($key,0,32);
1169: my $cipherkey=pack("H32",$key);
1170: $cipher=new IDEA $cipherkey;
1171: print $client "$buildkey\n";
1172: # ------------------------------------------------------------------------ load
1173: } elsif ($userinput =~ /^load/) { # client only
1174: if (isClient) {
1175: my $loadavg;
1176: {
1177: my $loadfile=IO::File->new('/proc/loadavg');
1178: $loadavg=<$loadfile>;
1179: }
1180: $loadavg =~ s/\s.*//g;
1181: my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
1182: print $client "$loadpercent\n";
1183: } else {
1184: Reply($client, "refused\n", $userinput);
1185:
1186: }
1187: # -------------------------------------------------------------------- userload
1188: } elsif ($userinput =~ /^userload/) { # client only
1189: if(isClient) {
1190: my $userloadpercent=&userload();
1191: print $client "$userloadpercent\n";
1192: } else {
1193: Reply($client, "refused\n", $userinput);
1194:
1195: }
1196: #
1197: # Transactions requiring encryption:
1198: #
1199: # ----------------------------------------------------------------- currentauth
1200: } elsif ($userinput =~ /^currentauth/) {
1201: if (($wasenc==1) && isClient) { # Encoded & client only.
1202: my ($cmd,$udom,$uname)=split(/:/,$userinput);
1203: my $result = GetAuthType($udom, $uname);
1204: if($result eq "nouser") {
1205: print $client "unknown_user\n";
1206: }
1207: else {
1208: print $client "$result\n";
1209: }
1210: } else {
1211: Reply($client, "refused\n", $userinput);
1212:
1213: }
1214: #--------------------------------------------------------------------- pushfile
1215: } elsif($userinput =~ /^pushfile/) { # encoded & manager.
1216: if(($wasenc == 1) && isManager) {
1217: my $cert = GetCertificate($userinput);
1218: if(ValidManager($cert)) {
1219: my $reply = PushFile($userinput);
1220: print $client "$reply\n";
1221: } else {
1222: print $client "refused\n";
1223: }
1224: } else {
1225: Reply($client, "refused\n", $userinput);
1226:
1227: }
1228: #--------------------------------------------------------------------- reinit
1229: } elsif($userinput =~ /^reinit/) { # Encoded and manager
1230: if (($wasenc == 1) && isManager) {
1231: my $cert = GetCertificate($userinput);
1232: if(ValidManager($cert)) {
1233: chomp($userinput);
1234: my $reply = ReinitProcess($userinput);
1235: print $client "$reply\n";
1236: } else {
1237: print $client "refused\n";
1238: }
1239: } else {
1240: Reply($client, "refused\n", $userinput);
1241: }
1242: #------------------------------------------------------------------------- edit
1243: } elsif ($userinput =~ /^edit/) { # encoded and manager:
1244: if(($wasenc ==1) && (isManager)) {
1245: my $cert = GetCertificate($userinput);
1246: if(ValidManager($cert)) {
1247: my($command, $filetype, $script) = split(/:/, $userinput);
1248: if (($filetype eq "hosts") || ($filetype eq "domain")) {
1249: if($script ne "") {
1250: Reply($client, EditFile($userinput));
1251: } else {
1252: Reply($client,"refused\n",$userinput);
1253: }
1254: } else {
1255: Reply($client,"refused\n",$userinput);
1256: }
1257: } else {
1258: Reply($client,"refused\n",$userinput);
1259: }
1260: } else {
1261: Reply($client,"refused\n",$userinput);
1262: }
1263: # ------------------------------------------------------------------------ auth
1264: } elsif ($userinput =~ /^auth/) { # Encoded and client only.
1265: if (($wasenc==1) && isClient) {
1266: my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
1267: chomp($upass);
1268: $upass=unescape($upass);
1269: my $proname=propath($udom,$uname);
1270: my $passfilename="$proname/passwd";
1271: if (-e $passfilename) {
1272: my $pf = IO::File->new($passfilename);
1273: my $realpasswd=<$pf>;
1274: chomp($realpasswd);
1275: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1276: my $pwdcorrect=0;
1277: if ($howpwd eq 'internal') {
1278: &Debug("Internal auth");
1279: $pwdcorrect=
1280: (crypt($upass,$contentpwd) eq $contentpwd);
1281: } elsif ($howpwd eq 'unix') {
1282: &Debug("Unix auth");
1283: if((getpwnam($uname))[1] eq "") { #no such user!
1284: $pwdcorrect = 0;
1285: } else {
1286: $contentpwd=(getpwnam($uname))[1];
1287: my $pwauth_path="/usr/local/sbin/pwauth";
1288: unless ($contentpwd eq 'x') {
1289: $pwdcorrect=
1290: (crypt($upass,$contentpwd) eq
1291: $contentpwd);
1292: }
1293:
1294: elsif (-e $pwauth_path) {
1295: open PWAUTH, "|$pwauth_path" or
1296: die "Cannot invoke authentication";
1297: print PWAUTH "$uname\n$upass\n";
1298: close PWAUTH;
1299: $pwdcorrect=!$?;
1300: }
1301: }
1302: } elsif ($howpwd eq 'krb4') {
1303: my $null=pack("C",0);
1304: unless ($upass=~/$null/) {
1305: my $krb4_error = &Authen::Krb4::get_pw_in_tkt
1306: ($uname,"",$contentpwd,'krbtgt',
1307: $contentpwd,1,$upass);
1308: if (!$krb4_error) {
1309: $pwdcorrect = 1;
1310: } else {
1311: $pwdcorrect=0;
1312: # log error if it is not a bad password
1313: if ($krb4_error != 62) {
1314: &logthis('krb4:'.$uname.','.
1315: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
1316: }
1317: }
1318: }
1319: } elsif ($howpwd eq 'krb5') {
1320: my $null=pack("C",0);
1321: unless ($upass=~/$null/) {
1322: my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
1323: my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
1324: my $krbserver=&Authen::Krb5::parse_name($krbservice);
1325: my $credentials=&Authen::Krb5::cc_default();
1326: $credentials->initialize($krbclient);
1327: my $krbreturn =
1328: &Authen::Krb5::get_in_tkt_with_password(
1329: $krbclient,$krbserver,$upass,$credentials);
1330: # unless ($krbreturn) {
1331: # &logthis("Krb5 Error: ".
1332: # &Authen::Krb5::error());
1333: # }
1334: $pwdcorrect = ($krbreturn == 1);
1335: } else { $pwdcorrect=0; }
1336: } elsif ($howpwd eq 'localauth') {
1337: $pwdcorrect=&localauth::localauth($uname,$upass,
1338: $contentpwd);
1339: }
1340: if ($pwdcorrect) {
1341: print $client "authorized\n";
1342: } else {
1343: print $client "non_authorized\n";
1344: }
1345: } else {
1346: print $client "unknown_user\n";
1347: }
1348: } else {
1349: Reply($client, "refused\n", $userinput);
1350:
1351: }
1352: # ---------------------------------------------------------------------- passwd
1353: } elsif ($userinput =~ /^passwd/) { # encoded and client
1354: if (($wasenc==1) && isClient) {
1355: my
1356: ($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
1357: chomp($npass);
1358: $upass=&unescape($upass);
1359: $npass=&unescape($npass);
1360: &Debug("Trying to change password for $uname");
1361: my $proname=propath($udom,$uname);
1362: my $passfilename="$proname/passwd";
1363: if (-e $passfilename) {
1364: my $realpasswd;
1365: { my $pf = IO::File->new($passfilename);
1366: $realpasswd=<$pf>; }
1367: chomp($realpasswd);
1368: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1369: if ($howpwd eq 'internal') {
1370: &Debug("internal auth");
1371: if (crypt($upass,$contentpwd) eq $contentpwd) {
1372: my $salt=time;
1373: $salt=substr($salt,6,2);
1374: my $ncpass=crypt($npass,$salt);
1375: {
1376: my $pf;
1377: if ($pf = IO::File->new(">$passfilename")) {
1378: print $pf "internal:$ncpass\n";
1379: &logthis("Result of password change for $uname: pwchange_success");
1380: print $client "ok\n";
1381: } else {
1382: &logthis("Unable to open $uname passwd to change password");
1383: print $client "non_authorized\n";
1384: }
1385: }
1386:
1387: } else {
1388: print $client "non_authorized\n";
1389: }
1390: } elsif ($howpwd eq 'unix') {
1391: # Unix means we have to access /etc/password
1392: # one way or another.
1393: # First: Make sure the current password is
1394: # correct
1395: &Debug("auth is unix");
1396: $contentpwd=(getpwnam($uname))[1];
1397: my $pwdcorrect = "0";
1398: my $pwauth_path="/usr/local/sbin/pwauth";
1399: unless ($contentpwd eq 'x') {
1400: $pwdcorrect=
1401: (crypt($upass,$contentpwd) eq $contentpwd);
1402: } elsif (-e $pwauth_path) {
1403: open PWAUTH, "|$pwauth_path" or
1404: die "Cannot invoke authentication";
1405: print PWAUTH "$uname\n$upass\n";
1406: close PWAUTH;
1407: &Debug("exited pwauth with $? ($uname,$upass) ");
1408: $pwdcorrect=($? == 0);
1409: }
1410: if ($pwdcorrect) {
1411: my $execdir=$perlvar{'lonDaemons'};
1412: &Debug("Opening lcpasswd pipeline");
1413: my $pf = IO::File->new("|$execdir/lcpasswd > $perlvar{'lonDaemons'}/logs/lcpasswd.log");
1414: print $pf "$uname\n$npass\n$npass\n";
1415: close $pf;
1416: my $err = $?;
1417: my $result = ($err>0 ? 'pwchange_failure'
1418: : 'ok');
1419: &logthis("Result of password change for $uname: ".
1420: &lcpasswdstrerror($?));
1421: print $client "$result\n";
1422: } else {
1423: print $client "non_authorized\n";
1424: }
1425: } else {
1426: print $client "auth_mode_error\n";
1427: }
1428: } else {
1429: print $client "unknown_user\n";
1430: }
1431: } else {
1432: Reply($client, "refused\n", $userinput);
1433:
1434: }
1435: # -------------------------------------------------------------------- makeuser
1436: } elsif ($userinput =~ /^makeuser/) { # encoded and client.
1437: &Debug("Make user received");
1438: my $oldumask=umask(0077);
1439: if (($wasenc==1) && isClient) {
1440: my
1441: ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
1442: &Debug("cmd =".$cmd." $udom =".$udom.
1443: " uname=".$uname);
1444: chomp($npass);
1445: $npass=&unescape($npass);
1446: my $proname=propath($udom,$uname);
1447: my $passfilename="$proname/passwd";
1448: &Debug("Password file created will be:".
1449: $passfilename);
1450: if (-e $passfilename) {
1451: print $client "already_exists\n";
1452: } elsif ($udom ne $currentdomainid) {
1453: print $client "not_right_domain\n";
1454: } else {
1455: my @fpparts=split(/\//,$proname);
1456: my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
1457: my $fperror='';
1458: for (my $i=3;$i<=$#fpparts;$i++) {
1459: $fpnow.='/'.$fpparts[$i];
1460: unless (-e $fpnow) {
1461: unless (mkdir($fpnow,0777)) {
1462: $fperror="error: ".($!+0)
1463: ." mkdir failed while attempting "
1464: ."makeuser";
1465: }
1466: }
1467: }
1468: unless ($fperror) {
1469: my $result=&make_passwd_file($uname, $umode,$npass,
1470: $passfilename);
1471: print $client $result;
1472: } else {
1473: print $client "$fperror\n";
1474: }
1475: }
1476: } else {
1477: Reply($client, "refused\n", $userinput);
1478:
1479: }
1480: umask($oldumask);
1481: # -------------------------------------------------------------- changeuserauth
1482: } elsif ($userinput =~ /^changeuserauth/) { # encoded & client
1483: &Debug("Changing authorization");
1484: if (($wasenc==1) && isClient) {
1485: my
1486: ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
1487: chomp($npass);
1488: &Debug("cmd = ".$cmd." domain= ".$udom.
1489: "uname =".$uname." umode= ".$umode);
1490: $npass=&unescape($npass);
1491: my $proname=&propath($udom,$uname);
1492: my $passfilename="$proname/passwd";
1493: if ($udom ne $currentdomainid) {
1494: print $client "not_right_domain\n";
1495: } else {
1496: my $result=&make_passwd_file($uname, $umode,$npass,
1497: $passfilename);
1498: print $client $result;
1499: }
1500: } else {
1501: Reply($client, "refused\n", $userinput);
1502:
1503: }
1504: # ------------------------------------------------------------------------ home
1505: } elsif ($userinput =~ /^home/) { # client clear or encoded
1506: if(isClient) {
1507: my ($cmd,$udom,$uname)=split(/:/,$userinput);
1508: chomp($uname);
1509: my $proname=propath($udom,$uname);
1510: if (-e $proname) {
1511: print $client "found\n";
1512: } else {
1513: print $client "not_found\n";
1514: }
1515: } else {
1516: Reply($client, "refused\n", $userinput);
1517:
1518: }
1519: # ---------------------------------------------------------------------- update
1520: } elsif ($userinput =~ /^update/) { # client clear or encoded.
1521: if(isClient) {
1522: my ($cmd,$fname)=split(/:/,$userinput);
1523: my $ownership=ishome($fname);
1524: if ($ownership eq 'not_owner') {
1525: if (-e $fname) {
1526: my ($dev,$ino,$mode,$nlink,
1527: $uid,$gid,$rdev,$size,
1528: $atime,$mtime,$ctime,
1529: $blksize,$blocks)=stat($fname);
1530: my $now=time;
1531: my $since=$now-$atime;
1532: if ($since>$perlvar{'lonExpire'}) {
1533: my $reply=
1534: &reply("unsub:$fname","$clientname");
1535: unlink("$fname");
1536: } else {
1537: my $transname="$fname.in.transfer";
1538: my $remoteurl=
1539: &reply("sub:$fname","$clientname");
1540: my $response;
1541: {
1542: my $ua=new LWP::UserAgent;
1543: my $request=new HTTP::Request('GET',"$remoteurl");
1544: $response=$ua->request($request,$transname);
1545: }
1546: if ($response->is_error()) {
1547: unlink($transname);
1548: my $message=$response->status_line;
1549: &logthis(
1550: "LWP GET: $message for $fname ($remoteurl)");
1551: } else {
1552: if ($remoteurl!~/\.meta$/) {
1553: my $ua=new LWP::UserAgent;
1554: my $mrequest=
1555: new HTTP::Request('GET',$remoteurl.'.meta');
1556: my $mresponse=
1557: $ua->request($mrequest,$fname.'.meta');
1558: if ($mresponse->is_error()) {
1559: unlink($fname.'.meta');
1560: }
1561: }
1562: rename($transname,$fname);
1563: }
1564: }
1565: print $client "ok\n";
1566: } else {
1567: print $client "not_found\n";
1568: }
1569: } else {
1570: print $client "rejected\n";
1571: }
1572: } else {
1573: Reply($client, "refused\n", $userinput);
1574:
1575: }
1576: # -------------------------------------- fetch a user file from a remote server
1577: } elsif ($userinput =~ /^fetchuserfile/) { # Client clear or enc.
1578: if(isClient) {
1579: my ($cmd,$fname)=split(/:/,$userinput);
1580: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1581: my $udir=propath($udom,$uname).'/userfiles';
1582: unless (-e $udir) { mkdir($udir,0770); }
1583: if (-e $udir) {
1584: $ufile=~s/^[\.\~]+//;
1585: my $path = $udir;
1586: if ($ufile =~m|(.+)/([^/]+)$|) {
1587: my @parts=split('/',$1);
1588: foreach my $part (@parts) {
1589: $path .= '/'.$part;
1590: if ((-e $path)!=1) {
1591: mkdir($path,0770);
1592: }
1593: }
1594: }
1595: my $destname=$udir.'/'.$ufile;
1596: my $transname=$udir.'/'.$ufile.'.in.transit';
1597: my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
1598: my $response;
1599: {
1600: my $ua=new LWP::UserAgent;
1601: my $request=new HTTP::Request('GET',"$remoteurl");
1602: $response=$ua->request($request,$transname);
1603: }
1604: if ($response->is_error()) {
1605: unlink($transname);
1606: my $message=$response->status_line;
1607: &logthis("LWP GET: $message for $fname ($remoteurl)");
1608: print $client "failed\n";
1609: } else {
1610: if (!rename($transname,$destname)) {
1611: &logthis("Unable to move $transname to $destname");
1612: unlink($transname);
1613: print $client "failed\n";
1614: } else {
1615: print $client "ok\n";
1616: }
1617: }
1618: } else {
1619: print $client "not_home\n";
1620: }
1621: } else {
1622: Reply($client, "refused\n", $userinput);
1623: }
1624: # --------------------------------------------------------- remove a user file
1625: } elsif ($userinput =~ /^removeuserfile/) { # Client clear or enc.
1626: if(isClient) {
1627: my ($cmd,$fname)=split(/:/,$userinput);
1628: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1629: &logthis("$udom - $uname - $ufile");
1630: if ($ufile =~m|/\.\./|) {
1631: # any files paths with /../ in them refuse
1632: # to deal with
1633: print $client "refused\n";
1634: } else {
1635: my $udir=propath($udom,$uname);
1636: if (-e $udir) {
1637: my $file=$udir.'/userfiles/'.$ufile;
1638: if (-e $file) {
1639: unlink($file);
1640: if (-e $file) {
1641: print $client "failed\n";
1642: } else {
1643: print $client "ok\n";
1644: }
1645: } else {
1646: print $client "not_found\n";
1647: }
1648: } else {
1649: print $client "not_home\n";
1650: }
1651: }
1652: } else {
1653: Reply($client, "refused\n", $userinput);
1654: }
1655: # ------------------------------------------ authenticate access to a user file
1656: } elsif ($userinput =~ /^tokenauthuserfile/) { # Client only
1657: if(isClient) {
1658: my ($cmd,$fname,$session)=split(/:/,$userinput);
1659: chomp($session);
1660: my $reply='non_auth';
1661: if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
1662: $session.'.id')) {
1663: while (my $line=<ENVIN>) {
1664: if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply='ok'; }
1665: }
1666: close(ENVIN);
1667: print $client $reply."\n";
1668: } else {
1669: print $client "invalid_token\n";
1670: }
1671: } else {
1672: Reply($client, "refused\n", $userinput);
1673:
1674: }
1675: # ----------------------------------------------------------------- unsubscribe
1676: } elsif ($userinput =~ /^unsub/) {
1677: if(isClient) {
1678: my ($cmd,$fname)=split(/:/,$userinput);
1679: if (-e $fname) {
1680: print $client &unsub($fname,$clientip);
1681: } else {
1682: print $client "not_found\n";
1683: }
1684: } else {
1685: Reply($client, "refused\n", $userinput);
1686:
1687: }
1688: # ------------------------------------------------------------------- subscribe
1689: } elsif ($userinput =~ /^sub/) {
1690: if(isClient) {
1691: print $client &subscribe($userinput,$clientip);
1692: } else {
1693: Reply($client, "refused\n", $userinput);
1694:
1695: }
1696: # ------------------------------------------------------------- current version
1697: } elsif ($userinput =~ /^currentversion/) {
1698: if(isClient) {
1699: my ($cmd,$fname)=split(/:/,$userinput);
1700: print $client ¤tversion($fname)."\n";
1701: } else {
1702: Reply($client, "refused\n", $userinput);
1703:
1704: }
1705: # ------------------------------------------------------------------------- log
1706: } elsif ($userinput =~ /^log/) {
1707: if(isClient) {
1708: my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
1709: chomp($what);
1710: my $proname=propath($udom,$uname);
1711: my $now=time;
1712: {
1713: my $hfh;
1714: if ($hfh=IO::File->new(">>$proname/activity.log")) {
1715: print $hfh "$now:$clientname:$what\n";
1716: print $client "ok\n";
1717: } else {
1718: print $client "error: ".($!+0)
1719: ." IO::File->new Failed "
1720: ."while attempting log\n";
1721: }
1722: }
1723: } else {
1724: Reply($client, "refused\n", $userinput);
1725:
1726: }
1727: # ------------------------------------------------------------------------- put
1728: } elsif ($userinput =~ /^put/) {
1729: if(isClient) {
1730: my ($cmd,$udom,$uname,$namespace,$what)
1731: =split(/:/,$userinput,5);
1732: $namespace=~s/\//\_/g;
1733: $namespace=~s/\W//g;
1734: if ($namespace ne 'roles') {
1735: chomp($what);
1736: my $proname=propath($udom,$uname);
1737: my $now=time;
1738: my @pairs=split(/\&/,$what);
1739: my %hash;
1740: if (tie(%hash,'GDBM_File',
1741: "$proname/$namespace.db",
1742: &GDBM_WRCREAT(),0640)) {
1743: unless ($namespace=~/^nohist\_/) {
1744: my $hfh;
1745: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
1746: }
1747:
1748: foreach my $pair (@pairs) {
1749: my ($key,$value)=split(/=/,$pair);
1750: $hash{$key}=$value;
1751: }
1752: if (untie(%hash)) {
1753: print $client "ok\n";
1754: } else {
1755: print $client "error: ".($!+0)
1756: ." untie(GDBM) failed ".
1757: "while attempting put\n";
1758: }
1759: } else {
1760: print $client "error: ".($!)
1761: ." tie(GDBM) Failed ".
1762: "while attempting put\n";
1763: }
1764: } else {
1765: print $client "refused\n";
1766: }
1767: } else {
1768: Reply($client, "refused\n", $userinput);
1769:
1770: }
1771: # ------------------------------------------------------------------- inc
1772: } elsif ($userinput =~ /^inc:/) {
1773: if(isClient) {
1774: my ($cmd,$udom,$uname,$namespace,$what)
1775: =split(/:/,$userinput);
1776: $namespace=~s/\//\_/g;
1777: $namespace=~s/\W//g;
1778: if ($namespace ne 'roles') {
1779: chomp($what);
1780: my $proname=propath($udom,$uname);
1781: my $now=time;
1782: my @pairs=split(/\&/,$what);
1783: my %hash;
1784: if (tie(%hash,'GDBM_File',
1785: "$proname/$namespace.db",
1786: &GDBM_WRCREAT(),0640)) {
1787: unless ($namespace=~/^nohist\_/) {
1788: my $hfh;
1789: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
1790: }
1791: foreach my $pair (@pairs) {
1792: my ($key,$value)=split(/=/,$pair);
1793: # We could check that we have a number...
1794: if (! defined($value) || $value eq '') {
1795: $value = 1;
1796: }
1797: $hash{$key}+=$value;
1798: }
1799: if (untie(%hash)) {
1800: print $client "ok\n";
1801: } else {
1802: print $client "error: ".($!+0)
1803: ." untie(GDBM) failed ".
1804: "while attempting inc\n";
1805: }
1806: } else {
1807: print $client "error: ".($!)
1808: ." tie(GDBM) Failed ".
1809: "while attempting inc\n";
1810: }
1811: } else {
1812: print $client "refused\n";
1813: }
1814: } else {
1815: Reply($client, "refused\n", $userinput);
1816:
1817: }
1818: # -------------------------------------------------------------------- rolesput
1819: } elsif ($userinput =~ /^rolesput/) {
1820: if(isClient) {
1821: &Debug("rolesput");
1822: if ($wasenc==1) {
1823: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
1824: =split(/:/,$userinput);
1825: &Debug("cmd = ".$cmd." exedom= ".$exedom.
1826: "user = ".$exeuser." udom=".$udom.
1827: "what = ".$what);
1828: my $namespace='roles';
1829: chomp($what);
1830: my $proname=propath($udom,$uname);
1831: my $now=time;
1832: my @pairs=split(/\&/,$what);
1833: my %hash;
1834: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1835: {
1836: my $hfh;
1837: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
1838: print $hfh "P:$now:$exedom:$exeuser:$what\n";
1839: }
1840: }
1841:
1842: foreach my $pair (@pairs) {
1843: my ($key,$value)=split(/=/,$pair);
1844: &ManagePermissions($key, $udom, $uname,
1845: &GetAuthType( $udom,
1846: $uname));
1847: $hash{$key}=$value;
1848: }
1849: if (untie(%hash)) {
1850: print $client "ok\n";
1851: } else {
1852: print $client "error: ".($!+0)
1853: ." untie(GDBM) Failed ".
1854: "while attempting rolesput\n";
1855: }
1856: } else {
1857: print $client "error: ".($!+0)
1858: ." tie(GDBM) Failed ".
1859: "while attempting rolesput\n";
1860: }
1861: } else {
1862: print $client "refused\n";
1863: }
1864: } else {
1865: Reply($client, "refused\n", $userinput);
1866:
1867: }
1868: # -------------------------------------------------------------------- rolesdel
1869: } elsif ($userinput =~ /^rolesdel/) {
1870: if(isClient) {
1871: &Debug("rolesdel");
1872: if ($wasenc==1) {
1873: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
1874: =split(/:/,$userinput);
1875: &Debug("cmd = ".$cmd." exedom= ".$exedom.
1876: "user = ".$exeuser." udom=".$udom.
1877: "what = ".$what);
1878: my $namespace='roles';
1879: chomp($what);
1880: my $proname=propath($udom,$uname);
1881: my $now=time;
1882: my @rolekeys=split(/\&/,$what);
1883: my %hash;
1884: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1885: {
1886: my $hfh;
1887: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
1888: print $hfh "D:$now:$exedom:$exeuser:$what\n";
1889: }
1890: }
1891: foreach my $key (@rolekeys) {
1892: delete $hash{$key};
1893: }
1894: if (untie(%hash)) {
1895: print $client "ok\n";
1896: } else {
1897: print $client "error: ".($!+0)
1898: ." untie(GDBM) Failed ".
1899: "while attempting rolesdel\n";
1900: }
1901: } else {
1902: print $client "error: ".($!+0)
1903: ." tie(GDBM) Failed ".
1904: "while attempting rolesdel\n";
1905: }
1906: } else {
1907: print $client "refused\n";
1908: }
1909: } else {
1910: Reply($client, "refused\n", $userinput);
1911:
1912: }
1913: # ------------------------------------------------------------------------- get
1914: } elsif ($userinput =~ /^get/) {
1915: if(isClient) {
1916: my ($cmd,$udom,$uname,$namespace,$what)
1917: =split(/:/,$userinput);
1918: $namespace=~s/\//\_/g;
1919: $namespace=~s/\W//g;
1920: chomp($what);
1921: my @queries=split(/\&/,$what);
1922: my $proname=propath($udom,$uname);
1923: my $qresult='';
1924: my %hash;
1925: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
1926: for (my $i=0;$i<=$#queries;$i++) {
1927: $qresult.="$hash{$queries[$i]}&";
1928: }
1929: if (untie(%hash)) {
1930: $qresult=~s/\&$//;
1931: print $client "$qresult\n";
1932: } else {
1933: print $client "error: ".($!+0)
1934: ." untie(GDBM) Failed ".
1935: "while attempting get\n";
1936: }
1937: } else {
1938: if ($!+0 == 2) {
1939: print $client "error:No such file or ".
1940: "GDBM reported bad block error\n";
1941: } else {
1942: print $client "error: ".($!+0)
1943: ." tie(GDBM) Failed ".
1944: "while attempting get\n";
1945: }
1946: }
1947: } else {
1948: Reply($client, "refused\n", $userinput);
1949:
1950: }
1951: # ------------------------------------------------------------------------ eget
1952: } elsif ($userinput =~ /^eget/) {
1953: if (isClient) {
1954: my ($cmd,$udom,$uname,$namespace,$what)
1955: =split(/:/,$userinput);
1956: $namespace=~s/\//\_/g;
1957: $namespace=~s/\W//g;
1958: chomp($what);
1959: my @queries=split(/\&/,$what);
1960: my $proname=propath($udom,$uname);
1961: my $qresult='';
1962: my %hash;
1963: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
1964: for (my $i=0;$i<=$#queries;$i++) {
1965: $qresult.="$hash{$queries[$i]}&";
1966: }
1967: if (untie(%hash)) {
1968: $qresult=~s/\&$//;
1969: if ($cipher) {
1970: my $cmdlength=length($qresult);
1971: $qresult.=" ";
1972: my $encqresult='';
1973: for
1974: (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
1975: $encqresult.=
1976: unpack("H16",
1977: $cipher->encrypt(substr($qresult,$encidx,8)));
1978: }
1979: print $client "enc:$cmdlength:$encqresult\n";
1980: } else {
1981: print $client "error:no_key\n";
1982: }
1983: } else {
1984: print $client "error: ".($!+0)
1985: ." untie(GDBM) Failed ".
1986: "while attempting eget\n";
1987: }
1988: } else {
1989: print $client "error: ".($!+0)
1990: ." tie(GDBM) Failed ".
1991: "while attempting eget\n";
1992: }
1993: } else {
1994: Reply($client, "refused\n", $userinput);
1995:
1996: }
1997: # ------------------------------------------------------------------------- del
1998: } elsif ($userinput =~ /^del/) {
1999: if(isClient) {
2000: my ($cmd,$udom,$uname,$namespace,$what)
2001: =split(/:/,$userinput);
2002: $namespace=~s/\//\_/g;
2003: $namespace=~s/\W//g;
2004: chomp($what);
2005: my $proname=propath($udom,$uname);
2006: my $now=time;
2007: my @keys=split(/\&/,$what);
2008: my %hash;
2009: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2010: unless ($namespace=~/^nohist\_/) {
2011: my $hfh;
2012: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "D:$now:$what\n"; }
2013: }
2014: foreach my $key (@keys) {
2015: delete($hash{$key});
2016: }
2017: if (untie(%hash)) {
2018: print $client "ok\n";
2019: } else {
2020: print $client "error: ".($!+0)
2021: ." untie(GDBM) Failed ".
2022: "while attempting del\n";
2023: }
2024: } else {
2025: print $client "error: ".($!+0)
2026: ." tie(GDBM) Failed ".
2027: "while attempting del\n";
2028: }
2029: } else {
2030: Reply($client, "refused\n", $userinput);
2031:
2032: }
2033: # ------------------------------------------------------------------------ keys
2034: } elsif ($userinput =~ /^keys/) {
2035: if(isClient) {
2036: my ($cmd,$udom,$uname,$namespace)
2037: =split(/:/,$userinput);
2038: $namespace=~s/\//\_/g;
2039: $namespace=~s/\W//g;
2040: my $proname=propath($udom,$uname);
2041: my $qresult='';
2042: my %hash;
2043: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2044: foreach my $key (keys %hash) {
2045: $qresult.="$key&";
2046: }
2047: if (untie(%hash)) {
2048: $qresult=~s/\&$//;
2049: print $client "$qresult\n";
2050: } else {
2051: print $client "error: ".($!+0)
2052: ." untie(GDBM) Failed ".
2053: "while attempting keys\n";
2054: }
2055: } else {
2056: print $client "error: ".($!+0)
2057: ." tie(GDBM) Failed ".
2058: "while attempting keys\n";
2059: }
2060: } else {
2061: Reply($client, "refused\n", $userinput);
2062:
2063: }
2064: # ----------------------------------------------------------------- dumpcurrent
2065: } elsif ($userinput =~ /^currentdump/) {
2066: if (isClient) {
2067: my ($cmd,$udom,$uname,$namespace)
2068: =split(/:/,$userinput);
2069: $namespace=~s/\//\_/g;
2070: $namespace=~s/\W//g;
2071: my $qresult='';
2072: my $proname=propath($udom,$uname);
2073: my %hash;
2074: if (tie(%hash,'GDBM_File',
2075: "$proname/$namespace.db",
2076: &GDBM_READER(),0640)) {
2077: # Structure of %data:
2078: # $data{$symb}->{$parameter}=$value;
2079: # $data{$symb}->{'v.'.$parameter}=$version;
2080: # since $parameter will be unescaped, we do not
2081: # have to worry about silly parameter names...
2082: my %data = ();
2083: while (my ($key,$value) = each(%hash)) {
2084: my ($v,$symb,$param) = split(/:/,$key);
2085: next if ($v eq 'version' || $symb eq 'keys');
2086: next if (exists($data{$symb}) &&
2087: exists($data{$symb}->{$param}) &&
2088: $data{$symb}->{'v.'.$param} > $v);
2089: $data{$symb}->{$param}=$value;
2090: $data{$symb}->{'v.'.$param}=$v;
2091: }
2092: if (untie(%hash)) {
2093: while (my ($symb,$param_hash) = each(%data)) {
2094: while(my ($param,$value) = each (%$param_hash)){
2095: next if ($param =~ /^v\./);
2096: $qresult.=$symb.':'.$param.'='.$value.'&';
2097: }
2098: }
2099: chop($qresult);
2100: print $client "$qresult\n";
2101: } else {
2102: print $client "error: ".($!+0)
2103: ." untie(GDBM) Failed ".
2104: "while attempting currentdump\n";
2105: }
2106: } else {
2107: print $client "error: ".($!+0)
2108: ." tie(GDBM) Failed ".
2109: "while attempting currentdump\n";
2110: }
2111: } else {
2112: Reply($client, "refused\n", $userinput);
2113: }
2114: # ------------------------------------------------------------------------ dump
2115: } elsif ($userinput =~ /^dump/) {
2116: if(isClient) {
2117: my ($cmd,$udom,$uname,$namespace,$regexp)
2118: =split(/:/,$userinput);
2119: $namespace=~s/\//\_/g;
2120: $namespace=~s/\W//g;
2121: if (defined($regexp)) {
2122: $regexp=&unescape($regexp);
2123: } else {
2124: $regexp='.';
2125: }
2126: my $qresult='';
2127: my $proname=propath($udom,$uname);
2128: my %hash;
2129: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2130: while (my ($key,$value) = each(%hash)) {
2131: if ($regexp eq '.') {
2132: $qresult.=$key.'='.$value.'&';
2133: } else {
2134: my $unescapeKey = &unescape($key);
2135: if (eval('$unescapeKey=~/$regexp/')) {
2136: $qresult.="$key=$value&";
2137: }
2138: }
2139: }
2140: if (untie(%hash)) {
2141: chop($qresult);
2142: print $client "$qresult\n";
2143: } else {
2144: print $client "error: ".($!+0)
2145: ." untie(GDBM) Failed ".
2146: "while attempting dump\n";
2147: }
2148: } else {
2149: print $client "error: ".($!+0)
2150: ." tie(GDBM) Failed ".
2151: "while attempting dump\n";
2152: }
2153: } else {
2154: Reply($client, "refused\n", $userinput);
2155:
2156: }
2157: # ----------------------------------------------------------------------- store
2158: } elsif ($userinput =~ /^store/) {
2159: if(isClient) {
2160: my ($cmd,$udom,$uname,$namespace,$rid,$what)
2161: =split(/:/,$userinput);
2162: $namespace=~s/\//\_/g;
2163: $namespace=~s/\W//g;
2164: if ($namespace ne 'roles') {
2165: chomp($what);
2166: my $proname=propath($udom,$uname);
2167: my $now=time;
2168: my @pairs=split(/\&/,$what);
2169: my %hash;
2170: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2171: unless ($namespace=~/^nohist\_/) {
2172: my $hfh;
2173: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
2174: print $hfh "P:$now:$rid:$what\n";
2175: }
2176: }
2177: my @previouskeys=split(/&/,$hash{"keys:$rid"});
2178: my $key;
2179: $hash{"version:$rid"}++;
2180: my $version=$hash{"version:$rid"};
2181: my $allkeys='';
2182: foreach my $pair (@pairs) {
2183: my ($key,$value)=split(/=/,$pair);
2184: $allkeys.=$key.':';
2185: $hash{"$version:$rid:$key"}=$value;
2186: }
2187: $hash{"$version:$rid:timestamp"}=$now;
2188: $allkeys.='timestamp';
2189: $hash{"$version:keys:$rid"}=$allkeys;
2190: if (untie(%hash)) {
2191: print $client "ok\n";
2192: } else {
2193: print $client "error: ".($!+0)
2194: ." untie(GDBM) Failed ".
2195: "while attempting store\n";
2196: }
2197: } else {
2198: print $client "error: ".($!+0)
2199: ." tie(GDBM) Failed ".
2200: "while attempting store\n";
2201: }
2202: } else {
2203: print $client "refused\n";
2204: }
2205: } else {
2206: Reply($client, "refused\n", $userinput);
2207:
2208: }
2209: # --------------------------------------------------------------------- restore
2210: } elsif ($userinput =~ /^restore/) {
2211: if(isClient) {
2212: my ($cmd,$udom,$uname,$namespace,$rid)
2213: =split(/:/,$userinput);
2214: $namespace=~s/\//\_/g;
2215: $namespace=~s/\W//g;
2216: chomp($rid);
2217: my $proname=propath($udom,$uname);
2218: my $qresult='';
2219: my %hash;
2220: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2221: my $version=$hash{"version:$rid"};
2222: $qresult.="version=$version&";
2223: my $scope;
2224: for ($scope=1;$scope<=$version;$scope++) {
2225: my $vkeys=$hash{"$scope:keys:$rid"};
2226: my @keys=split(/:/,$vkeys);
2227: my $key;
2228: $qresult.="$scope:keys=$vkeys&";
2229: foreach $key (@keys) {
2230: $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
2231: }
2232: }
2233: if (untie(%hash)) {
2234: $qresult=~s/\&$//;
2235: print $client "$qresult\n";
2236: } else {
2237: print $client "error: ".($!+0)
2238: ." untie(GDBM) Failed ".
2239: "while attempting restore\n";
2240: }
2241: } else {
2242: print $client "error: ".($!+0)
2243: ." tie(GDBM) Failed ".
2244: "while attempting restore\n";
2245: }
2246: } else {
2247: Reply($client, "refused\n", $userinput);
2248:
2249: }
2250: # -------------------------------------------------------------------- chatsend
2251: } elsif ($userinput =~ /^chatsend/) {
2252: if(isClient) {
2253: my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
2254: &chatadd($cdom,$cnum,$newpost);
2255: print $client "ok\n";
2256: } else {
2257: Reply($client, "refused\n", $userinput);
2258:
2259: }
2260: # -------------------------------------------------------------------- chatretr
2261: } elsif ($userinput =~ /^chatretr/) {
2262: if(isClient) {
2263: my
2264: ($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
2265: my $reply='';
2266: foreach (&getchat($cdom,$cnum,$udom,$uname)) {
2267: $reply.=&escape($_).':';
2268: }
2269: $reply=~s/\:$//;
2270: print $client $reply."\n";
2271: } else {
2272: Reply($client, "refused\n", $userinput);
2273:
2274: }
2275: # ------------------------------------------------------------------- querysend
2276: } elsif ($userinput =~ /^querysend/) {
2277: if (isClient) {
2278: my ($cmd,$query,
2279: $arg1,$arg2,$arg3)=split(/\:/,$userinput);
2280: $query=~s/\n*$//g;
2281: print $client "".
2282: sqlreply("$clientname\&$query".
2283: "\&$arg1"."\&$arg2"."\&$arg3")."\n";
2284: } else {
2285: Reply($client, "refused\n", $userinput);
2286:
2287: }
2288: # ------------------------------------------------------------------ queryreply
2289: } elsif ($userinput =~ /^queryreply/) {
2290: if(isClient) {
2291: my ($cmd,$id,$reply)=split(/:/,$userinput);
2292: my $store;
2293: my $execdir=$perlvar{'lonDaemons'};
2294: if ($store=IO::File->new(">$execdir/tmp/$id")) {
2295: $reply=~s/\&/\n/g;
2296: print $store $reply;
2297: close $store;
2298: my $store2=IO::File->new(">$execdir/tmp/$id.end");
2299: print $store2 "done\n";
2300: close $store2;
2301: print $client "ok\n";
2302: }
2303: else {
2304: print $client "error: ".($!+0)
2305: ." IO::File->new Failed ".
2306: "while attempting queryreply\n";
2307: }
2308: } else {
2309: Reply($client, "refused\n", $userinput);
2310:
2311: }
2312: # ----------------------------------------------------------------- courseidput
2313: } elsif ($userinput =~ /^courseidput/) {
2314: if(isClient) {
2315: my ($cmd,$udom,$what)=split(/:/,$userinput);
2316: chomp($what);
2317: $udom=~s/\W//g;
2318: my $proname=
2319: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
2320: my $now=time;
2321: my @pairs=split(/\&/,$what);
2322: my %hash;
2323: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
2324: foreach my $pair (@pairs) {
2325: my ($key,$descr,$inst_code)=split(/=/,$pair);
2326: $hash{$key}=$descr.':'.$inst_code.':'.$now;
2327: }
2328: if (untie(%hash)) {
2329: print $client "ok\n";
2330: } else {
2331: print $client "error: ".($!+0)
2332: ." untie(GDBM) Failed ".
2333: "while attempting courseidput\n";
2334: }
2335: } else {
2336: print $client "error: ".($!+0)
2337: ." tie(GDBM) Failed ".
2338: "while attempting courseidput\n";
2339: }
2340: } else {
2341: Reply($client, "refused\n", $userinput);
2342:
2343: }
2344: # ---------------------------------------------------------------- courseiddump
2345: } elsif ($userinput =~ /^courseiddump/) {
2346: if(isClient) {
2347: my ($cmd,$udom,$since,$description)
2348: =split(/:/,$userinput);
2349: if (defined($description)) {
2350: $description=&unescape($description);
2351: } else {
2352: $description='.';
2353: }
2354: unless (defined($since)) { $since=0; }
2355: my $qresult='';
2356: my $proname=
2357: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
2358: my %hash;
2359: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
2360: while (my ($key,$value) = each(%hash)) {
2361: my ($descr,$lasttime,$inst_code);
2362: if ($value =~ m/^([^\:]*):([^\:]*):(\d+)$/) {
2363: ($descr,$inst_code,$lasttime)=($1,$2,$3);
2364: } else {
2365: ($descr,$lasttime) = split(/\:/,$value);
2366: }
2367: if ($lasttime<$since) { next; }
2368: if ($description eq '.') {
2369: $qresult.=$key.'='.$descr.':'.$inst_code.'&';
2370: } else {
2371: my $unescapeVal = &unescape($descr);
2372: if (eval('$unescapeVal=~/\Q$description\E/i')) {
2373: $qresult.=$key.'='.$descr.':'.$inst_code.'&';
2374: }
2375: }
2376: }
2377: if (untie(%hash)) {
2378: chop($qresult);
2379: print $client "$qresult\n";
2380: } else {
2381: print $client "error: ".($!+0)
2382: ." untie(GDBM) Failed ".
2383: "while attempting courseiddump\n";
2384: }
2385: } else {
2386: print $client "error: ".($!+0)
2387: ." tie(GDBM) Failed ".
2388: "while attempting courseiddump\n";
2389: }
2390: } else {
2391: Reply($client, "refused\n", $userinput);
2392:
2393: }
2394: # ----------------------------------------------------------------------- idput
2395: } elsif ($userinput =~ /^idput/) {
2396: if(isClient) {
2397: my ($cmd,$udom,$what)=split(/:/,$userinput);
2398: chomp($what);
2399: $udom=~s/\W//g;
2400: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
2401: my $now=time;
2402: my @pairs=split(/\&/,$what);
2403: my %hash;
2404: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
2405: {
2406: my $hfh;
2407: if ($hfh=IO::File->new(">>$proname.hist")) {
2408: print $hfh "P:$now:$what\n";
2409: }
2410: }
2411: foreach my $pair (@pairs) {
2412: my ($key,$value)=split(/=/,$pair);
2413: $hash{$key}=$value;
2414: }
2415: if (untie(%hash)) {
2416: print $client "ok\n";
2417: } else {
2418: print $client "error: ".($!+0)
2419: ." untie(GDBM) Failed ".
2420: "while attempting idput\n";
2421: }
2422: } else {
2423: print $client "error: ".($!+0)
2424: ." tie(GDBM) Failed ".
2425: "while attempting idput\n";
2426: }
2427: } else {
2428: Reply($client, "refused\n", $userinput);
2429:
2430: }
2431: # ----------------------------------------------------------------------- idget
2432: } elsif ($userinput =~ /^idget/) {
2433: if(isClient) {
2434: my ($cmd,$udom,$what)=split(/:/,$userinput);
2435: chomp($what);
2436: $udom=~s/\W//g;
2437: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
2438: my @queries=split(/\&/,$what);
2439: my $qresult='';
2440: my %hash;
2441: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
2442: for (my $i=0;$i<=$#queries;$i++) {
2443: $qresult.="$hash{$queries[$i]}&";
2444: }
2445: if (untie(%hash)) {
2446: $qresult=~s/\&$//;
2447: print $client "$qresult\n";
2448: } else {
2449: print $client "error: ".($!+0)
2450: ." untie(GDBM) Failed ".
2451: "while attempting idget\n";
2452: }
2453: } else {
2454: print $client "error: ".($!+0)
2455: ." tie(GDBM) Failed ".
2456: "while attempting idget\n";
2457: }
2458: } else {
2459: Reply($client, "refused\n", $userinput);
2460:
2461: }
2462: # ---------------------------------------------------------------------- tmpput
2463: } elsif ($userinput =~ /^tmpput/) {
2464: if(isClient) {
2465: my ($cmd,$what)=split(/:/,$userinput);
2466: my $store;
2467: $tmpsnum++;
2468: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
2469: $id=~s/\W/\_/g;
2470: $what=~s/\n//g;
2471: my $execdir=$perlvar{'lonDaemons'};
2472: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
2473: print $store $what;
2474: close $store;
2475: print $client "$id\n";
2476: }
2477: else {
2478: print $client "error: ".($!+0)
2479: ."IO::File->new Failed ".
2480: "while attempting tmpput\n";
2481: }
2482: } else {
2483: Reply($client, "refused\n", $userinput);
2484:
2485: }
2486:
2487: # ---------------------------------------------------------------------- tmpget
2488: } elsif ($userinput =~ /^tmpget/) {
2489: if(isClient) {
2490: my ($cmd,$id)=split(/:/,$userinput);
2491: chomp($id);
2492: $id=~s/\W/\_/g;
2493: my $store;
2494: my $execdir=$perlvar{'lonDaemons'};
2495: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
2496: my $reply=<$store>;
2497: print $client "$reply\n";
2498: close $store;
2499: }
2500: else {
2501: print $client "error: ".($!+0)
2502: ."IO::File->new Failed ".
2503: "while attempting tmpget\n";
2504: }
2505: } else {
2506: Reply($client, "refused\n", $userinput);
2507:
2508: }
2509: # ---------------------------------------------------------------------- tmpdel
2510: } elsif ($userinput =~ /^tmpdel/) {
2511: if(isClient) {
2512: my ($cmd,$id)=split(/:/,$userinput);
2513: chomp($id);
2514: $id=~s/\W/\_/g;
2515: my $execdir=$perlvar{'lonDaemons'};
2516: if (unlink("$execdir/tmp/$id.tmp")) {
2517: print $client "ok\n";
2518: } else {
2519: print $client "error: ".($!+0)
2520: ."Unlink tmp Failed ".
2521: "while attempting tmpdel\n";
2522: }
2523: } else {
2524: Reply($client, "refused\n", $userinput);
2525:
2526: }
2527: # ----------------------------------------- portfolio directory list (portls)
2528: } elsif ($userinput =~ /^portls/) {
2529: if(isClient) {
2530: my ($cmd,$uname,$udom)=split(/:/,$userinput);
2531: my $udir=propath($udom,$uname).'/userfiles/portfolio';
2532: my $dirLine='';
2533: my $dirContents='';
2534: if (opendir(LSDIR,$udir.'/')){
2535: while ($dirLine = readdir(LSDIR)){
2536: $dirContents = $dirContents.$dirLine.'<br />';
2537: }
2538: } else {
2539: $dirContents = "No directory found\n";
2540: }
2541: print $client $dirContents."\n";
2542: } else {
2543: Reply($client, "refused\n", $userinput);
2544: }
2545: # -------------------------------------------------------------------------- ls
2546: } elsif ($userinput =~ /^ls/) {
2547: if(isClient) {
2548: my $obs;
2549: my $rights;
2550: my ($cmd,$ulsdir)=split(/:/,$userinput);
2551: my $ulsout='';
2552: my $ulsfn;
2553: if (-e $ulsdir) {
2554: if(-d $ulsdir) {
2555: if (opendir(LSDIR,$ulsdir)) {
2556: while ($ulsfn=readdir(LSDIR)) {
2557: undef $obs, $rights;
2558: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
2559: #We do some obsolete checking here
2560: if(-e $ulsdir.'/'.$ulsfn.".meta") {
2561: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
2562: my @obsolete=<FILE>;
2563: foreach my $obsolete (@obsolete) {
2564: if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; }
2565: if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
2566: }
2567: }
2568: $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
2569: if($obs eq '1') { $ulsout.="&1"; }
2570: else { $ulsout.="&0"; }
2571: if($rights eq '1') { $ulsout.="&1:"; }
2572: else { $ulsout.="&0:"; }
2573: }
2574: closedir(LSDIR);
2575: }
2576: } else {
2577: my @ulsstats=stat($ulsdir);
2578: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
2579: }
2580: } else {
2581: $ulsout='no_such_dir';
2582: }
2583: if ($ulsout eq '') { $ulsout='empty'; }
2584: print $client "$ulsout\n";
2585: } else {
2586: Reply($client, "refused\n", $userinput);
2587:
2588: }
2589: # ----------------------------------------------------------------- setannounce
2590: } elsif ($userinput =~ /^setannounce/) {
2591: if (isClient) {
2592: my ($cmd,$announcement)=split(/:/,$userinput);
2593: chomp($announcement);
2594: $announcement=&unescape($announcement);
2595: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
2596: '/announcement.txt')) {
2597: print $store $announcement;
2598: close $store;
2599: print $client "ok\n";
2600: } else {
2601: print $client "error: ".($!+0)."\n";
2602: }
2603: } else {
2604: Reply($client, "refused\n", $userinput);
2605:
2606: }
2607: # ------------------------------------------------------------------ Hanging up
2608: } elsif (($userinput =~ /^exit/) ||
2609: ($userinput =~ /^init/)) { # no restrictions.
2610: &logthis(
2611: "Client $clientip ($clientname) hanging up: $userinput");
2612: print $client "bye\n";
2613: $client->shutdown(2); # shutdown the socket forcibly.
2614: $client->close();
2615: return 0;
2616:
2617: # ---------------------------------- set current host/domain
2618: } elsif ($userinput =~ /^sethost:/) {
2619: if (isClient) {
2620: print $client &sethost($userinput)."\n";
2621: } else {
2622: print $client "refused\n";
2623: }
2624: #---------------------------------- request file (?) version.
2625: } elsif ($userinput =~/^version:/) {
2626: if (isClient) {
2627: print $client &version($userinput)."\n";
2628: } else {
2629: print $client "refused\n";
2630: }
2631: #------------------------------- is auto-enrollment enabled?
2632: } elsif ($userinput =~/^autorun:/) {
2633: if (isClient) {
2634: my ($cmd,$cdom) = split(/:/,$userinput);
2635: my $outcome = &localenroll::run($cdom);
2636: print $client "$outcome\n";
2637: } else {
2638: print $client "0\n";
2639: }
2640: #------------------------------- get official sections (for auto-enrollment).
2641: } elsif ($userinput =~/^autogetsections:/) {
2642: if (isClient) {
2643: my ($cmd,$coursecode,$cdom)=split(/:/,$userinput);
2644: my @secs = &localenroll::get_sections($coursecode,$cdom);
2645: my $seclist = &escape(join(':',@secs));
2646: print $client "$seclist\n";
2647: } else {
2648: print $client "refused\n";
2649: }
2650: #----------------------- validate owner of new course section (for auto-enrollment).
2651: } elsif ($userinput =~/^autonewcourse:/) {
2652: if (isClient) {
2653: my ($cmd,$inst_course_id,$owner,$cdom)=split(/:/,$userinput);
2654: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
2655: print $client "$outcome\n";
2656: } else {
2657: print $client "refused\n";
2658: }
2659: #-------------- validate course section in schedule of classes (for auto-enrollment).
2660: } elsif ($userinput =~/^autovalidatecourse:/) {
2661: if (isClient) {
2662: my ($cmd,$inst_course_id,$cdom)=split(/:/,$userinput);
2663: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
2664: print $client "$outcome\n";
2665: } else {
2666: print $client "refused\n";
2667: }
2668: #--------------------------- create password for new user (for auto-enrollment).
2669: } elsif ($userinput =~/^autocreatepassword:/) {
2670: if (isClient) {
2671: my ($cmd,$authparam,$cdom)=split(/:/,$userinput);
2672: my ($create_passwd,$authchk);
2673: ($authparam,$create_passwd,$authchk) = &localenroll::create_password($authparam,$cdom);
2674: print $client &escape($authparam.':'.$create_passwd.':'.$authchk)."\n";
2675: } else {
2676: print $client "refused\n";
2677: }
2678: #--------------------------- read and remove temporary files (for auto-enrollment).
2679: } elsif ($userinput =~/^autoretrieve:/) {
2680: if (isClient) {
2681: my ($cmd,$filename) = split(/:/,$userinput);
2682: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
2683: if ( (-e $source) && ($filename ne '') ) {
2684: my $reply = '';
2685: if (open(my $fh,$source)) {
2686: while (<$fh>) {
2687: chomp($_);
2688: $_ =~ s/^\s+//g;
2689: $_ =~ s/\s+$//g;
2690: $reply .= $_;
2691: }
2692: close($fh);
2693: print $client &escape($reply)."\n";
2694: # unlink($source);
2695: } else {
2696: print $client "error\n";
2697: }
2698: } else {
2699: print $client "error\n";
2700: }
2701: } else {
2702: print $client "refused\n";
2703: }
2704: #--------------------- read and retrieve institutional code format (for support form).
2705: } elsif ($userinput =~/^autoinstcodeformat:/) {
2706: if (isClient) {
2707: my $reply;
2708: my($cmd,$cdom,$course) = split(/:/,$userinput);
2709: my @pairs = split/\&/,$course;
2710: my %instcodes = ();
2711: my %codes = ();
2712: my @codetitles = ();
2713: my %cat_titles = ();
2714: my %cat_order = ();
2715: foreach (@pairs) {
2716: my ($key,$value) = split/=/,$_;
2717: $instcodes{&unescape($key)} = &unescape($value);
2718: }
2719: my $formatreply = &localenroll::instcode_format($cdom,\%instcodes,\%codes,\@codetitles,\%cat_titles,\%cat_order);
2720: if ($formatreply eq 'ok') {
2721: my $codes_str = &hash2str(%codes);
2722: my $codetitles_str = &array2str(@codetitles);
2723: my $cat_titles_str = &hash2str(%cat_titles);
2724: my $cat_order_str = &hash2str(%cat_order);
2725: print $client $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'.$cat_order_str."\n";
2726: }
2727: } else {
2728: print $client "refused\n";
2729: }
2730: # ------------------------------------------------------------- unknown command
2731:
2732: } else {
2733: # unknown command
2734: print $client "unknown_cmd\n";
2735: }
2736: # -------------------------------------------------------------------- complete
2737: Debug("process_request - returning 1");
2738: return 1;
2739: }
2740: #
2741: # Decipher encoded traffic
2742: # Parameters:
2743: # input - Encoded data.
2744: # Returns:
2745: # Decoded data or undef if encryption key was not yet negotiated.
2746: # Implicit input:
2747: # cipher - This global holds the negotiated encryption key.
2748: #
2749: sub decipher {
2750: my ($input) = @_;
2751: my $output = '';
2752:
2753:
2754: if($cipher) {
2755: my($enc, $enclength, $encinput) = split(/:/, $input);
2756: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
2757: $output .=
2758: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
2759: }
2760: return substr($output, 0, $enclength);
2761: } else {
2762: return undef;
2763: }
2764: }
2765:
2766: #
2767: # Register a command processor. This function is invoked to register a sub
2768: # to process a request. Once registered, the ProcessRequest sub can automatically
2769: # dispatch requests to an appropriate sub, and do the top level validity checking
2770: # as well:
2771: # - Is the keyword recognized.
2772: # - Is the proper client type attempting the request.
2773: # - Is the request encrypted if it has to be.
2774: # Parameters:
2775: # $request_name - Name of the request being registered.
2776: # This is the command request that will match
2777: # against the hash keywords to lookup the information
2778: # associated with the dispatch information.
2779: # $procedure - Reference to a sub to call to process the request.
2780: # All subs get called as follows:
2781: # Procedure($cmd, $tail, $replyfd, $key)
2782: # $cmd - the actual keyword that invoked us.
2783: # $tail - the tail of the request that invoked us.
2784: # $replyfd- File descriptor connected to the client
2785: # $must_encode - True if the request must be encoded to be good.
2786: # $client_ok - True if it's ok for a client to request this.
2787: # $manager_ok - True if it's ok for a manager to request this.
2788: # Side effects:
2789: # - On success, the Dispatcher hash has an entry added for the key $RequestName
2790: # - On failure, the program will die as it's a bad internal bug to try to
2791: # register a duplicate command handler.
2792: #
2793: sub register_handler {
2794: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
2795:
2796: # Don't allow duplication#
2797:
2798: if (defined $Dispatcher{$request_name}) {
2799: die "Attempting to define a duplicate request handler for $request_name\n";
2800: }
2801: # Build the client type mask:
2802:
2803: my $client_type_mask = 0;
2804: if($client_ok) {
2805: $client_type_mask |= $CLIENT_OK;
2806: }
2807: if($manager_ok) {
2808: $client_type_mask |= $MANAGER_OK;
2809: }
2810:
2811: # Enter the hash:
2812:
2813: my @entry = ($procedure, $must_encode, $client_type_mask);
2814:
2815: $Dispatcher{$request_name} = \@entry;
2816:
2817:
2818: }
2819:
2820:
2821: #------------------------------------------------------------------
2822:
2823:
2824:
2825:
2826: #
2827: # Convert an error return code from lcpasswd to a string value.
2828: #
2829: sub lcpasswdstrerror {
2830: my $ErrorCode = shift;
2831: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
2832: return "lcpasswd Unrecognized error return value ".$ErrorCode;
2833: } else {
2834: return $passwderrors[$ErrorCode];
2835: }
2836: }
2837:
2838: #
2839: # Convert an error return code from lcuseradd to a string value:
2840: #
2841: sub lcuseraddstrerror {
2842: my $ErrorCode = shift;
2843: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
2844: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
2845: } else {
2846: return $adderrors[$ErrorCode];
2847: }
2848: }
2849:
2850: # grabs exception and records it to log before exiting
2851: sub catchexception {
2852: my ($error)=@_;
2853: $SIG{'QUIT'}='DEFAULT';
2854: $SIG{__DIE__}='DEFAULT';
2855: &status("Catching exception");
2856: &logthis("<font color='red'>CRITICAL: "
2857: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
2858: ."a crash with this error msg->[$error]</font>");
2859: &logthis('Famous last words: '.$status.' - '.$lastlog);
2860: if ($client) { print $client "error: $error\n"; }
2861: $server->close();
2862: die($error);
2863: }
2864:
2865: sub timeout {
2866: &status("Handling Timeout");
2867: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
2868: &catchexception('Timeout');
2869: }
2870: # -------------------------------- Set signal handlers to record abnormal exits
2871:
2872: $SIG{'QUIT'}=\&catchexception;
2873: $SIG{__DIE__}=\&catchexception;
2874:
2875: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
2876: &status("Read loncapa.conf and loncapa_apache.conf");
2877: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
2878: %perlvar=%{$perlvarref};
2879: undef $perlvarref;
2880:
2881: # ----------------------------- Make sure this process is running from user=www
2882: my $wwwid=getpwnam('www');
2883: if ($wwwid!=$<) {
2884: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
2885: my $subj="LON: $currenthostid User ID mismatch";
2886: system("echo 'User ID mismatch. lond must be run as user www.' |\
2887: mailto $emailto -s '$subj' > /dev/null");
2888: exit 1;
2889: }
2890:
2891: # --------------------------------------------- Check if other instance running
2892:
2893: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
2894:
2895: if (-e $pidfile) {
2896: my $lfh=IO::File->new("$pidfile");
2897: my $pide=<$lfh>;
2898: chomp($pide);
2899: if (kill 0 => $pide) { die "already running"; }
2900: }
2901:
2902: # ------------------------------------------------------------- Read hosts file
2903:
2904:
2905:
2906: # establish SERVER socket, bind and listen.
2907: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
2908: Type => SOCK_STREAM,
2909: Proto => 'tcp',
2910: Reuse => 1,
2911: Listen => 10 )
2912: or die "making socket: $@\n";
2913:
2914: # --------------------------------------------------------- Do global variables
2915:
2916: # global variables
2917:
2918: my %children = (); # keys are current child process IDs
2919:
2920: sub REAPER { # takes care of dead children
2921: $SIG{CHLD} = \&REAPER;
2922: &status("Handling child death");
2923: my $pid;
2924: do {
2925: $pid = waitpid(-1,&WNOHANG());
2926: if (defined($children{$pid})) {
2927: &logthis("Child $pid died");
2928: delete($children{$pid});
2929: } elsif ($pid > 0) {
2930: &logthis("Unknown Child $pid died");
2931: }
2932: } while ( $pid > 0 );
2933: foreach my $child (keys(%children)) {
2934: $pid = waitpid($child,&WNOHANG());
2935: if ($pid > 0) {
2936: &logthis("Child $child - $pid looks like we missed it's death");
2937: delete($children{$pid});
2938: }
2939: }
2940: &status("Finished Handling child death");
2941: }
2942:
2943: sub HUNTSMAN { # signal handler for SIGINT
2944: &status("Killing children (INT)");
2945: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
2946: kill 'INT' => keys %children;
2947: &logthis("Free socket: ".shutdown($server,2)); # free up socket
2948: my $execdir=$perlvar{'lonDaemons'};
2949: unlink("$execdir/logs/lond.pid");
2950: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
2951: &status("Done killing children");
2952: exit; # clean up with dignity
2953: }
2954:
2955: sub HUPSMAN { # signal handler for SIGHUP
2956: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
2957: &status("Killing children for restart (HUP)");
2958: kill 'INT' => keys %children;
2959: &logthis("Free socket: ".shutdown($server,2)); # free up socket
2960: &logthis("<font color='red'>CRITICAL: Restarting</font>");
2961: my $execdir=$perlvar{'lonDaemons'};
2962: unlink("$execdir/logs/lond.pid");
2963: &status("Restarting self (HUP)");
2964: exec("$execdir/lond"); # here we go again
2965: }
2966:
2967: #
2968: # Kill off hashes that describe the host table prior to re-reading it.
2969: # Hashes affected are:
2970: # %hostid, %hostdom %hostip %hostdns.
2971: #
2972: sub KillHostHashes {
2973: foreach my $key (keys %hostid) {
2974: delete $hostid{$key};
2975: }
2976: foreach my $key (keys %hostdom) {
2977: delete $hostdom{$key};
2978: }
2979: foreach my $key (keys %hostip) {
2980: delete $hostip{$key};
2981: }
2982: foreach my $key (keys %hostdns) {
2983: delete $hostdns{$key};
2984: }
2985: }
2986: #
2987: # Read in the host table from file and distribute it into the various hashes:
2988: #
2989: # - %hostid - Indexed by IP, the loncapa hostname.
2990: # - %hostdom - Indexed by loncapa hostname, the domain.
2991: # - %hostip - Indexed by hostid, the Ip address of the host.
2992: sub ReadHostTable {
2993:
2994: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
2995: my $myloncapaname = $perlvar{'lonHostID'};
2996: Debug("My loncapa name is : $myloncapaname");
2997: while (my $configline=<CONFIG>) {
2998: if (!($configline =~ /^\s*\#/)) {
2999: my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
3000: chomp($ip); $ip=~s/\D+$//;
3001: $hostid{$ip}=$id; # LonCAPA name of host by IP.
3002: $hostdom{$id}=$domain; # LonCAPA domain name of host.
3003: $hostip{$id}=$ip; # IP address of host.
3004: $hostdns{$name} = $id; # LonCAPA name of host by DNS.
3005:
3006: if ($id eq $perlvar{'lonHostID'}) {
3007: Debug("Found me in the host table: $name");
3008: $thisserver=$name;
3009: }
3010: }
3011: }
3012: close(CONFIG);
3013: }
3014: #
3015: # Reload the Apache daemon's state.
3016: # This is done by invoking /home/httpd/perl/apachereload
3017: # a setuid perl script that can be root for us to do this job.
3018: #
3019: sub ReloadApache {
3020: my $execdir = $perlvar{'lonDaemons'};
3021: my $script = $execdir."/apachereload";
3022: system($script);
3023: }
3024:
3025: #
3026: # Called in response to a USR2 signal.
3027: # - Reread hosts.tab
3028: # - All children connected to hosts that were removed from hosts.tab
3029: # are killed via SIGINT
3030: # - All children connected to previously existing hosts are sent SIGUSR1
3031: # - Our internal hosts hash is updated to reflect the new contents of
3032: # hosts.tab causing connections from hosts added to hosts.tab to
3033: # now be honored.
3034: #
3035: sub UpdateHosts {
3036: &status("Reload hosts.tab");
3037: logthis('<font color="blue"> Updating connections </font>');
3038: #
3039: # The %children hash has the set of IP's we currently have children
3040: # on. These need to be matched against records in the hosts.tab
3041: # Any ip's no longer in the table get killed off they correspond to
3042: # either dropped or changed hosts. Note that the re-read of the table
3043: # will take care of new and changed hosts as connections come into being.
3044:
3045:
3046: KillHostHashes;
3047: ReadHostTable;
3048:
3049: foreach my $child (keys %children) {
3050: my $childip = $children{$child};
3051: if(!$hostid{$childip}) {
3052: logthis('<font color="blue"> UpdateHosts killing child '
3053: ." $child for ip $childip </font>");
3054: kill('INT', $child);
3055: } else {
3056: logthis('<font color="green"> keeping child for ip '
3057: ." $childip (pid=$child) </font>");
3058: }
3059: }
3060: ReloadApache;
3061: &status("Finished reloading hosts.tab");
3062: }
3063:
3064:
3065: sub checkchildren {
3066: &status("Checking on the children (sending signals)");
3067: &initnewstatus();
3068: &logstatus();
3069: &logthis('Going to check on the children');
3070: my $docdir=$perlvar{'lonDocRoot'};
3071: foreach (sort keys %children) {
3072: sleep 1;
3073: unless (kill 'USR1' => $_) {
3074: &logthis ('Child '.$_.' is dead');
3075: &logstatus($$.' is dead');
3076: }
3077: }
3078: sleep 5;
3079: $SIG{ALRM} = sub { Debug("timeout");
3080: die "timeout"; };
3081: $SIG{__DIE__} = 'DEFAULT';
3082: &status("Checking on the children (waiting for reports)");
3083: foreach (sort keys %children) {
3084: unless (-e "$docdir/lon-status/londchld/$_.txt") {
3085: eval {
3086: alarm(300);
3087: &logthis('Child '.$_.' did not respond');
3088: kill 9 => $_;
3089: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
3090: #$subj="LON: $currenthostid killed lond process $_";
3091: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
3092: #$execdir=$perlvar{'lonDaemons'};
3093: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
3094: alarm(0);
3095: }
3096: }
3097: }
3098: $SIG{ALRM} = 'DEFAULT';
3099: $SIG{__DIE__} = \&catchexception;
3100: &status("Finished checking children");
3101: }
3102:
3103: # --------------------------------------------------------------------- Logging
3104:
3105: sub logthis {
3106: my $message=shift;
3107: my $execdir=$perlvar{'lonDaemons'};
3108: my $fh=IO::File->new(">>$execdir/logs/lond.log");
3109: my $now=time;
3110: my $local=localtime($now);
3111: $lastlog=$local.': '.$message;
3112: print $fh "$local ($$): $message\n";
3113: }
3114:
3115: # ------------------------- Conditional log if $DEBUG true.
3116: sub Debug {
3117: my $message = shift;
3118: if($DEBUG) {
3119: &logthis($message);
3120: }
3121: }
3122:
3123: #
3124: # Sub to do replies to client.. this gives a hook for some
3125: # debug tracing too:
3126: # Parameters:
3127: # fd - File open on client.
3128: # reply - Text to send to client.
3129: # request - Original request from client.
3130: #
3131: sub Reply {
3132: alarm(120);
3133: my $fd = shift;
3134: my $reply = shift;
3135: my $request = shift;
3136:
3137: my ($fd, $reply, $request) = @_;
3138: print $fd $reply;
3139: Debug("Request was $request Reply was $reply");
3140:
3141: $Transactions++;
3142: alarm(0);
3143:
3144:
3145: }
3146:
3147:
3148: #
3149: # Sub to report a failure.
3150: # This function:
3151: # - Increments the failure statistic counters.
3152: # - Invokes Reply to send the error message to the client.
3153: # Parameters:
3154: # fd - File descriptor open on the client
3155: # reply - Reply text to emit.
3156: # request - The original request message (used by Reply
3157: # to debug if that's enabled.
3158: # Implicit outputs:
3159: # $Failures- The number of failures is incremented.
3160: # Reply (invoked here) sends a message to the
3161: # client:
3162: #
3163: sub Failure {
3164: my $fd = shift;
3165: my $reply = shift;
3166: my $request = shift;
3167:
3168: $Failures++;
3169: Reply($fd, $reply, $request); # That's simple eh?
3170: }
3171: # ------------------------------------------------------------------ Log status
3172:
3173: sub logstatus {
3174: &status("Doing logging");
3175: my $docdir=$perlvar{'lonDocRoot'};
3176: {
3177: my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
3178: print $fh $$."\t".$clientname."\t".$currenthostid."\t"
3179: .$status."\t".$lastlog."\t $keymode\n";
3180: $fh->close();
3181: }
3182: &status("Finished londstatus.txt");
3183: {
3184: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
3185: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
3186: $fh->close();
3187: }
3188: &status("Finished logging");
3189: }
3190:
3191: sub initnewstatus {
3192: my $docdir=$perlvar{'lonDocRoot'};
3193: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
3194: my $now=time;
3195: my $local=localtime($now);
3196: print $fh "LOND status $local - parent $$\n\n";
3197: opendir(DIR,"$docdir/lon-status/londchld");
3198: while (my $filename=readdir(DIR)) {
3199: unlink("$docdir/lon-status/londchld/$filename");
3200: }
3201: closedir(DIR);
3202: }
3203:
3204: # -------------------------------------------------------------- Status setting
3205:
3206: sub status {
3207: my $what=shift;
3208: my $now=time;
3209: my $local=localtime($now);
3210: $status=$local.': '.$what;
3211: $0='lond: '.$what.' '.$local;
3212: }
3213:
3214: # -------------------------------------------------------- Escape Special Chars
3215:
3216: sub escape {
3217: my $str=shift;
3218: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
3219: return $str;
3220: }
3221:
3222: # ----------------------------------------------------- Un-Escape Special Chars
3223:
3224: sub unescape {
3225: my $str=shift;
3226: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
3227: return $str;
3228: }
3229:
3230: # ----------------------------------------------------------- Send USR1 to lonc
3231:
3232: sub reconlonc {
3233: my $peerfile=shift;
3234: &logthis("Trying to reconnect for $peerfile");
3235: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
3236: if (my $fh=IO::File->new("$loncfile")) {
3237: my $loncpid=<$fh>;
3238: chomp($loncpid);
3239: if (kill 0 => $loncpid) {
3240: &logthis("lonc at pid $loncpid responding, sending USR1");
3241: kill USR1 => $loncpid;
3242: } else {
3243: &logthis(
3244: "<font color='red'>CRITICAL: "
3245: ."lonc at pid $loncpid not responding, giving up</font>");
3246: }
3247: } else {
3248: &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
3249: }
3250: }
3251:
3252: # -------------------------------------------------- Non-critical communication
3253:
3254: sub subreply {
3255: my ($cmd,$server)=@_;
3256: my $peerfile="$perlvar{'lonSockDir'}/$server";
3257: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
3258: Type => SOCK_STREAM,
3259: Timeout => 10)
3260: or return "con_lost";
3261: print $sclient "$cmd\n";
3262: my $answer=<$sclient>;
3263: chomp($answer);
3264: if (!$answer) { $answer="con_lost"; }
3265: return $answer;
3266: }
3267:
3268: sub reply {
3269: my ($cmd,$server)=@_;
3270: my $answer;
3271: if ($server ne $currenthostid) {
3272: $answer=subreply($cmd,$server);
3273: if ($answer eq 'con_lost') {
3274: $answer=subreply("ping",$server);
3275: if ($answer ne $server) {
3276: &logthis("sub reply: answer != server answer is $answer, server is $server");
3277: &reconlonc("$perlvar{'lonSockDir'}/$server");
3278: }
3279: $answer=subreply($cmd,$server);
3280: }
3281: } else {
3282: $answer='self_reply';
3283: }
3284: return $answer;
3285: }
3286:
3287: # -------------------------------------------------------------- Talk to lonsql
3288:
3289: sub sqlreply {
3290: my ($cmd)=@_;
3291: my $answer=subsqlreply($cmd);
3292: if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
3293: return $answer;
3294: }
3295:
3296: sub subsqlreply {
3297: my ($cmd)=@_;
3298: my $unixsock="mysqlsock";
3299: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
3300: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
3301: Type => SOCK_STREAM,
3302: Timeout => 10)
3303: or return "con_lost";
3304: print $sclient "$cmd\n";
3305: my $answer=<$sclient>;
3306: chomp($answer);
3307: if (!$answer) { $answer="con_lost"; }
3308: return $answer;
3309: }
3310:
3311: # -------------------------------------------- Return path to profile directory
3312:
3313: sub propath {
3314: my ($udom,$uname)=@_;
3315: $udom=~s/\W//g;
3316: $uname=~s/\W//g;
3317: my $subdir=$uname.'__';
3318: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3319: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
3320: return $proname;
3321: }
3322:
3323: # --------------------------------------- Is this the home server of an author?
3324:
3325: sub ishome {
3326: my $author=shift;
3327: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3328: my ($udom,$uname)=split(/\//,$author);
3329: my $proname=propath($udom,$uname);
3330: if (-e $proname) {
3331: return 'owner';
3332: } else {
3333: return 'not_owner';
3334: }
3335: }
3336:
3337: # ======================================================= Continue main program
3338: # ---------------------------------------------------- Fork once and dissociate
3339:
3340: my $fpid=fork;
3341: exit if $fpid;
3342: die "Couldn't fork: $!" unless defined ($fpid);
3343:
3344: POSIX::setsid() or die "Can't start new session: $!";
3345:
3346: # ------------------------------------------------------- Write our PID on disk
3347:
3348: my $execdir=$perlvar{'lonDaemons'};
3349: open (PIDSAVE,">$execdir/logs/lond.pid");
3350: print PIDSAVE "$$\n";
3351: close(PIDSAVE);
3352: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
3353: &status('Starting');
3354:
3355:
3356:
3357: # ----------------------------------------------------- Install signal handlers
3358:
3359:
3360: $SIG{CHLD} = \&REAPER;
3361: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
3362: $SIG{HUP} = \&HUPSMAN;
3363: $SIG{USR1} = \&checkchildren;
3364: $SIG{USR2} = \&UpdateHosts;
3365:
3366: # Read the host hashes:
3367:
3368: ReadHostTable;
3369:
3370: # --------------------------------------------------------------
3371: # Accept connections. When a connection comes in, it is validated
3372: # and if good, a child process is created to process transactions
3373: # along the connection.
3374:
3375: while (1) {
3376: &status('Starting accept');
3377: $client = $server->accept() or next;
3378: &status('Accepted '.$client.' off to spawn');
3379: make_new_child($client);
3380: &status('Finished spawning');
3381: }
3382:
3383: sub make_new_child {
3384: my $pid;
3385: # my $cipher; # Now global
3386: my $sigset;
3387:
3388: $client = shift;
3389: &status('Starting new child '.$client);
3390: &logthis('<font color="green"> Attempting to start child ('.$client.
3391: ")</font>");
3392: # block signal for fork
3393: $sigset = POSIX::SigSet->new(SIGINT);
3394: sigprocmask(SIG_BLOCK, $sigset)
3395: or die "Can't block SIGINT for fork: $!\n";
3396:
3397: die "fork: $!" unless defined ($pid = fork);
3398:
3399: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
3400: # connection liveness.
3401:
3402: #
3403: # Figure out who we're talking to so we can record the peer in
3404: # the pid hash.
3405: #
3406: my $caller = getpeername($client);
3407: my ($port,$iaddr);
3408: if (defined($caller) && length($caller) > 0) {
3409: ($port,$iaddr)=unpack_sockaddr_in($caller);
3410: } else {
3411: &logthis("Unable to determine who caller was, getpeername returned nothing");
3412: }
3413: if (defined($iaddr)) {
3414: $clientip = inet_ntoa($iaddr);
3415: Debug("Connected with $clientip");
3416: $clientdns = gethostbyaddr($iaddr, AF_INET);
3417: Debug("Connected with $clientdns by name");
3418: } else {
3419: &logthis("Unable to determine clientip");
3420: $clientip='Unavailable';
3421: }
3422:
3423: if ($pid) {
3424: # Parent records the child's birth and returns.
3425: sigprocmask(SIG_UNBLOCK, $sigset)
3426: or die "Can't unblock SIGINT for fork: $!\n";
3427: $children{$pid} = $clientip;
3428: &status('Started child '.$pid);
3429: return;
3430: } else {
3431: # Child can *not* return from this subroutine.
3432: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
3433: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
3434: #don't get intercepted
3435: $SIG{USR1}= \&logstatus;
3436: $SIG{ALRM}= \&timeout;
3437: $lastlog='Forked ';
3438: $status='Forked';
3439:
3440: # unblock signals
3441: sigprocmask(SIG_UNBLOCK, $sigset)
3442: or die "Can't unblock SIGINT for fork: $!\n";
3443:
3444: # my $tmpsnum=0; # Now global
3445: #---------------------------------------------------- kerberos 5 initialization
3446: &Authen::Krb5::init_context();
3447: &Authen::Krb5::init_ets();
3448:
3449: &status('Accepted connection');
3450: # =============================================================================
3451: # do something with the connection
3452: # -----------------------------------------------------------------------------
3453: # see if we know client and 'check' for spoof IP by ineffective challenge
3454:
3455: ReadManagerTable; # May also be a manager!!
3456:
3457: my $clientrec=($hostid{$clientip} ne undef);
3458: my $ismanager=($managers{$clientip} ne undef);
3459: $clientname = "[unknonwn]";
3460: if($clientrec) { # Establish client type.
3461: $ConnectionType = "client";
3462: $clientname = $hostid{$clientip};
3463: if($ismanager) {
3464: $ConnectionType = "both";
3465: }
3466: } else {
3467: $ConnectionType = "manager";
3468: $clientname = $managers{$clientip};
3469: }
3470: my $clientok;
3471:
3472: if ($clientrec || $ismanager) {
3473: &status("Waiting for init from $clientip $clientname");
3474: &logthis('<font color="yellow">INFO: Connection, '.
3475: $clientip.
3476: " ($clientname) connection type = $ConnectionType </font>" );
3477: &status("Connecting $clientip ($clientname))");
3478: my $remotereq=<$client>;
3479: chomp($remotereq);
3480: Debug("Got init: $remotereq");
3481: my $inikeyword = split(/:/, $remotereq);
3482: if ($remotereq =~ /^init/) {
3483: &sethost("sethost:$perlvar{'lonHostID'}");
3484: #
3485: # If the remote is attempting a local init... give that a try:
3486: #
3487: my ($i, $inittype) = split(/:/, $remotereq);
3488:
3489: # If the connection type is ssl, but I didn't get my
3490: # certificate files yet, then I'll drop back to
3491: # insecure (if allowed).
3492:
3493: if($inittype eq "ssl") {
3494: my ($ca, $cert) = lonssl::CertificateFile;
3495: my $kfile = lonssl::KeyFile;
3496: if((!$ca) ||
3497: (!$cert) ||
3498: (!$kfile)) {
3499: $inittype = ""; # This forces insecure attempt.
3500: &logthis("<font color=\"blue\"> Certificates not "
3501: ."installed -- trying insecure auth</font>");
3502: }
3503: else { # SSL certificates are in place so
3504: } # Leave the inittype alone.
3505: }
3506:
3507: if($inittype eq "local") {
3508: my $key = LocalConnection($client, $remotereq);
3509: if($key) {
3510: Debug("Got local key $key");
3511: $clientok = 1;
3512: my $cipherkey = pack("H32", $key);
3513: $cipher = new IDEA($cipherkey);
3514: print $client "ok:local\n";
3515: &logthis('<font color="green"'
3516: . "Successful local authentication </font>");
3517: $keymode = "local"
3518: } else {
3519: Debug("Failed to get local key");
3520: $clientok = 0;
3521: shutdown($client, 3);
3522: close $client;
3523: }
3524: } elsif ($inittype eq "ssl") {
3525: my $key = SSLConnection($client);
3526: if ($key) {
3527: $clientok = 1;
3528: my $cipherkey = pack("H32", $key);
3529: $cipher = new IDEA($cipherkey);
3530: &logthis('<font color="green">'
3531: ."Successfull ssl authentication with $clientname </font>");
3532: $keymode = "ssl";
3533:
3534: } else {
3535: $clientok = 0;
3536: close $client;
3537: }
3538:
3539: } else {
3540: my $ok = InsecureConnection($client);
3541: if($ok) {
3542: $clientok = 1;
3543: &logthis('<font color="green">'
3544: ."Successful insecure authentication with $clientname </font>");
3545: print $client "ok\n";
3546: $keymode = "insecure";
3547: } else {
3548: &logthis('<font color="yellow">'
3549: ."Attempted insecure connection disallowed </font>");
3550: close $client;
3551: $clientok = 0;
3552:
3553: }
3554: }
3555: } else {
3556: &logthis(
3557: "<font color='blue'>WARNING: "
3558: ."$clientip failed to initialize: >$remotereq< </font>");
3559: &status('No init '.$clientip);
3560: }
3561:
3562: } else {
3563: &logthis(
3564: "<font color='blue'>WARNING: Unknown client $clientip</font>");
3565: &status('Hung up on '.$clientip);
3566: }
3567:
3568: if ($clientok) {
3569: # ---------------- New known client connecting, could mean machine online again
3570:
3571: foreach my $id (keys(%hostip)) {
3572: if ($hostip{$id} ne $clientip ||
3573: $hostip{$currenthostid} eq $clientip) {
3574: # no need to try to do recon's to myself
3575: next;
3576: }
3577: &reconlonc("$perlvar{'lonSockDir'}/$id");
3578: }
3579: &logthis("<font color='green'>Established connection: $clientname</font>");
3580: &status('Will listen to '.$clientname);
3581: # ------------------------------------------------------------ Process requests
3582: my $keep_going = 1;
3583: my $user_input;
3584: while(($user_input = get_request) && $keep_going) {
3585: alarm(120);
3586: Debug("Main: Got $user_input\n");
3587: $keep_going = &process_request($user_input);
3588: alarm(0);
3589: &status('Listening to '.$clientname." ($keymode)");
3590: }
3591:
3592: # --------------------------------------------- client unknown or fishy, refuse
3593: } else {
3594: print $client "refused\n";
3595: $client->close();
3596: &logthis("<font color='blue'>WARNING: "
3597: ."Rejected client $clientip, closing connection</font>");
3598: }
3599: }
3600:
3601: # =============================================================================
3602:
3603: &logthis("<font color='red'>CRITICAL: "
3604: ."Disconnect from $clientip ($clientname)</font>");
3605:
3606:
3607: # this exit is VERY important, otherwise the child will become
3608: # a producer of more and more children, forking yourself into
3609: # process death.
3610: exit;
3611:
3612: }
3613:
3614:
3615: #
3616: # Checks to see if the input roleput request was to set
3617: # an author role. If so, invokes the lchtmldir script to set
3618: # up a correct public_html
3619: # Parameters:
3620: # request - The request sent to the rolesput subchunk.
3621: # We're looking for /domain/_au
3622: # domain - The domain in which the user is having roles doctored.
3623: # user - Name of the user for which the role is being put.
3624: # authtype - The authentication type associated with the user.
3625: #
3626: sub ManagePermissions
3627: {
3628:
3629: my ($request, $domain, $user, $authtype) = @_;
3630:
3631: # See if the request is of the form /$domain/_au
3632: if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
3633: my $execdir = $perlvar{'lonDaemons'};
3634: my $userhome= "/home/$user" ;
3635: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
3636: system("$execdir/lchtmldir $userhome $user $authtype");
3637: }
3638: }
3639: #
3640: # GetAuthType - Determines the authorization type of a user in a domain.
3641:
3642: # Returns the authorization type or nouser if there is no such user.
3643: #
3644: sub GetAuthType
3645: {
3646:
3647: my ($domain, $user) = @_;
3648:
3649: Debug("GetAuthType( $domain, $user ) \n");
3650: my $proname = &propath($domain, $user);
3651: my $passwdfile = "$proname/passwd";
3652: if( -e $passwdfile ) {
3653: my $pf = IO::File->new($passwdfile);
3654: my $realpassword = <$pf>;
3655: chomp($realpassword);
3656: Debug("Password info = $realpassword\n");
3657: my ($authtype, $contentpwd) = split(/:/, $realpassword);
3658: Debug("Authtype = $authtype, content = $contentpwd\n");
3659: my $availinfo = '';
3660: if($authtype eq 'krb4' or $authtype eq 'krb5') {
3661: $availinfo = $contentpwd;
3662: }
3663:
3664: return "$authtype:$availinfo";
3665: }
3666: else {
3667: Debug("Returning nouser");
3668: return "nouser";
3669: }
3670: }
3671:
3672: sub addline {
3673: my ($fname,$hostid,$ip,$newline)=@_;
3674: my $contents;
3675: my $found=0;
3676: my $expr='^'.$hostid.':'.$ip.':';
3677: $expr =~ s/\./\\\./g;
3678: my $sh;
3679: if ($sh=IO::File->new("$fname.subscription")) {
3680: while (my $subline=<$sh>) {
3681: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
3682: }
3683: $sh->close();
3684: }
3685: $sh=IO::File->new(">$fname.subscription");
3686: if ($contents) { print $sh $contents; }
3687: if ($newline) { print $sh $newline; }
3688: $sh->close();
3689: return $found;
3690: }
3691:
3692: sub getchat {
3693: my ($cdom,$cname,$udom,$uname)=@_;
3694: my %hash;
3695: my $proname=&propath($cdom,$cname);
3696: my @entries=();
3697: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
3698: &GDBM_READER(),0640)) {
3699: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
3700: untie %hash;
3701: }
3702: my @participants=();
3703: my $cutoff=time-60;
3704: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
3705: &GDBM_WRCREAT(),0640)) {
3706: $hash{$uname.':'.$udom}=time;
3707: foreach (sort keys %hash) {
3708: if ($hash{$_}>$cutoff) {
3709: $participants[$#participants+1]='active_participant:'.$_;
3710: }
3711: }
3712: untie %hash;
3713: }
3714: return (@participants,@entries);
3715: }
3716:
3717: sub chatadd {
3718: my ($cdom,$cname,$newchat)=@_;
3719: my %hash;
3720: my $proname=&propath($cdom,$cname);
3721: my @entries=();
3722: my $time=time;
3723: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
3724: &GDBM_WRCREAT(),0640)) {
3725: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
3726: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
3727: my ($thentime,$idnum)=split(/\_/,$lastid);
3728: my $newid=$time.'_000000';
3729: if ($thentime==$time) {
3730: $idnum=~s/^0+//;
3731: $idnum++;
3732: $idnum=substr('000000'.$idnum,-6,6);
3733: $newid=$time.'_'.$idnum;
3734: }
3735: $hash{$newid}=$newchat;
3736: my $expired=$time-3600;
3737: foreach (keys %hash) {
3738: my ($thistime)=($_=~/(\d+)\_/);
3739: if ($thistime<$expired) {
3740: delete $hash{$_};
3741: }
3742: }
3743: untie %hash;
3744: }
3745: {
3746: my $hfh;
3747: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
3748: print $hfh "$time:".&unescape($newchat)."\n";
3749: }
3750: }
3751: }
3752:
3753: sub unsub {
3754: my ($fname,$clientip)=@_;
3755: my $result;
3756: my $unsubs = 0; # Number of successful unsubscribes:
3757:
3758:
3759: # An old way subscriptions were handled was to have a
3760: # subscription marker file:
3761:
3762: Debug("Attempting unlink of $fname.$clientname");
3763: if (unlink("$fname.$clientname")) {
3764: $unsubs++; # Successful unsub via marker file.
3765: }
3766:
3767: # The more modern way to do it is to have a subscription list
3768: # file:
3769:
3770: if (-e "$fname.subscription") {
3771: my $found=&addline($fname,$clientname,$clientip,'');
3772: if ($found) {
3773: $unsubs++;
3774: }
3775: }
3776:
3777: # If either or both of these mechanisms succeeded in unsubscribing a
3778: # resource we can return ok:
3779:
3780: if($unsubs) {
3781: $result = "ok\n";
3782: } else {
3783: $result = "not_subscribed\n";
3784: }
3785:
3786: return $result;
3787: }
3788:
3789: sub currentversion {
3790: my $fname=shift;
3791: my $version=-1;
3792: my $ulsdir='';
3793: if ($fname=~/^(.+)\/[^\/]+$/) {
3794: $ulsdir=$1;
3795: }
3796: my ($fnamere1,$fnamere2);
3797: # remove version if already specified
3798: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
3799: # get the bits that go before and after the version number
3800: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
3801: $fnamere1=$1;
3802: $fnamere2='.'.$2;
3803: }
3804: if (-e $fname) { $version=1; }
3805: if (-e $ulsdir) {
3806: if(-d $ulsdir) {
3807: if (opendir(LSDIR,$ulsdir)) {
3808: my $ulsfn;
3809: while ($ulsfn=readdir(LSDIR)) {
3810: # see if this is a regular file (ignore links produced earlier)
3811: my $thisfile=$ulsdir.'/'.$ulsfn;
3812: unless (-l $thisfile) {
3813: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
3814: if ($1>$version) { $version=$1; }
3815: }
3816: }
3817: }
3818: closedir(LSDIR);
3819: $version++;
3820: }
3821: }
3822: }
3823: return $version;
3824: }
3825:
3826: sub thisversion {
3827: my $fname=shift;
3828: my $version=-1;
3829: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
3830: $version=$1;
3831: }
3832: return $version;
3833: }
3834:
3835: sub subscribe {
3836: my ($userinput,$clientip)=@_;
3837: my $result;
3838: my ($cmd,$fname)=split(/:/,$userinput);
3839: my $ownership=&ishome($fname);
3840: if ($ownership eq 'owner') {
3841: # explitly asking for the current version?
3842: unless (-e $fname) {
3843: my $currentversion=¤tversion($fname);
3844: if (&thisversion($fname)==$currentversion) {
3845: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
3846: my $root=$1;
3847: my $extension=$2;
3848: symlink($root.'.'.$extension,
3849: $root.'.'.$currentversion.'.'.$extension);
3850: unless ($extension=~/\.meta$/) {
3851: symlink($root.'.'.$extension.'.meta',
3852: $root.'.'.$currentversion.'.'.$extension.'.meta');
3853: }
3854: }
3855: }
3856: }
3857: if (-e $fname) {
3858: if (-d $fname) {
3859: $result="directory\n";
3860: } else {
3861: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
3862: my $now=time;
3863: my $found=&addline($fname,$clientname,$clientip,
3864: "$clientname:$clientip:$now\n");
3865: if ($found) { $result="$fname\n"; }
3866: # if they were subscribed to only meta data, delete that
3867: # subscription, when you subscribe to a file you also get
3868: # the metadata
3869: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
3870: $fname=~s/\/home\/httpd\/html\/res/raw/;
3871: $fname="http://$thisserver/".$fname;
3872: $result="$fname\n";
3873: }
3874: } else {
3875: $result="not_found\n";
3876: }
3877: } else {
3878: $result="rejected\n";
3879: }
3880: return $result;
3881: }
3882:
3883: sub make_passwd_file {
3884: my ($uname, $umode,$npass,$passfilename)=@_;
3885: my $result="ok\n";
3886: if ($umode eq 'krb4' or $umode eq 'krb5') {
3887: {
3888: my $pf = IO::File->new(">$passfilename");
3889: print $pf "$umode:$npass\n";
3890: }
3891: } elsif ($umode eq 'internal') {
3892: my $salt=time;
3893: $salt=substr($salt,6,2);
3894: my $ncpass=crypt($npass,$salt);
3895: {
3896: &Debug("Creating internal auth");
3897: my $pf = IO::File->new(">$passfilename");
3898: print $pf "internal:$ncpass\n";
3899: }
3900: } elsif ($umode eq 'localauth') {
3901: {
3902: my $pf = IO::File->new(">$passfilename");
3903: print $pf "localauth:$npass\n";
3904: }
3905: } elsif ($umode eq 'unix') {
3906: {
3907: #
3908: # Don't allow the creation of privileged accounts!!! that would
3909: # be real bad!!!
3910: #
3911: my $uid = getpwnam($uname);
3912: if((defined $uid) && ($uid == 0)) {
3913: &logthis(">>>Attempted to create privilged account blocked");
3914: return "no_priv_account_error\n";
3915: }
3916:
3917: my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
3918: {
3919: &Debug("Executing external: ".$execpath);
3920: &Debug("user = ".$uname.", Password =". $npass);
3921: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
3922: print $se "$uname\n";
3923: print $se "$npass\n";
3924: print $se "$npass\n";
3925: }
3926: my $useraddok = $?;
3927: if($useraddok > 0) {
3928: &logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
3929: }
3930: my $pf = IO::File->new(">$passfilename");
3931: print $pf "unix:\n";
3932: }
3933: } elsif ($umode eq 'none') {
3934: {
3935: my $pf = IO::File->new(">$passfilename");
3936: print $pf "none:\n";
3937: }
3938: } else {
3939: $result="auth_mode_error\n";
3940: }
3941: return $result;
3942: }
3943:
3944: sub sethost {
3945: my ($remotereq) = @_;
3946: my (undef,$hostid)=split(/:/,$remotereq);
3947: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
3948: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
3949: $currenthostid =$hostid;
3950: $currentdomainid=$hostdom{$hostid};
3951: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
3952: } else {
3953: &logthis("Requested host id $hostid not an alias of ".
3954: $perlvar{'lonHostID'}." refusing connection");
3955: return 'unable_to_set';
3956: }
3957: return 'ok';
3958: }
3959:
3960: sub version {
3961: my ($userinput)=@_;
3962: $remoteVERSION=(split(/:/,$userinput))[1];
3963: return "version:$VERSION";
3964: }
3965:
3966: #There is a copy of this in lonnet.pm
3967: sub userload {
3968: my $numusers=0;
3969: {
3970: opendir(LONIDS,$perlvar{'lonIDsDir'});
3971: my $filename;
3972: my $curtime=time;
3973: while ($filename=readdir(LONIDS)) {
3974: if ($filename eq '.' || $filename eq '..') {next;}
3975: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
3976: if ($curtime-$mtime < 1800) { $numusers++; }
3977: }
3978: closedir(LONIDS);
3979: }
3980: my $userloadpercent=0;
3981: my $maxuserload=$perlvar{'lonUserLoadLim'};
3982: if ($maxuserload) {
3983: $userloadpercent=100*$numusers/$maxuserload;
3984: }
3985: $userloadpercent=sprintf("%.2f",$userloadpercent);
3986: return $userloadpercent;
3987: }
3988:
3989: # Routines for serializing arrays and hashes (copies from lonnet)
3990:
3991: sub array2str {
3992: my (@array) = @_;
3993: my $result=&arrayref2str(\@array);
3994: $result=~s/^__ARRAY_REF__//;
3995: $result=~s/__END_ARRAY_REF__$//;
3996: return $result;
3997: }
3998:
3999: sub arrayref2str {
4000: my ($arrayref) = @_;
4001: my $result='__ARRAY_REF__';
4002: foreach my $elem (@$arrayref) {
4003: if(ref($elem) eq 'ARRAY') {
4004: $result.=&arrayref2str($elem).'&';
4005: } elsif(ref($elem) eq 'HASH') {
4006: $result.=&hashref2str($elem).'&';
4007: } elsif(ref($elem)) {
4008: #print("Got a ref of ".(ref($elem))." skipping.");
4009: } else {
4010: $result.=&escape($elem).'&';
4011: }
4012: }
4013: $result=~s/\&$//;
4014: $result .= '__END_ARRAY_REF__';
4015: return $result;
4016: }
4017:
4018: sub hash2str {
4019: my (%hash) = @_;
4020: my $result=&hashref2str(\%hash);
4021: $result=~s/^__HASH_REF__//;
4022: $result=~s/__END_HASH_REF__$//;
4023: return $result;
4024: }
4025:
4026: sub hashref2str {
4027: my ($hashref)=@_;
4028: my $result='__HASH_REF__';
4029: foreach (sort(keys(%$hashref))) {
4030: if (ref($_) eq 'ARRAY') {
4031: $result.=&arrayref2str($_).'=';
4032: } elsif (ref($_) eq 'HASH') {
4033: $result.=&hashref2str($_).'=';
4034: } elsif (ref($_)) {
4035: $result.='=';
4036: #print("Got a ref of ".(ref($_))." skipping.");
4037: } else {
4038: if ($_) {$result.=&escape($_).'=';} else { last; }
4039: }
4040:
4041: if(ref($hashref->{$_}) eq 'ARRAY') {
4042: $result.=&arrayref2str($hashref->{$_}).'&';
4043: } elsif(ref($hashref->{$_}) eq 'HASH') {
4044: $result.=&hashref2str($hashref->{$_}).'&';
4045: } elsif(ref($hashref->{$_})) {
4046: $result.='&';
4047: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
4048: } else {
4049: $result.=&escape($hashref->{$_}).'&';
4050: }
4051: }
4052: $result=~s/\&$//;
4053: $result .= '__END_HASH_REF__';
4054: return $result;
4055: }
4056:
4057: # ----------------------------------- POD (plain old documentation, CPAN style)
4058:
4059: =head1 NAME
4060:
4061: lond - "LON Daemon" Server (port "LOND" 5663)
4062:
4063: =head1 SYNOPSIS
4064:
4065: Usage: B<lond>
4066:
4067: Should only be run as user=www. This is a command-line script which
4068: is invoked by B<loncron>. There is no expectation that a typical user
4069: will manually start B<lond> from the command-line. (In other words,
4070: DO NOT START B<lond> YOURSELF.)
4071:
4072: =head1 DESCRIPTION
4073:
4074: There are two characteristics associated with the running of B<lond>,
4075: PROCESS MANAGEMENT (starting, stopping, handling child processes)
4076: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
4077: subscriptions, etc). These are described in two large
4078: sections below.
4079:
4080: B<PROCESS MANAGEMENT>
4081:
4082: Preforker - server who forks first. Runs as a daemon. HUPs.
4083: Uses IDEA encryption
4084:
4085: B<lond> forks off children processes that correspond to the other servers
4086: in the network. Management of these processes can be done at the
4087: parent process level or the child process level.
4088:
4089: B<logs/lond.log> is the location of log messages.
4090:
4091: The process management is now explained in terms of linux shell commands,
4092: subroutines internal to this code, and signal assignments:
4093:
4094: =over 4
4095:
4096: =item *
4097:
4098: PID is stored in B<logs/lond.pid>
4099:
4100: This is the process id number of the parent B<lond> process.
4101:
4102: =item *
4103:
4104: SIGTERM and SIGINT
4105:
4106: Parent signal assignment:
4107: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
4108:
4109: Child signal assignment:
4110: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
4111: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
4112: to restart a new child.)
4113:
4114: Command-line invocations:
4115: B<kill> B<-s> SIGTERM I<PID>
4116: B<kill> B<-s> SIGINT I<PID>
4117:
4118: Subroutine B<HUNTSMAN>:
4119: This is only invoked for the B<lond> parent I<PID>.
4120: This kills all the children, and then the parent.
4121: The B<lonc.pid> file is cleared.
4122:
4123: =item *
4124:
4125: SIGHUP
4126:
4127: Current bug:
4128: This signal can only be processed the first time
4129: on the parent process. Subsequent SIGHUP signals
4130: have no effect.
4131:
4132: Parent signal assignment:
4133: $SIG{HUP} = \&HUPSMAN;
4134:
4135: Child signal assignment:
4136: none (nothing happens)
4137:
4138: Command-line invocations:
4139: B<kill> B<-s> SIGHUP I<PID>
4140:
4141: Subroutine B<HUPSMAN>:
4142: This is only invoked for the B<lond> parent I<PID>,
4143: This kills all the children, and then the parent.
4144: The B<lond.pid> file is cleared.
4145:
4146: =item *
4147:
4148: SIGUSR1
4149:
4150: Parent signal assignment:
4151: $SIG{USR1} = \&USRMAN;
4152:
4153: Child signal assignment:
4154: $SIG{USR1}= \&logstatus;
4155:
4156: Command-line invocations:
4157: B<kill> B<-s> SIGUSR1 I<PID>
4158:
4159: Subroutine B<USRMAN>:
4160: When invoked for the B<lond> parent I<PID>,
4161: SIGUSR1 is sent to all the children, and the status of
4162: each connection is logged.
4163:
4164: =item *
4165:
4166: SIGUSR2
4167:
4168: Parent Signal assignment:
4169: $SIG{USR2} = \&UpdateHosts
4170:
4171: Child signal assignment:
4172: NONE
4173:
4174:
4175: =item *
4176:
4177: SIGCHLD
4178:
4179: Parent signal assignment:
4180: $SIG{CHLD} = \&REAPER;
4181:
4182: Child signal assignment:
4183: none
4184:
4185: Command-line invocations:
4186: B<kill> B<-s> SIGCHLD I<PID>
4187:
4188: Subroutine B<REAPER>:
4189: This is only invoked for the B<lond> parent I<PID>.
4190: Information pertaining to the child is removed.
4191: The socket port is cleaned up.
4192:
4193: =back
4194:
4195: B<SERVER-SIDE ACTIVITIES>
4196:
4197: Server-side information can be accepted in an encrypted or non-encrypted
4198: method.
4199:
4200: =over 4
4201:
4202: =item ping
4203:
4204: Query a client in the hosts.tab table; "Are you there?"
4205:
4206: =item pong
4207:
4208: Respond to a ping query.
4209:
4210: =item ekey
4211:
4212: Read in encrypted key, make cipher. Respond with a buildkey.
4213:
4214: =item load
4215:
4216: Respond with CPU load based on a computation upon /proc/loadavg.
4217:
4218: =item currentauth
4219:
4220: Reply with current authentication information (only over an
4221: encrypted channel).
4222:
4223: =item auth
4224:
4225: Only over an encrypted channel, reply as to whether a user's
4226: authentication information can be validated.
4227:
4228: =item passwd
4229:
4230: Allow for a password to be set.
4231:
4232: =item makeuser
4233:
4234: Make a user.
4235:
4236: =item passwd
4237:
4238: Allow for authentication mechanism and password to be changed.
4239:
4240: =item home
4241:
4242: Respond to a question "are you the home for a given user?"
4243:
4244: =item update
4245:
4246: Update contents of a subscribed resource.
4247:
4248: =item unsubscribe
4249:
4250: The server is unsubscribing from a resource.
4251:
4252: =item subscribe
4253:
4254: The server is subscribing to a resource.
4255:
4256: =item log
4257:
4258: Place in B<logs/lond.log>
4259:
4260: =item put
4261:
4262: stores hash in namespace
4263:
4264: =item rolesput
4265:
4266: put a role into a user's environment
4267:
4268: =item get
4269:
4270: returns hash with keys from array
4271: reference filled in from namespace
4272:
4273: =item eget
4274:
4275: returns hash with keys from array
4276: reference filled in from namesp (encrypts the return communication)
4277:
4278: =item rolesget
4279:
4280: get a role from a user's environment
4281:
4282: =item del
4283:
4284: deletes keys out of array from namespace
4285:
4286: =item keys
4287:
4288: returns namespace keys
4289:
4290: =item dump
4291:
4292: dumps the complete (or key matching regexp) namespace into a hash
4293:
4294: =item store
4295:
4296: stores hash permanently
4297: for this url; hashref needs to be given and should be a \%hashname; the
4298: remaining args aren't required and if they aren't passed or are '' they will
4299: be derived from the ENV
4300:
4301: =item restore
4302:
4303: returns a hash for a given url
4304:
4305: =item querysend
4306:
4307: Tells client about the lonsql process that has been launched in response
4308: to a sent query.
4309:
4310: =item queryreply
4311:
4312: Accept information from lonsql and make appropriate storage in temporary
4313: file space.
4314:
4315: =item idput
4316:
4317: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
4318: for each student, defined perhaps by the institutional Registrar.)
4319:
4320: =item idget
4321:
4322: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
4323: for each student, defined perhaps by the institutional Registrar.)
4324:
4325: =item tmpput
4326:
4327: Accept and store information in temporary space.
4328:
4329: =item tmpget
4330:
4331: Send along temporarily stored information.
4332:
4333: =item ls
4334:
4335: List part of a user's directory.
4336:
4337: =item pushtable
4338:
4339: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
4340: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
4341: must be restored manually in case of a problem with the new table file.
4342: pushtable requires that the request be encrypted and validated via
4343: ValidateManager. The form of the command is:
4344: enc:pushtable tablename <tablecontents> \n
4345: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
4346: cleartext newline.
4347:
4348: =item Hanging up (exit or init)
4349:
4350: What to do when a client tells the server that they (the client)
4351: are leaving the network.
4352:
4353: =item unknown command
4354:
4355: If B<lond> is sent an unknown command (not in the list above),
4356: it replys to the client "unknown_cmd".
4357:
4358:
4359: =item UNKNOWN CLIENT
4360:
4361: If the anti-spoofing algorithm cannot verify the client,
4362: the client is rejected (with a "refused" message sent
4363: to the client, and the connection is closed.
4364:
4365: =back
4366:
4367: =head1 PREREQUISITES
4368:
4369: IO::Socket
4370: IO::File
4371: Apache::File
4372: Symbol
4373: POSIX
4374: Crypt::IDEA
4375: LWP::UserAgent()
4376: GDBM_File
4377: Authen::Krb4
4378: Authen::Krb5
4379:
4380: =head1 COREQUISITES
4381:
4382: =head1 OSNAMES
4383:
4384: linux
4385:
4386: =head1 SCRIPT CATEGORIES
4387:
4388: Server/Process
4389:
4390: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>