File:
[LON-CAPA] /
loncom /
lond
Revision
1.280:
download - view:
text,
annotated -
select for diffs
Thu Mar 3 23:21:51 2005 UTC (19 years, 5 months ago) by
matthew
Branches:
MAIN
CVS tags:
HEAD
Bug 3964: Use of ':' in directory name prevented resource browsing
lond: added ls2_handler which encodes its results prior to concatenating
them with ':'s.
lonnet::dirlist: modified to call 'ls2' and fall back to 'ls' on failure.
unescapes values from 'ls2' before sending them back.
1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
4: #
5: # $Id: lond,v 1.280 2005/03/03 23:21:51 matthew 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 localstudentphoto;
50: use File::Copy;
51: use LONCAPA::ConfigFileEdit;
52: use LONCAPA::lonlocal;
53: use LONCAPA::lonssl;
54: use Fcntl qw(:flock);
55:
56: my $DEBUG = 0; # Non zero to enable debug log entries.
57:
58: my $status='';
59: my $lastlog='';
60:
61: my $VERSION='$Revision: 1.280 $'; #' stupid emacs
62: my $remoteVERSION;
63: my $currenthostid="default";
64: my $currentdomainid;
65:
66: my $client;
67: my $clientip; # IP address of client.
68: my $clientname; # LonCAPA name of client.
69:
70: my $server;
71: my $thisserver; # DNS of us.
72:
73: my $keymode;
74:
75: my $cipher; # Cipher key negotiated with client
76: my $tmpsnum = 0; # Id of tmpputs.
77:
78: #
79: # Connection type is:
80: # client - All client actions are allowed
81: # manager - only management functions allowed.
82: # both - Both management and client actions are allowed
83: #
84:
85: my $ConnectionType;
86:
87: my %hostid; # ID's for hosts in cluster by ip.
88: my %hostdom; # LonCAPA domain for hosts in cluster.
89: my %hostip; # IPs for hosts in cluster.
90: my %hostdns; # ID's of hosts looked up by DNS name.
91:
92: my %managers; # Ip -> manager names
93:
94: my %perlvar; # Will have the apache conf defined perl vars.
95:
96: #
97: # The hash below is used for command dispatching, and is therefore keyed on the request keyword.
98: # Each element of the hash contains a reference to an array that contains:
99: # A reference to a sub that executes the request corresponding to the keyword.
100: # A flag that is true if the request must be encoded to be acceptable.
101: # A mask with bits as follows:
102: # CLIENT_OK - Set when the function is allowed by ordinary clients
103: # MANAGER_OK - Set when the function is allowed to manager clients.
104: #
105: my $CLIENT_OK = 1;
106: my $MANAGER_OK = 2;
107: my %Dispatcher;
108:
109:
110: #
111: # The array below are password error strings."
112: #
113: my $lastpwderror = 13; # Largest error number from lcpasswd.
114: my @passwderrors = ("ok",
115: "lcpasswd must be run as user 'www'",
116: "lcpasswd got incorrect number of arguments",
117: "lcpasswd did not get the right nubmer of input text lines",
118: "lcpasswd too many simultaneous pwd changes in progress",
119: "lcpasswd User does not exist.",
120: "lcpasswd Incorrect current passwd",
121: "lcpasswd Unable to su to root.",
122: "lcpasswd Cannot set new passwd.",
123: "lcpasswd Username has invalid characters",
124: "lcpasswd Invalid characters in password",
125: "lcpasswd User already exists",
126: "lcpasswd Something went wrong with user addition.",
127: "lcpasswd Password mismatch",
128: "lcpasswd Error filename is invalid");
129:
130:
131: # The array below are lcuseradd error strings.:
132:
133: my $lastadderror = 13;
134: my @adderrors = ("ok",
135: "User ID mismatch, lcuseradd must run as user www",
136: "lcuseradd Incorrect number of command line parameters must be 3",
137: "lcuseradd Incorrect number of stdinput lines, must be 3",
138: "lcuseradd Too many other simultaneous pwd changes in progress",
139: "lcuseradd User does not exist",
140: "lcuseradd Unable to make www member of users's group",
141: "lcuseradd Unable to su to root",
142: "lcuseradd Unable to set password",
143: "lcuseradd Usrname has invalid characters",
144: "lcuseradd Password has an invalid character",
145: "lcuseradd User already exists",
146: "lcuseradd Could not add user.",
147: "lcuseradd Password mismatch");
148:
149:
150:
151: #
152: # Statistics that are maintained and dislayed in the status line.
153: #
154: my $Transactions = 0; # Number of attempted transactions.
155: my $Failures = 0; # Number of transcations failed.
156:
157: # ResetStatistics:
158: # Resets the statistics counters:
159: #
160: sub ResetStatistics {
161: $Transactions = 0;
162: $Failures = 0;
163: }
164:
165: #------------------------------------------------------------------------
166: #
167: # LocalConnection
168: # Completes the formation of a locally authenticated connection.
169: # This function will ensure that the 'remote' client is really the
170: # local host. If not, the connection is closed, and the function fails.
171: # If so, initcmd is parsed for the name of a file containing the
172: # IDEA session key. The fie is opened, read, deleted and the session
173: # key returned to the caller.
174: #
175: # Parameters:
176: # $Socket - Socket open on client.
177: # $initcmd - The full text of the init command.
178: #
179: # Implicit inputs:
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: $clientip me: $thisserver");
189: if($clientip ne "127.0.0.1") {
190: &logthis('<font color="red"> LocalConnection rejecting non local: '
191: ."$clientip ne $thisserver </font>");
192: close $Socket;
193: return undef;
194: } else {
195: chomp($initcmd); # Get rid of \n in filename.
196: my ($init, $type, $name) = split(/:/, $initcmd);
197: Debug(" Init command: $init $type $name ");
198:
199: # Require that $init = init, and $type = local: Otherwise
200: # the caller is insane:
201:
202: if(($init ne "init") && ($type ne "local")) {
203: &logthis('<font color = "red"> LocalConnection: caller is insane! '
204: ."init = $init, and type = $type </font>");
205: close($Socket);;
206: return undef;
207:
208: }
209: # Now get the key filename:
210:
211: my $IDEAKey = lonlocal::ReadKeyFile($name);
212: return $IDEAKey;
213: }
214: }
215: #------------------------------------------------------------------------------
216: #
217: # SSLConnection
218: # Completes the formation of an ssh authenticated connection. The
219: # socket is promoted to an ssl socket. If this promotion and the associated
220: # certificate exchange are successful, the IDEA key is generated and sent
221: # to the remote peer via the SSL tunnel. The IDEA key is also returned to
222: # the caller after the SSL tunnel is torn down.
223: #
224: # Parameters:
225: # Name Type Purpose
226: # $Socket IO::Socket::INET Plaintext socket.
227: #
228: # Returns:
229: # IDEA key on success.
230: # undef on failure.
231: #
232: sub SSLConnection {
233: my $Socket = shift;
234:
235: Debug("SSLConnection: ");
236: my $KeyFile = lonssl::KeyFile();
237: if(!$KeyFile) {
238: my $err = lonssl::LastError();
239: &logthis("<font color=\"red\"> CRITICAL"
240: ."Can't get key file $err </font>");
241: return undef;
242: }
243: my ($CACertificate,
244: $Certificate) = lonssl::CertificateFile();
245:
246:
247: # If any of the key, certificate or certificate authority
248: # certificate filenames are not defined, this can't work.
249:
250: if((!$Certificate) || (!$CACertificate)) {
251: my $err = lonssl::LastError();
252: &logthis("<font color=\"red\"> CRITICAL"
253: ."Can't get certificates: $err </font>");
254:
255: return undef;
256: }
257: Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
258:
259: # Indicate to our peer that we can procede with
260: # a transition to ssl authentication:
261:
262: print $Socket "ok:ssl\n";
263:
264: Debug("Approving promotion -> ssl");
265: # And do so:
266:
267: my $SSLSocket = lonssl::PromoteServerSocket($Socket,
268: $CACertificate,
269: $Certificate,
270: $KeyFile);
271: if(! ($SSLSocket) ) { # SSL socket promotion failed.
272: my $err = lonssl::LastError();
273: &logthis("<font color=\"red\"> CRITICAL "
274: ."SSL Socket promotion failed: $err </font>");
275: return undef;
276: }
277: Debug("SSL Promotion successful");
278:
279: #
280: # The only thing we'll use the socket for is to send the IDEA key
281: # to the peer:
282:
283: my $Key = lonlocal::CreateCipherKey();
284: print $SSLSocket "$Key\n";
285:
286: lonssl::Close($SSLSocket);
287:
288: Debug("Key exchange complete: $Key");
289:
290: return $Key;
291: }
292: #
293: # InsecureConnection:
294: # If insecure connections are allowd,
295: # exchange a challenge with the client to 'validate' the
296: # client (not really, but that's the protocol):
297: # We produce a challenge string that's sent to the client.
298: # The client must then echo the challenge verbatim to us.
299: #
300: # Parameter:
301: # Socket - Socket open on the client.
302: # Returns:
303: # 1 - success.
304: # 0 - failure (e.g.mismatch or insecure not allowed).
305: #
306: sub InsecureConnection {
307: my $Socket = shift;
308:
309: # Don't even start if insecure connections are not allowed.
310:
311: if(! $perlvar{londAllowInsecure}) { # Insecure connections not allowed.
312: return 0;
313: }
314:
315: # Fabricate a challenge string and send it..
316:
317: my $challenge = "$$".time; # pid + time.
318: print $Socket "$challenge\n";
319: &status("Waiting for challenge reply");
320:
321: my $answer = <$Socket>;
322: $answer =~s/\W//g;
323: if($challenge eq $answer) {
324: return 1;
325: } else {
326: logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
327: &status("No challenge reqply");
328: return 0;
329: }
330:
331:
332: }
333: #
334: # Safely execute a command (as long as it's not a shel command and doesn
335: # not require/rely on shell escapes. The function operates by doing a
336: # a pipe based fork and capturing stdout and stderr from the pipe.
337: #
338: # Formal Parameters:
339: # $line - A line of text to be executed as a command.
340: # Returns:
341: # The output from that command. If the output is multiline the caller
342: # must know how to split up the output.
343: #
344: #
345: sub execute_command {
346: my ($line) = @_;
347: my @words = split(/\s/, $line); # Bust the command up into words.
348: my $output = "";
349:
350: my $pid = open(CHILD, "-|");
351:
352: if($pid) { # Parent process
353: Debug("In parent process for execute_command");
354: my @data = <CHILD>; # Read the child's outupt...
355: close CHILD;
356: foreach my $output_line (@data) {
357: Debug("Adding $output_line");
358: $output .= $output_line; # Presumably has a \n on it.
359: }
360:
361: } else { # Child process
362: close (STDERR);
363: open (STDERR, ">&STDOUT");# Combine stderr, and stdout...
364: exec(@words); # won't return.
365: }
366: return $output;
367: }
368:
369:
370: # GetCertificate: Given a transaction that requires a certificate,
371: # this function will extract the certificate from the transaction
372: # request. Note that at this point, the only concept of a certificate
373: # is the hostname to which we are connected.
374: #
375: # Parameter:
376: # request - The request sent by our client (this parameterization may
377: # need to change when we really use a certificate granting
378: # authority.
379: #
380: sub GetCertificate {
381: my $request = shift;
382:
383: return $clientip;
384: }
385:
386: #
387: # Return true if client is a manager.
388: #
389: sub isManager {
390: return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
391: }
392: #
393: # Return tru if client can do client functions
394: #
395: sub isClient {
396: return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
397: }
398:
399:
400: #
401: # ReadManagerTable: Reads in the current manager table. For now this is
402: # done on each manager authentication because:
403: # - These authentications are not frequent
404: # - This allows dynamic changes to the manager table
405: # without the need to signal to the lond.
406: #
407: sub ReadManagerTable {
408:
409: # Clean out the old table first..
410:
411: foreach my $key (keys %managers) {
412: delete $managers{$key};
413: }
414:
415: my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
416: if (!open (MANAGERS, $tablename)) {
417: logthis('<font color="red">No manager table. Nobody can manage!!</font>');
418: return;
419: }
420: while(my $host = <MANAGERS>) {
421: chomp($host);
422: if ($host =~ "^#") { # Comment line.
423: next;
424: }
425: if (!defined $hostip{$host}) { # This is a non cluster member
426: # The entry is of the form:
427: # cluname:hostname
428: # cluname - A 'cluster hostname' is needed in order to negotiate
429: # the host key.
430: # hostname- The dns name of the host.
431: #
432: my($cluname, $dnsname) = split(/:/, $host);
433:
434: my $ip = gethostbyname($dnsname);
435: if(defined($ip)) { # bad names don't deserve entry.
436: my $hostip = inet_ntoa($ip);
437: $managers{$hostip} = $cluname;
438: logthis('<font color="green"> registering manager '.
439: "$dnsname as $cluname with $hostip </font>\n");
440: }
441: } else {
442: logthis('<font color="green"> existing host'." $host</font>\n");
443: $managers{$hostip{$host}} = $host; # Use info from cluster tab if clumemeber
444: }
445: }
446: }
447:
448: #
449: # ValidManager: Determines if a given certificate represents a valid manager.
450: # in this primitive implementation, the 'certificate' is
451: # just the connecting loncapa client name. This is checked
452: # against a valid client list in the configuration.
453: #
454: #
455: sub ValidManager {
456: my $certificate = shift;
457:
458: return isManager;
459: }
460: #
461: # CopyFile: Called as part of the process of installing a
462: # new configuration file. This function copies an existing
463: # file to a backup file.
464: # Parameters:
465: # oldfile - Name of the file to backup.
466: # newfile - Name of the backup file.
467: # Return:
468: # 0 - Failure (errno has failure reason).
469: # 1 - Success.
470: #
471: sub CopyFile {
472:
473: my ($oldfile, $newfile) = @_;
474:
475: # The file must exist:
476:
477: if(-e $oldfile) {
478:
479: # Read the old file.
480:
481: my $oldfh = IO::File->new("< $oldfile");
482: if(!$oldfh) {
483: return 0;
484: }
485: my @contents = <$oldfh>; # Suck in the entire file.
486:
487: # write the backup file:
488:
489: my $newfh = IO::File->new("> $newfile");
490: if(!(defined $newfh)){
491: return 0;
492: }
493: my $lines = scalar @contents;
494: for (my $i =0; $i < $lines; $i++) {
495: print $newfh ($contents[$i]);
496: }
497:
498: $oldfh->close;
499: $newfh->close;
500:
501: chmod(0660, $newfile);
502:
503: return 1;
504:
505: } else {
506: return 0;
507: }
508: }
509: #
510: # Host files are passed out with externally visible host IPs.
511: # If, for example, we are behind a fire-wall or NAT host, our
512: # internally visible IP may be different than the externally
513: # visible IP. Therefore, we always adjust the contents of the
514: # host file so that the entry for ME is the IP that we believe
515: # we have. At present, this is defined as the entry that
516: # DNS has for us. If by some chance we are not able to get a
517: # DNS translation for us, then we assume that the host.tab file
518: # is correct.
519: # BUGBUGBUG - in the future, we really should see if we can
520: # easily query the interface(s) instead.
521: # Parameter(s):
522: # contents - The contents of the host.tab to check.
523: # Returns:
524: # newcontents - The adjusted contents.
525: #
526: #
527: sub AdjustHostContents {
528: my $contents = shift;
529: my $adjusted;
530: my $me = $perlvar{'lonHostID'};
531:
532: foreach my $line (split(/\n/,$contents)) {
533: if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
534: chomp($line);
535: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
536: if ($id eq $me) {
537: my $ip = gethostbyname($name);
538: my $ipnew = inet_ntoa($ip);
539: $ip = $ipnew;
540: # Reconstruct the host line and append to adjusted:
541:
542: my $newline = "$id:$domain:$role:$name:$ip";
543: if($maxcon ne "") { # Not all hosts have loncnew tuning params
544: $newline .= ":$maxcon:$idleto:$mincon";
545: }
546: $adjusted .= $newline."\n";
547:
548: } else { # Not me, pass unmodified.
549: $adjusted .= $line."\n";
550: }
551: } else { # Blank or comment never re-written.
552: $adjusted .= $line."\n"; # Pass blanks and comments as is.
553: }
554: }
555: return $adjusted;
556: }
557: #
558: # InstallFile: Called to install an administrative file:
559: # - The file is created with <name>.tmp
560: # - The <name>.tmp file is then mv'd to <name>
561: # This lugubrious procedure is done to ensure that we are never without
562: # a valid, even if dated, version of the file regardless of who crashes
563: # and when the crash occurs.
564: #
565: # Parameters:
566: # Name of the file
567: # File Contents.
568: # Return:
569: # nonzero - success.
570: # 0 - failure and $! has an errno.
571: #
572: sub InstallFile {
573:
574: my ($Filename, $Contents) = @_;
575: my $TempFile = $Filename.".tmp";
576:
577: # Open the file for write:
578:
579: my $fh = IO::File->new("> $TempFile"); # Write to temp.
580: if(!(defined $fh)) {
581: &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
582: return 0;
583: }
584: # write the contents of the file:
585:
586: print $fh ($Contents);
587: $fh->close; # In case we ever have a filesystem w. locking
588:
589: chmod(0660, $TempFile);
590:
591: # Now we can move install the file in position.
592:
593: move($TempFile, $Filename);
594:
595: return 1;
596: }
597:
598:
599: #
600: # ConfigFileFromSelector: converts a configuration file selector
601: # (one of host or domain at this point) into a
602: # configuration file pathname.
603: #
604: # Parameters:
605: # selector - Configuration file selector.
606: # Returns:
607: # Full path to the file or undef if the selector is invalid.
608: #
609: sub ConfigFileFromSelector {
610: my $selector = shift;
611: my $tablefile;
612:
613: my $tabledir = $perlvar{'lonTabDir'}.'/';
614: if ($selector eq "hosts") {
615: $tablefile = $tabledir."hosts.tab";
616: } elsif ($selector eq "domain") {
617: $tablefile = $tabledir."domain.tab";
618: } else {
619: return undef;
620: }
621: return $tablefile;
622:
623: }
624: #
625: # PushFile: Called to do an administrative push of a file.
626: # - Ensure the file being pushed is one we support.
627: # - Backup the old file to <filename.saved>
628: # - Separate the contents of the new file out from the
629: # rest of the request.
630: # - Write the new file.
631: # Parameter:
632: # Request - The entire user request. This consists of a : separated
633: # string pushfile:tablename:contents.
634: # NOTE: The contents may have :'s in it as well making things a bit
635: # more interesting... but not much.
636: # Returns:
637: # String to send to client ("ok" or "refused" if bad file).
638: #
639: sub PushFile {
640: my $request = shift;
641: my ($command, $filename, $contents) = split(":", $request, 3);
642:
643: # At this point in time, pushes for only the following tables are
644: # supported:
645: # hosts.tab ($filename eq host).
646: # domain.tab ($filename eq domain).
647: # Construct the destination filename or reject the request.
648: #
649: # lonManage is supposed to ensure this, however this session could be
650: # part of some elaborate spoof that managed somehow to authenticate.
651: #
652:
653:
654: my $tablefile = ConfigFileFromSelector($filename);
655: if(! (defined $tablefile)) {
656: return "refused";
657: }
658: #
659: # >copy< the old table to the backup table
660: # don't rename in case system crashes/reboots etc. in the time
661: # window between a rename and write.
662: #
663: my $backupfile = $tablefile;
664: $backupfile =~ s/\.tab$/.old/;
665: if(!CopyFile($tablefile, $backupfile)) {
666: &logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
667: return "error:$!";
668: }
669: &logthis('<font color="green"> Pushfile: backed up '
670: .$tablefile." to $backupfile</font>");
671:
672: # If the file being pushed is the host file, we adjust the entry for ourself so that the
673: # IP will be our current IP as looked up in dns. Note this is only 99% good as it's possible
674: # to conceive of conditions where we don't have a DNS entry locally. This is possible in a
675: # network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
676: # that possibilty.
677:
678: if($filename eq "host") {
679: $contents = AdjustHostContents($contents);
680: }
681:
682: # Install the new file:
683:
684: if(!InstallFile($tablefile, $contents)) {
685: &logthis('<font color="red"> Pushfile: unable to install '
686: .$tablefile." $! </font>");
687: return "error:$!";
688: } else {
689: &logthis('<font color="green"> Installed new '.$tablefile
690: ."</font>");
691:
692: }
693:
694:
695: # Indicate success:
696:
697: return "ok";
698:
699: }
700:
701: #
702: # Called to re-init either lonc or lond.
703: #
704: # Parameters:
705: # request - The full request by the client. This is of the form
706: # reinit:<process>
707: # where <process> is allowed to be either of
708: # lonc or lond
709: #
710: # Returns:
711: # The string to be sent back to the client either:
712: # ok - Everything worked just fine.
713: # error:why - There was a failure and why describes the reason.
714: #
715: #
716: sub ReinitProcess {
717: my $request = shift;
718:
719:
720: # separate the request (reinit) from the process identifier and
721: # validate it producing the name of the .pid file for the process.
722: #
723: #
724: my ($junk, $process) = split(":", $request);
725: my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
726: if($process eq 'lonc') {
727: $processpidfile = $processpidfile."lonc.pid";
728: if (!open(PIDFILE, "< $processpidfile")) {
729: return "error:Open failed for $processpidfile";
730: }
731: my $loncpid = <PIDFILE>;
732: close(PIDFILE);
733: logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
734: ."</font>");
735: kill("USR2", $loncpid);
736: } elsif ($process eq 'lond') {
737: logthis('<font color="red"> Reinitializing self (lond) </font>');
738: &UpdateHosts; # Lond is us!!
739: } else {
740: &logthis('<font color="yellow" Invalid reinit request for '.$process
741: ."</font>");
742: return "error:Invalid process identifier $process";
743: }
744: return 'ok';
745: }
746: # Validate a line in a configuration file edit script:
747: # Validation includes:
748: # - Ensuring the command is valid.
749: # - Ensuring the command has sufficient parameters
750: # Parameters:
751: # scriptline - A line to validate (\n has been stripped for what it's worth).
752: #
753: # Return:
754: # 0 - Invalid scriptline.
755: # 1 - Valid scriptline
756: # NOTE:
757: # Only the command syntax is checked, not the executability of the
758: # command.
759: #
760: sub isValidEditCommand {
761: my $scriptline = shift;
762:
763: # Line elements are pipe separated:
764:
765: my ($command, $key, $newline) = split(/\|/, $scriptline);
766: &logthis('<font color="green"> isValideditCommand checking: '.
767: "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
768:
769: if ($command eq "delete") {
770: #
771: # key with no newline.
772: #
773: if( ($key eq "") || ($newline ne "")) {
774: return 0; # Must have key but no newline.
775: } else {
776: return 1; # Valid syntax.
777: }
778: } elsif ($command eq "replace") {
779: #
780: # key and newline:
781: #
782: if (($key eq "") || ($newline eq "")) {
783: return 0;
784: } else {
785: return 1;
786: }
787: } elsif ($command eq "append") {
788: if (($key ne "") && ($newline eq "")) {
789: return 1;
790: } else {
791: return 0;
792: }
793: } else {
794: return 0; # Invalid command.
795: }
796: return 0; # Should not get here!!!
797: }
798: #
799: # ApplyEdit - Applies an edit command to a line in a configuration
800: # file. It is the caller's responsiblity to validate the
801: # edit line.
802: # Parameters:
803: # $directive - A single edit directive to apply.
804: # Edit directives are of the form:
805: # append|newline - Appends a new line to the file.
806: # replace|key|newline - Replaces the line with key value 'key'
807: # delete|key - Deletes the line with key value 'key'.
808: # $editor - A config file editor object that contains the
809: # file being edited.
810: #
811: sub ApplyEdit {
812:
813: my ($directive, $editor) = @_;
814:
815: # Break the directive down into its command and its parameters
816: # (at most two at this point. The meaning of the parameters, if in fact
817: # they exist depends on the command).
818:
819: my ($command, $p1, $p2) = split(/\|/, $directive);
820:
821: if($command eq "append") {
822: $editor->Append($p1); # p1 - key p2 null.
823: } elsif ($command eq "replace") {
824: $editor->ReplaceLine($p1, $p2); # p1 - key p2 = newline.
825: } elsif ($command eq "delete") {
826: $editor->DeleteLine($p1); # p1 - key p2 null.
827: } else { # Should not get here!!!
828: die "Invalid command given to ApplyEdit $command"
829: }
830: }
831: #
832: # AdjustOurHost:
833: # Adjusts a host file stored in a configuration file editor object
834: # for the true IP address of this host. This is necessary for hosts
835: # that live behind a firewall.
836: # Those hosts have a publicly distributed IP of the firewall, but
837: # internally must use their actual IP. We assume that a given
838: # host only has a single IP interface for now.
839: # Formal Parameters:
840: # editor - The configuration file editor to adjust. This
841: # editor is assumed to contain a hosts.tab file.
842: # Strategy:
843: # - Figure out our hostname.
844: # - Lookup the entry for this host.
845: # - Modify the line to contain our IP
846: # - Do a replace for this host.
847: sub AdjustOurHost {
848: my $editor = shift;
849:
850: # figure out who I am.
851:
852: my $myHostName = $perlvar{'lonHostID'}; # LonCAPA hostname.
853:
854: # Get my host file entry.
855:
856: my $ConfigLine = $editor->Find($myHostName);
857: if(! (defined $ConfigLine)) {
858: die "AdjustOurHost - no entry for me in hosts file $myHostName";
859: }
860: # figure out my IP:
861: # Use the config line to get my hostname.
862: # Use gethostbyname to translate that into an IP address.
863: #
864: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
865: my $BinaryIp = gethostbyname($name);
866: my $ip = inet_ntoa($ip);
867: #
868: # Reassemble the config line from the elements in the list.
869: # Note that if the loncnew items were not present before, they will
870: # be now even if they would be empty
871: #
872: my $newConfigLine = $id;
873: foreach my $item ($domain, $role, $name, $ip, $maxcon, $idleto, $mincon) {
874: $newConfigLine .= ":".$item;
875: }
876: # Replace the line:
877:
878: $editor->ReplaceLine($id, $newConfigLine);
879:
880: }
881: #
882: # ReplaceConfigFile:
883: # Replaces a configuration file with the contents of a
884: # configuration file editor object.
885: # This is done by:
886: # - Copying the target file to <filename>.old
887: # - Writing the new file to <filename>.tmp
888: # - Moving <filename.tmp> -> <filename>
889: # This laborious process ensures that the system is never without
890: # a configuration file that's at least valid (even if the contents
891: # may be dated).
892: # Parameters:
893: # filename - Name of the file to modify... this is a full path.
894: # editor - Editor containing the file.
895: #
896: sub ReplaceConfigFile {
897:
898: my ($filename, $editor) = @_;
899:
900: CopyFile ($filename, $filename.".old");
901:
902: my $contents = $editor->Get(); # Get the contents of the file.
903:
904: InstallFile($filename, $contents);
905: }
906: #
907: #
908: # Called to edit a configuration table file
909: # Parameters:
910: # request - The entire command/request sent by lonc or lonManage
911: # Return:
912: # The reply to send to the client.
913: #
914: sub EditFile {
915: my $request = shift;
916:
917: # Split the command into it's pieces: edit:filetype:script
918:
919: my ($request, $filetype, $script) = split(/:/, $request,3); # : in script
920:
921: # Check the pre-coditions for success:
922:
923: if($request != "edit") { # Something is amiss afoot alack.
924: return "error:edit request detected, but request != 'edit'\n";
925: }
926: if( ($filetype ne "hosts") &&
927: ($filetype ne "domain")) {
928: return "error:edit requested with invalid file specifier: $filetype \n";
929: }
930:
931: # Split the edit script and check it's validity.
932:
933: my @scriptlines = split(/\n/, $script); # one line per element.
934: my $linecount = scalar(@scriptlines);
935: for(my $i = 0; $i < $linecount; $i++) {
936: chomp($scriptlines[$i]);
937: if(!isValidEditCommand($scriptlines[$i])) {
938: return "error:edit with bad script line: '$scriptlines[$i]' \n";
939: }
940: }
941:
942: # Execute the edit operation.
943: # - Create a config file editor for the appropriate file and
944: # - execute each command in the script:
945: #
946: my $configfile = ConfigFileFromSelector($filetype);
947: if (!(defined $configfile)) {
948: return "refused\n";
949: }
950: my $editor = ConfigFileEdit->new($configfile);
951:
952: for (my $i = 0; $i < $linecount; $i++) {
953: ApplyEdit($scriptlines[$i], $editor);
954: }
955: # If the file is the host file, ensure that our host is
956: # adjusted to have our ip:
957: #
958: if($filetype eq "host") {
959: AdjustOurHost($editor);
960: }
961: # Finally replace the current file with our file.
962: #
963: ReplaceConfigFile($configfile, $editor);
964:
965: return "ok\n";
966: }
967:
968: #---------------------------------------------------------------
969: #
970: # Manipulation of hash based databases (factoring out common code
971: # for later use as we refactor.
972: #
973: # Ties a domain level resource file to a hash.
974: # If requested a history entry is created in the associated hist file.
975: #
976: # Parameters:
977: # domain - Name of the domain in which the resource file lives.
978: # namespace - Name of the hash within that domain.
979: # how - How to tie the hash (e.g. GDBM_WRCREAT()).
980: # loghead - Optional parameter, if present a log entry is created
981: # in the associated history file and this is the first part
982: # of that entry.
983: # logtail - Goes along with loghead, The actual logentry is of the
984: # form $loghead:<timestamp>:logtail.
985: # Returns:
986: # Reference to a hash bound to the db file or alternatively undef
987: # if the tie failed.
988: #
989: sub tie_domain_hash {
990: my ($domain,$namespace,$how,$loghead,$logtail) = @_;
991:
992: # Filter out any whitespace in the domain name:
993:
994: $domain =~ s/\W//g;
995:
996: # We have enough to go on to tie the hash:
997:
998: my $user_top_dir = $perlvar{'lonUsersDir'};
999: my $domain_dir = $user_top_dir."/$domain";
1000: my $resource_file = $domain_dir."/$namespace.db";
1001: my %hash;
1002: if(tie(%hash, 'GDBM_File', $resource_file, $how, 0640)) {
1003: if (defined($loghead)) { # Need to log the operation.
1004: my $logFh = IO::File->new(">>$domain_dir/$namespace.hist");
1005: if($logFh) {
1006: my $timestamp = time;
1007: print $logFh "$loghead:$timestamp:$logtail\n";
1008: }
1009: $logFh->close;
1010: }
1011: return \%hash; # Return the tied hash.
1012: } else {
1013: return undef; # Tie failed.
1014: }
1015: }
1016:
1017: #
1018: # Ties a user's resource file to a hash.
1019: # If necessary, an appropriate history
1020: # log file entry is made as well.
1021: # This sub factors out common code from the subs that manipulate
1022: # the various gdbm files that keep keyword value pairs.
1023: # Parameters:
1024: # domain - Name of the domain the user is in.
1025: # user - Name of the 'current user'.
1026: # namespace - Namespace representing the file to tie.
1027: # how - What the tie is done to (e.g. GDBM_WRCREAT().
1028: # loghead - Optional first part of log entry if there may be a
1029: # history file.
1030: # what - Optional tail of log entry if there may be a history
1031: # file.
1032: # Returns:
1033: # hash to which the database is tied. It's up to the caller to untie.
1034: # undef if the has could not be tied.
1035: #
1036: sub tie_user_hash {
1037: my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
1038:
1039: $namespace=~s/\//\_/g; # / -> _
1040: $namespace=~s/\W//g; # whitespace eliminated.
1041: my $proname = propath($domain, $user);
1042:
1043: # Tie the database.
1044:
1045: my %hash;
1046: if(tie(%hash, 'GDBM_File', "$proname/$namespace.db",
1047: $how, 0640)) {
1048: # If this is a namespace for which a history is kept,
1049: # make the history log entry:
1050: if (($namespace !~/^nohist\_/) && (defined($loghead))) {
1051: my $args = scalar @_;
1052: Debug(" Opening history: $namespace $args");
1053: my $hfh = IO::File->new(">>$proname/$namespace.hist");
1054: if($hfh) {
1055: my $now = time;
1056: print $hfh "$loghead:$now:$what\n";
1057: }
1058: $hfh->close;
1059: }
1060: return \%hash;
1061: } else {
1062: return undef;
1063: }
1064:
1065: }
1066:
1067: # read_profile
1068: #
1069: # Returns a set of specific entries from a user's profile file.
1070: # this is a utility function that is used by both get_profile_entry and
1071: # get_profile_entry_encrypted.
1072: #
1073: # Parameters:
1074: # udom - Domain in which the user exists.
1075: # uname - User's account name (loncapa account)
1076: # namespace - The profile namespace to open.
1077: # what - A set of & separated queries.
1078: # Returns:
1079: # If all ok: - The string that needs to be shipped back to the user.
1080: # If failure - A string that starts with error: followed by the failure
1081: # reason.. note that this probabyl gets shipped back to the
1082: # user as well.
1083: #
1084: sub read_profile {
1085: my ($udom, $uname, $namespace, $what) = @_;
1086:
1087: my $hashref = &tie_user_hash($udom, $uname, $namespace,
1088: &GDBM_READER());
1089: if ($hashref) {
1090: my @queries=split(/\&/,$what);
1091: my $qresult='';
1092:
1093: for (my $i=0;$i<=$#queries;$i++) {
1094: $qresult.="$hashref->{$queries[$i]}&"; # Presumably failure gives empty string.
1095: }
1096: $qresult=~s/\&$//; # Remove trailing & from last lookup.
1097: if (untie %$hashref) {
1098: return $qresult;
1099: } else {
1100: return "error: ".($!+0)." untie (GDBM) Failed";
1101: }
1102: } else {
1103: if ($!+0 == 2) {
1104: return "error:No such file or GDBM reported bad block error";
1105: } else {
1106: return "error: ".($!+0)." tie (GDBM) Failed";
1107: }
1108: }
1109:
1110: }
1111: #--------------------- Request Handlers --------------------------------------------
1112: #
1113: # By convention each request handler registers itself prior to the sub
1114: # declaration:
1115: #
1116:
1117: #++
1118: #
1119: # Handles ping requests.
1120: # Parameters:
1121: # $cmd - the actual keyword that invoked us.
1122: # $tail - the tail of the request that invoked us.
1123: # $replyfd- File descriptor connected to the client
1124: # Implicit Inputs:
1125: # $currenthostid - Global variable that carries the name of the host we are
1126: # known as.
1127: # Returns:
1128: # 1 - Ok to continue processing.
1129: # 0 - Program should exit.
1130: # Side effects:
1131: # Reply information is sent to the client.
1132: sub ping_handler {
1133: my ($cmd, $tail, $client) = @_;
1134: Debug("$cmd $tail $client .. $currenthostid:");
1135:
1136: Reply( $client,"$currenthostid\n","$cmd:$tail");
1137:
1138: return 1;
1139: }
1140: ®ister_handler("ping", \&ping_handler, 0, 1, 1); # Ping unencoded, client or manager.
1141:
1142: #++
1143: #
1144: # Handles pong requests. Pong replies with our current host id, and
1145: # the results of a ping sent to us via our lonc.
1146: #
1147: # Parameters:
1148: # $cmd - the actual keyword that invoked us.
1149: # $tail - the tail of the request that invoked us.
1150: # $replyfd- File descriptor connected to the client
1151: # Implicit Inputs:
1152: # $currenthostid - Global variable that carries the name of the host we are
1153: # connected to.
1154: # Returns:
1155: # 1 - Ok to continue processing.
1156: # 0 - Program should exit.
1157: # Side effects:
1158: # Reply information is sent to the client.
1159: sub pong_handler {
1160: my ($cmd, $tail, $replyfd) = @_;
1161:
1162: my $reply=&reply("ping",$clientname);
1163: &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail");
1164: return 1;
1165: }
1166: ®ister_handler("pong", \&pong_handler, 0, 1, 1); # Pong unencoded, client or manager
1167:
1168: #++
1169: # Called to establish an encrypted session key with the remote client.
1170: # Note that with secure lond, in most cases this function is never
1171: # invoked. Instead, the secure session key is established either
1172: # via a local file that's locked down tight and only lives for a short
1173: # time, or via an ssl tunnel...and is generated from a bunch-o-random
1174: # bits from /dev/urandom, rather than the predictable pattern used by
1175: # by this sub. This sub is only used in the old-style insecure
1176: # key negotiation.
1177: # Parameters:
1178: # $cmd - the actual keyword that invoked us.
1179: # $tail - the tail of the request that invoked us.
1180: # $replyfd- File descriptor connected to the client
1181: # Implicit Inputs:
1182: # $currenthostid - Global variable that carries the name of the host
1183: # known as.
1184: # $clientname - Global variable that carries the name of the hsot we're connected to.
1185: # Returns:
1186: # 1 - Ok to continue processing.
1187: # 0 - Program should exit.
1188: # Implicit Outputs:
1189: # Reply information is sent to the client.
1190: # $cipher is set with a reference to a new IDEA encryption object.
1191: #
1192: sub establish_key_handler {
1193: my ($cmd, $tail, $replyfd) = @_;
1194:
1195: my $buildkey=time.$$.int(rand 100000);
1196: $buildkey=~tr/1-6/A-F/;
1197: $buildkey=int(rand 100000).$buildkey.int(rand 100000);
1198: my $key=$currenthostid.$clientname;
1199: $key=~tr/a-z/A-Z/;
1200: $key=~tr/G-P/0-9/;
1201: $key=~tr/Q-Z/0-9/;
1202: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
1203: $key=substr($key,0,32);
1204: my $cipherkey=pack("H32",$key);
1205: $cipher=new IDEA $cipherkey;
1206: &Reply($replyfd, "$buildkey\n", "$cmd:$tail");
1207:
1208: return 1;
1209:
1210: }
1211: ®ister_handler("ekey", \&establish_key_handler, 0, 1,1);
1212:
1213: # Handler for the load command. Returns the current system load average
1214: # to the requestor.
1215: #
1216: # Parameters:
1217: # $cmd - the actual keyword that invoked us.
1218: # $tail - the tail of the request that invoked us.
1219: # $replyfd- File descriptor connected to the client
1220: # Implicit Inputs:
1221: # $currenthostid - Global variable that carries the name of the host
1222: # known as.
1223: # $clientname - Global variable that carries the name of the hsot we're connected to.
1224: # Returns:
1225: # 1 - Ok to continue processing.
1226: # 0 - Program should exit.
1227: # Side effects:
1228: # Reply information is sent to the client.
1229: sub load_handler {
1230: my ($cmd, $tail, $replyfd) = @_;
1231:
1232: # Get the load average from /proc/loadavg and calculate it as a percentage of
1233: # the allowed load limit as set by the perl global variable lonLoadLim
1234:
1235: my $loadavg;
1236: my $loadfile=IO::File->new('/proc/loadavg');
1237:
1238: $loadavg=<$loadfile>;
1239: $loadavg =~ s/\s.*//g; # Extract the first field only.
1240:
1241: my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
1242:
1243: &Reply( $replyfd, "$loadpercent\n", "$cmd:$tail");
1244:
1245: return 1;
1246: }
1247: ®ister_handler("load", \&load_handler, 0, 1, 0);
1248:
1249: #
1250: # Process the userload request. This sub returns to the client the current
1251: # user load average. It can be invoked either by clients or managers.
1252: #
1253: # Parameters:
1254: # $cmd - the actual keyword that invoked us.
1255: # $tail - the tail of the request that invoked us.
1256: # $replyfd- File descriptor connected to the client
1257: # Implicit Inputs:
1258: # $currenthostid - Global variable that carries the name of the host
1259: # known as.
1260: # $clientname - Global variable that carries the name of the hsot we're connected to.
1261: # Returns:
1262: # 1 - Ok to continue processing.
1263: # 0 - Program should exit
1264: # Implicit inputs:
1265: # whatever the userload() function requires.
1266: # Implicit outputs:
1267: # the reply is written to the client.
1268: #
1269: sub user_load_handler {
1270: my ($cmd, $tail, $replyfd) = @_;
1271:
1272: my $userloadpercent=&userload();
1273: &Reply($replyfd, "$userloadpercent\n", "$cmd:$tail");
1274:
1275: return 1;
1276: }
1277: ®ister_handler("userload", \&user_load_handler, 0, 1, 0);
1278:
1279: # Process a request for the authorization type of a user:
1280: # (userauth).
1281: #
1282: # Parameters:
1283: # $cmd - the actual keyword that invoked us.
1284: # $tail - the tail of the request that invoked us.
1285: # $replyfd- File descriptor connected to the client
1286: # Returns:
1287: # 1 - Ok to continue processing.
1288: # 0 - Program should exit
1289: # Implicit outputs:
1290: # The user authorization type is written to the client.
1291: #
1292: sub user_authorization_type {
1293: my ($cmd, $tail, $replyfd) = @_;
1294:
1295: my $userinput = "$cmd:$tail";
1296:
1297: # Pull the domain and username out of the command tail.
1298: # and call get_auth_type to determine the authentication type.
1299:
1300: my ($udom,$uname)=split(/:/,$tail);
1301: my $result = &get_auth_type($udom, $uname);
1302: if($result eq "nouser") {
1303: &Failure( $replyfd, "unknown_user\n", $userinput);
1304: } else {
1305: #
1306: # We only want to pass the second field from get_auth_type
1307: # for ^krb.. otherwise we'll be handing out the encrypted
1308: # password for internals e.g.
1309: #
1310: my ($type,$otherinfo) = split(/:/,$result);
1311: if($type =~ /^krb/) {
1312: $type = $result;
1313: } else {
1314: $type .= ':';
1315: }
1316: &Reply( $replyfd, "$type\n", $userinput);
1317: }
1318:
1319: return 1;
1320: }
1321: ®ister_handler("currentauth", \&user_authorization_type, 1, 1, 0);
1322:
1323: # Process a request by a manager to push a hosts or domain table
1324: # to us. We pick apart the command and pass it on to the subs
1325: # that already exist to do this.
1326: #
1327: # Parameters:
1328: # $cmd - the actual keyword that invoked us.
1329: # $tail - the tail of the request that invoked us.
1330: # $client - File descriptor connected to the client
1331: # Returns:
1332: # 1 - Ok to continue processing.
1333: # 0 - Program should exit
1334: # Implicit Output:
1335: # a reply is written to the client.
1336: sub push_file_handler {
1337: my ($cmd, $tail, $client) = @_;
1338:
1339: my $userinput = "$cmd:$tail";
1340:
1341: # At this time we only know that the IP of our partner is a valid manager
1342: # the code below is a hook to do further authentication (e.g. to resolve
1343: # spoofing).
1344:
1345: my $cert = &GetCertificate($userinput);
1346: if(&ValidManager($cert)) {
1347:
1348: # Now presumably we have the bona fides of both the peer host and the
1349: # process making the request.
1350:
1351: my $reply = &PushFile($userinput);
1352: &Reply($client, "$reply\n", $userinput);
1353:
1354: } else {
1355: &Failure( $client, "refused\n", $userinput);
1356: }
1357: return 1;
1358: }
1359: ®ister_handler("pushfile", \&push_file_handler, 1, 0, 1);
1360:
1361: #
1362: # du - list the disk usuage of a directory recursively.
1363: #
1364: # note: stolen code from the ls file handler
1365: # under construction by Rick Banghart
1366: # .
1367: # Parameters:
1368: # $cmd - The command that dispatched us (du).
1369: # $ududir - The directory path to list... I'm not sure what this
1370: # is relative as things like ls:. return e.g.
1371: # no_such_dir.
1372: # $client - Socket open on the client.
1373: # Returns:
1374: # 1 - indicating that the daemon should not disconnect.
1375: # Side Effects:
1376: # The reply is written to $client.
1377: #
1378: sub du_handler {
1379: my ($cmd, $ududir, $client) = @_;
1380: my ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1381: my $userinput = "$cmd:$ududir";
1382:
1383: if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
1384: &Failure($client,"refused\n","$cmd:$ududir");
1385: return 1;
1386: }
1387: # Since $ududir could have some nasties in it,
1388: # we will require that ududir is a valid
1389: # directory. Just in case someone tries to
1390: # slip us a line like .;(cd /home/httpd rm -rf*)
1391: # etc.
1392: #
1393: if (-d $ududir) {
1394: # And as Shakespeare would say to make
1395: # assurance double sure,
1396: # use execute_command to ensure that the command is not executed in
1397: # a shell that can screw us up.
1398:
1399: my $duout = execute_command("du -ks $ududir");
1400: $duout=~s/[^\d]//g; #preserve only the numbers
1401: &Reply($client,"$duout\n","$cmd:$ududir");
1402: } else {
1403:
1404: &Failure($client, "bad_directory:$ududir\n","$cmd:$ududir");
1405:
1406: }
1407: return 1;
1408: }
1409: ®ister_handler("du", \&du_handler, 0, 1, 0);
1410:
1411: #
1412: # The ls_handler routine should be considered obosolete and is retained
1413: # for communication with legacy servers. Please see the ls2_handler.
1414: #
1415: # ls - list the contents of a directory. For each file in the
1416: # selected directory the filename followed by the full output of
1417: # the stat function is returned. The returned info for each
1418: # file are separated by ':'. The stat fields are separated by &'s.
1419: # Parameters:
1420: # $cmd - The command that dispatched us (ls).
1421: # $ulsdir - The directory path to list... I'm not sure what this
1422: # is relative as things like ls:. return e.g.
1423: # no_such_dir.
1424: # $client - Socket open on the client.
1425: # Returns:
1426: # 1 - indicating that the daemon should not disconnect.
1427: # Side Effects:
1428: # The reply is written to $client.
1429: #
1430: sub ls_handler {
1431: # obsoleted by ls2_handler
1432: my ($cmd, $ulsdir, $client) = @_;
1433:
1434: my $userinput = "$cmd:$ulsdir";
1435:
1436: my $obs;
1437: my $rights;
1438: my $ulsout='';
1439: my $ulsfn;
1440: if (-e $ulsdir) {
1441: if(-d $ulsdir) {
1442: if (opendir(LSDIR,$ulsdir)) {
1443: while ($ulsfn=readdir(LSDIR)) {
1444: undef $obs, $rights;
1445: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1446: #We do some obsolete checking here
1447: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1448: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1449: my @obsolete=<FILE>;
1450: foreach my $obsolete (@obsolete) {
1451: if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; }
1452: if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
1453: }
1454: }
1455: $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
1456: if($obs eq '1') { $ulsout.="&1"; }
1457: else { $ulsout.="&0"; }
1458: if($rights eq '1') { $ulsout.="&1:"; }
1459: else { $ulsout.="&0:"; }
1460: }
1461: closedir(LSDIR);
1462: }
1463: } else {
1464: my @ulsstats=stat($ulsdir);
1465: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1466: }
1467: } else {
1468: $ulsout='no_such_dir';
1469: }
1470: if ($ulsout eq '') { $ulsout='empty'; }
1471: &Reply($client, "$ulsout\n", $userinput); # This supports debug logging.
1472:
1473: return 1;
1474:
1475: }
1476: ®ister_handler("ls", \&ls_handler, 0, 1, 0);
1477:
1478: #
1479: # Please also see the ls_handler, which this routine obosolets.
1480: # ls2_handler differs from ls_handler in that it escapes its return
1481: # values before concatenating them together with ':'s.
1482: #
1483: # ls2 - list the contents of a directory. For each file in the
1484: # selected directory the filename followed by the full output of
1485: # the stat function is returned. The returned info for each
1486: # file are separated by ':'. The stat fields are separated by &'s.
1487: # Parameters:
1488: # $cmd - The command that dispatched us (ls).
1489: # $ulsdir - The directory path to list... I'm not sure what this
1490: # is relative as things like ls:. return e.g.
1491: # no_such_dir.
1492: # $client - Socket open on the client.
1493: # Returns:
1494: # 1 - indicating that the daemon should not disconnect.
1495: # Side Effects:
1496: # The reply is written to $client.
1497: #
1498: sub ls2_handler {
1499: my ($cmd, $ulsdir, $client) = @_;
1500:
1501: my $userinput = "$cmd:$ulsdir";
1502:
1503: my $obs;
1504: my $rights;
1505: my $ulsout='';
1506: my $ulsfn;
1507: if (-e $ulsdir) {
1508: if(-d $ulsdir) {
1509: if (opendir(LSDIR,$ulsdir)) {
1510: while ($ulsfn=readdir(LSDIR)) {
1511: undef $obs, $rights;
1512: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1513: #We do some obsolete checking here
1514: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1515: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1516: my @obsolete=<FILE>;
1517: foreach my $obsolete (@obsolete) {
1518: if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; }
1519: if($obsolete =~ m|(<copyright>)(default)|) {
1520: $rights = 1;
1521: }
1522: }
1523: }
1524: my $tmp = $ulsfn.'&'.join('&',@ulsstats);
1525: if ($obs eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1526: if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1527: $ulsout.= &escape($tmp).':';
1528: }
1529: closedir(LSDIR);
1530: }
1531: } else {
1532: my @ulsstats=stat($ulsdir);
1533: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1534: }
1535: } else {
1536: $ulsout='no_such_dir';
1537: }
1538: if ($ulsout eq '') { $ulsout='empty'; }
1539: &Reply($client, "$ulsout\n", $userinput); # This supports debug logging.
1540: return 1;
1541: }
1542: ®ister_handler("ls2", \&ls2_handler, 0, 1, 0);
1543:
1544: # Process a reinit request. Reinit requests that either
1545: # lonc or lond be reinitialized so that an updated
1546: # host.tab or domain.tab can be processed.
1547: #
1548: # Parameters:
1549: # $cmd - the actual keyword that invoked us.
1550: # $tail - the tail of the request that invoked us.
1551: # $client - File descriptor connected to the client
1552: # Returns:
1553: # 1 - Ok to continue processing.
1554: # 0 - Program should exit
1555: # Implicit output:
1556: # a reply is sent to the client.
1557: #
1558: sub reinit_process_handler {
1559: my ($cmd, $tail, $client) = @_;
1560:
1561: my $userinput = "$cmd:$tail";
1562:
1563: my $cert = &GetCertificate($userinput);
1564: if(&ValidManager($cert)) {
1565: chomp($userinput);
1566: my $reply = &ReinitProcess($userinput);
1567: &Reply( $client, "$reply\n", $userinput);
1568: } else {
1569: &Failure( $client, "refused\n", $userinput);
1570: }
1571: return 1;
1572: }
1573: ®ister_handler("reinit", \&reinit_process_handler, 1, 0, 1);
1574:
1575: # Process the editing script for a table edit operation.
1576: # the editing operation must be encrypted and requested by
1577: # a manager host.
1578: #
1579: # Parameters:
1580: # $cmd - the actual keyword that invoked us.
1581: # $tail - the tail of the request that invoked us.
1582: # $client - File descriptor connected to the client
1583: # Returns:
1584: # 1 - Ok to continue processing.
1585: # 0 - Program should exit
1586: # Implicit output:
1587: # a reply is sent to the client.
1588: #
1589: sub edit_table_handler {
1590: my ($command, $tail, $client) = @_;
1591:
1592: my $userinput = "$command:$tail";
1593:
1594: my $cert = &GetCertificate($userinput);
1595: if(&ValidManager($cert)) {
1596: my($filetype, $script) = split(/:/, $tail);
1597: if (($filetype eq "hosts") ||
1598: ($filetype eq "domain")) {
1599: if($script ne "") {
1600: &Reply($client, # BUGBUG - EditFile
1601: &EditFile($userinput), # could fail.
1602: $userinput);
1603: } else {
1604: &Failure($client,"refused\n",$userinput);
1605: }
1606: } else {
1607: &Failure($client,"refused\n",$userinput);
1608: }
1609: } else {
1610: &Failure($client,"refused\n",$userinput);
1611: }
1612: return 1;
1613: }
1614: ®ister_handler("edit", \&edit_table_handler, 1, 0, 1);
1615:
1616: #
1617: # Authenticate a user against the LonCAPA authentication
1618: # database. Note that there are several authentication
1619: # possibilities:
1620: # - unix - The user can be authenticated against the unix
1621: # password file.
1622: # - internal - The user can be authenticated against a purely
1623: # internal per user password file.
1624: # - kerberos - The user can be authenticated against either a kerb4 or kerb5
1625: # ticket granting authority.
1626: # - user - The person tailoring LonCAPA can supply a user authentication
1627: # mechanism that is per system.
1628: #
1629: # Parameters:
1630: # $cmd - The command that got us here.
1631: # $tail - Tail of the command (remaining parameters).
1632: # $client - File descriptor connected to client.
1633: # Returns
1634: # 0 - Requested to exit, caller should shut down.
1635: # 1 - Continue processing.
1636: # Implicit inputs:
1637: # The authentication systems describe above have their own forms of implicit
1638: # input into the authentication process that are described above.
1639: #
1640: sub authenticate_handler {
1641: my ($cmd, $tail, $client) = @_;
1642:
1643:
1644: # Regenerate the full input line
1645:
1646: my $userinput = $cmd.":".$tail;
1647:
1648: # udom - User's domain.
1649: # uname - Username.
1650: # upass - User's password.
1651:
1652: my ($udom,$uname,$upass)=split(/:/,$tail);
1653: &Debug(" Authenticate domain = $udom, user = $uname, password = $upass");
1654: chomp($upass);
1655: $upass=&unescape($upass);
1656:
1657: my $pwdcorrect = &validate_user($udom, $uname, $upass);
1658: if($pwdcorrect) {
1659: &Reply( $client, "authorized\n", $userinput);
1660: #
1661: # Bad credentials: Failed to authorize
1662: #
1663: } else {
1664: &Failure( $client, "non_authorized\n", $userinput);
1665: }
1666:
1667: return 1;
1668: }
1669: ®ister_handler("auth", \&authenticate_handler, 1, 1, 0);
1670:
1671: #
1672: # Change a user's password. Note that this function is complicated by
1673: # the fact that a user may be authenticated in more than one way:
1674: # At present, we are not able to change the password for all types of
1675: # authentication methods. Only for:
1676: # unix - unix password or shadow passoword style authentication.
1677: # local - Locally written authentication mechanism.
1678: # For now, kerb4 and kerb5 password changes are not supported and result
1679: # in an error.
1680: # FUTURE WORK:
1681: # Support kerberos passwd changes?
1682: # Parameters:
1683: # $cmd - The command that got us here.
1684: # $tail - Tail of the command (remaining parameters).
1685: # $client - File descriptor connected to client.
1686: # Returns
1687: # 0 - Requested to exit, caller should shut down.
1688: # 1 - Continue processing.
1689: # Implicit inputs:
1690: # The authentication systems describe above have their own forms of implicit
1691: # input into the authentication process that are described above.
1692: sub change_password_handler {
1693: my ($cmd, $tail, $client) = @_;
1694:
1695: my $userinput = $cmd.":".$tail; # Reconstruct client's string.
1696:
1697: #
1698: # udom - user's domain.
1699: # uname - Username.
1700: # upass - Current password.
1701: # npass - New password.
1702:
1703: my ($udom,$uname,$upass,$npass)=split(/:/,$tail);
1704:
1705: $upass=&unescape($upass);
1706: $npass=&unescape($npass);
1707: &Debug("Trying to change password for $uname");
1708:
1709: # First require that the user can be authenticated with their
1710: # old password:
1711:
1712: my $validated = &validate_user($udom, $uname, $upass);
1713: if($validated) {
1714: my $realpasswd = &get_auth_type($udom, $uname); # Defined since authd.
1715:
1716: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1717: if ($howpwd eq 'internal') {
1718: &Debug("internal auth");
1719: my $salt=time;
1720: $salt=substr($salt,6,2);
1721: my $ncpass=crypt($npass,$salt);
1722: if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1723: &logthis("Result of password change for "
1724: ."$uname: pwchange_success");
1725: &Reply($client, "ok\n", $userinput);
1726: } else {
1727: &logthis("Unable to open $uname passwd "
1728: ."to change password");
1729: &Failure( $client, "non_authorized\n",$userinput);
1730: }
1731: } elsif ($howpwd eq 'unix') {
1732: # Unix means we have to access /etc/password
1733: &Debug("auth is unix");
1734: my $execdir=$perlvar{'lonDaemons'};
1735: &Debug("Opening lcpasswd pipeline");
1736: my $pf = IO::File->new("|$execdir/lcpasswd > "
1737: ."$perlvar{'lonDaemons'}"
1738: ."/logs/lcpasswd.log");
1739: print $pf "$uname\n$npass\n$npass\n";
1740: close $pf;
1741: my $err = $?;
1742: my $result = ($err>0 ? 'pwchange_failure' : 'ok');
1743: &logthis("Result of password change for $uname: ".
1744: &lcpasswdstrerror($?));
1745: &Reply($client, "$result\n", $userinput);
1746: } else {
1747: # this just means that the current password mode is not
1748: # one we know how to change (e.g the kerberos auth modes or
1749: # locally written auth handler).
1750: #
1751: &Failure( $client, "auth_mode_error\n", $userinput);
1752: }
1753:
1754: } else {
1755: &Failure( $client, "non_authorized\n", $userinput);
1756: }
1757:
1758: return 1;
1759: }
1760: ®ister_handler("passwd", \&change_password_handler, 1, 1, 0);
1761:
1762: #
1763: # Create a new user. User in this case means a lon-capa user.
1764: # The user must either already exist in some authentication realm
1765: # like kerberos or the /etc/passwd. If not, a user completely local to
1766: # this loncapa system is created.
1767: #
1768: # Parameters:
1769: # $cmd - The command that got us here.
1770: # $tail - Tail of the command (remaining parameters).
1771: # $client - File descriptor connected to client.
1772: # Returns
1773: # 0 - Requested to exit, caller should shut down.
1774: # 1 - Continue processing.
1775: # Implicit inputs:
1776: # The authentication systems describe above have their own forms of implicit
1777: # input into the authentication process that are described above.
1778: sub add_user_handler {
1779:
1780: my ($cmd, $tail, $client) = @_;
1781:
1782:
1783: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
1784: my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
1785:
1786: &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
1787:
1788:
1789: if($udom eq $currentdomainid) { # Reject new users for other domains...
1790:
1791: my $oldumask=umask(0077);
1792: chomp($npass);
1793: $npass=&unescape($npass);
1794: my $passfilename = &password_path($udom, $uname);
1795: &Debug("Password file created will be:".$passfilename);
1796: if (-e $passfilename) {
1797: &Failure( $client, "already_exists\n", $userinput);
1798: } else {
1799: my $fperror='';
1800: if (!&mkpath($passfilename)) {
1801: $fperror="error: ".($!+0)." mkdir failed while attempting "
1802: ."makeuser";
1803: }
1804: unless ($fperror) {
1805: my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
1806: &Reply($client, $result, $userinput); #BUGBUG - could be fail
1807: } else {
1808: &Failure($client, "$fperror\n", $userinput);
1809: }
1810: }
1811: umask($oldumask);
1812: } else {
1813: &Failure($client, "not_right_domain\n",
1814: $userinput); # Even if we are multihomed.
1815:
1816: }
1817: return 1;
1818:
1819: }
1820: ®ister_handler("makeuser", \&add_user_handler, 1, 1, 0);
1821:
1822: #
1823: # Change the authentication method of a user. Note that this may
1824: # also implicitly change the user's password if, for example, the user is
1825: # joining an existing authentication realm. Known authentication realms at
1826: # this time are:
1827: # internal - Purely internal password file (only loncapa knows this user)
1828: # local - Institutionally written authentication module.
1829: # unix - Unix user (/etc/passwd with or without /etc/shadow).
1830: # kerb4 - kerberos version 4
1831: # kerb5 - kerberos version 5
1832: #
1833: # Parameters:
1834: # $cmd - The command that got us here.
1835: # $tail - Tail of the command (remaining parameters).
1836: # $client - File descriptor connected to client.
1837: # Returns
1838: # 0 - Requested to exit, caller should shut down.
1839: # 1 - Continue processing.
1840: # Implicit inputs:
1841: # The authentication systems describe above have their own forms of implicit
1842: # input into the authentication process that are described above.
1843: #
1844: sub change_authentication_handler {
1845:
1846: my ($cmd, $tail, $client) = @_;
1847:
1848: my $userinput = "$cmd:$tail"; # Reconstruct user input.
1849:
1850: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
1851: &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
1852: if ($udom ne $currentdomainid) {
1853: &Failure( $client, "not_right_domain\n", $client);
1854: } else {
1855:
1856: chomp($npass);
1857:
1858: $npass=&unescape($npass);
1859: my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1860: my $passfilename = &password_path($udom, $uname);
1861: if ($passfilename) { # Not allowed to create a new user!!
1862: my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
1863: #
1864: # If the current auth mode is internal, and the old auth mode was
1865: # unix, or krb*, and the user is an author for this domain,
1866: # re-run manage_permissions for that role in order to be able
1867: # to take ownership of the construction space back to www:www
1868: #
1869:
1870: if( (($oldauth =~ /^unix/) && ($umode eq "internal")) ||
1871: (($oldauth =~ /^internal/) && ($umode eq "unix")) ) {
1872: if(&is_author($udom, $uname)) {
1873: &Debug(" Need to manage author permissions...");
1874: &manage_permissions("/$udom/_au", $udom, $uname, "$umode:");
1875: }
1876: }
1877:
1878:
1879: &Reply($client, $result, $userinput);
1880: } else {
1881: &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1882: }
1883: }
1884: return 1;
1885: }
1886: ®ister_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
1887:
1888: #
1889: # Determines if this is the home server for a user. The home server
1890: # for a user will have his/her lon-capa passwd file. Therefore all we need
1891: # to do is determine if this file exists.
1892: #
1893: # Parameters:
1894: # $cmd - The command that got us here.
1895: # $tail - Tail of the command (remaining parameters).
1896: # $client - File descriptor connected to client.
1897: # Returns
1898: # 0 - Requested to exit, caller should shut down.
1899: # 1 - Continue processing.
1900: # Implicit inputs:
1901: # The authentication systems describe above have their own forms of implicit
1902: # input into the authentication process that are described above.
1903: #
1904: sub is_home_handler {
1905: my ($cmd, $tail, $client) = @_;
1906:
1907: my $userinput = "$cmd:$tail";
1908:
1909: my ($udom,$uname)=split(/:/,$tail);
1910: chomp($uname);
1911: my $passfile = &password_filename($udom, $uname);
1912: if($passfile) {
1913: &Reply( $client, "found\n", $userinput);
1914: } else {
1915: &Failure($client, "not_found\n", $userinput);
1916: }
1917: return 1;
1918: }
1919: ®ister_handler("home", \&is_home_handler, 0,1,0);
1920:
1921: #
1922: # Process an update request for a resource?? I think what's going on here is
1923: # that a resource has been modified that we hold a subscription to.
1924: # If the resource is not local, then we must update, or at least invalidate our
1925: # cached copy of the resource.
1926: # FUTURE WORK:
1927: # I need to look at this logic carefully. My druthers would be to follow
1928: # typical caching logic, and simple invalidate the cache, drop any subscription
1929: # an let the next fetch start the ball rolling again... however that may
1930: # actually be more difficult than it looks given the complex web of
1931: # proxy servers.
1932: # Parameters:
1933: # $cmd - The command that got us here.
1934: # $tail - Tail of the command (remaining parameters).
1935: # $client - File descriptor connected to client.
1936: # Returns
1937: # 0 - Requested to exit, caller should shut down.
1938: # 1 - Continue processing.
1939: # Implicit inputs:
1940: # The authentication systems describe above have their own forms of implicit
1941: # input into the authentication process that are described above.
1942: #
1943: sub update_resource_handler {
1944:
1945: my ($cmd, $tail, $client) = @_;
1946:
1947: my $userinput = "$cmd:$tail";
1948:
1949: my $fname= $tail; # This allows interactive testing
1950:
1951:
1952: my $ownership=ishome($fname);
1953: if ($ownership eq 'not_owner') {
1954: if (-e $fname) {
1955: my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
1956: $atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
1957: my $now=time;
1958: my $since=$now-$atime;
1959: if ($since>$perlvar{'lonExpire'}) {
1960: my $reply=&reply("unsub:$fname","$clientname");
1961: unlink("$fname");
1962: } else {
1963: my $transname="$fname.in.transfer";
1964: my $remoteurl=&reply("sub:$fname","$clientname");
1965: my $response;
1966: alarm(120);
1967: {
1968: my $ua=new LWP::UserAgent;
1969: my $request=new HTTP::Request('GET',"$remoteurl");
1970: $response=$ua->request($request,$transname);
1971: }
1972: alarm(0);
1973: if ($response->is_error()) {
1974: unlink($transname);
1975: my $message=$response->status_line;
1976: &logthis("LWP GET: $message for $fname ($remoteurl)");
1977: } else {
1978: if ($remoteurl!~/\.meta$/) {
1979: alarm(120);
1980: {
1981: my $ua=new LWP::UserAgent;
1982: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1983: my $mresponse=$ua->request($mrequest,$fname.'.meta');
1984: if ($mresponse->is_error()) {
1985: unlink($fname.'.meta');
1986: }
1987: }
1988: alarm(0);
1989: }
1990: rename($transname,$fname);
1991: }
1992: }
1993: &Reply( $client, "ok\n", $userinput);
1994: } else {
1995: &Failure($client, "not_found\n", $userinput);
1996: }
1997: } else {
1998: &Failure($client, "rejected\n", $userinput);
1999: }
2000: return 1;
2001: }
2002: ®ister_handler("update", \&update_resource_handler, 0 ,1, 0);
2003:
2004: #
2005: # Fetch a user file from a remote server to the user's home directory
2006: # userfiles subdir.
2007: # Parameters:
2008: # $cmd - The command that got us here.
2009: # $tail - Tail of the command (remaining parameters).
2010: # $client - File descriptor connected to client.
2011: # Returns
2012: # 0 - Requested to exit, caller should shut down.
2013: # 1 - Continue processing.
2014: #
2015: sub fetch_user_file_handler {
2016:
2017: my ($cmd, $tail, $client) = @_;
2018:
2019: my $userinput = "$cmd:$tail";
2020: my $fname = $tail;
2021: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2022: my $udir=&propath($udom,$uname).'/userfiles';
2023: unless (-e $udir) {
2024: mkdir($udir,0770);
2025: }
2026: Debug("fetch user file for $fname");
2027: if (-e $udir) {
2028: $ufile=~s/^[\.\~]+//;
2029:
2030: # IF necessary, create the path right down to the file.
2031: # Note that any regular files in the way of this path are
2032: # wiped out to deal with some earlier folly of mine.
2033:
2034: if (!&mkpath($udir.'/'.$ufile)) {
2035: &Failure($client, "unable_to_create\n", $userinput);
2036: }
2037:
2038: my $destname=$udir.'/'.$ufile;
2039: my $transname=$udir.'/'.$ufile.'.in.transit';
2040: my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
2041: my $response;
2042: Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
2043: alarm(120);
2044: {
2045: my $ua=new LWP::UserAgent;
2046: my $request=new HTTP::Request('GET',"$remoteurl");
2047: $response=$ua->request($request,$transname);
2048: }
2049: alarm(0);
2050: if ($response->is_error()) {
2051: unlink($transname);
2052: my $message=$response->status_line;
2053: &logthis("LWP GET: $message for $fname ($remoteurl)");
2054: &Failure($client, "failed\n", $userinput);
2055: } else {
2056: Debug("Renaming $transname to $destname");
2057: if (!rename($transname,$destname)) {
2058: &logthis("Unable to move $transname to $destname");
2059: unlink($transname);
2060: &Failure($client, "failed\n", $userinput);
2061: } else {
2062: &Reply($client, "ok\n", $userinput);
2063: }
2064: }
2065: } else {
2066: &Failure($client, "not_home\n", $userinput);
2067: }
2068: return 1;
2069: }
2070: ®ister_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
2071:
2072: #
2073: # Remove a file from a user's home directory userfiles subdirectory.
2074: # Parameters:
2075: # cmd - the Lond request keyword that got us here.
2076: # tail - the part of the command past the keyword.
2077: # client- File descriptor connected with the client.
2078: #
2079: # Returns:
2080: # 1 - Continue processing.
2081: sub remove_user_file_handler {
2082: my ($cmd, $tail, $client) = @_;
2083:
2084: my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2085:
2086: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2087: if ($ufile =~m|/\.\./|) {
2088: # any files paths with /../ in them refuse
2089: # to deal with
2090: &Failure($client, "refused\n", "$cmd:$tail");
2091: } else {
2092: my $udir = &propath($udom,$uname);
2093: if (-e $udir) {
2094: my $file=$udir.'/userfiles/'.$ufile;
2095: if (-e $file) {
2096: #
2097: # If the file is a regular file unlink is fine...
2098: # However it's possible the client wants a dir.
2099: # removed, in which case rmdir is more approprate:
2100: #
2101: if (-f $file){
2102: unlink($file);
2103: } elsif(-d $file) {
2104: rmdir($file);
2105: }
2106: if (-e $file) {
2107: # File is still there after we deleted it ?!?
2108:
2109: &Failure($client, "failed\n", "$cmd:$tail");
2110: } else {
2111: &Reply($client, "ok\n", "$cmd:$tail");
2112: }
2113: } else {
2114: &Failure($client, "not_found\n", "$cmd:$tail");
2115: }
2116: } else {
2117: &Failure($client, "not_home\n", "$cmd:$tail");
2118: }
2119: }
2120: return 1;
2121: }
2122: ®ister_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
2123:
2124: #
2125: # make a directory in a user's home directory userfiles subdirectory.
2126: # Parameters:
2127: # cmd - the Lond request keyword that got us here.
2128: # tail - the part of the command past the keyword.
2129: # client- File descriptor connected with the client.
2130: #
2131: # Returns:
2132: # 1 - Continue processing.
2133: sub mkdir_user_file_handler {
2134: my ($cmd, $tail, $client) = @_;
2135:
2136: my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2137: $dir=&unescape($dir);
2138: my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
2139: if ($ufile =~m|/\.\./|) {
2140: # any files paths with /../ in them refuse
2141: # to deal with
2142: &Failure($client, "refused\n", "$cmd:$tail");
2143: } else {
2144: my $udir = &propath($udom,$uname);
2145: if (-e $udir) {
2146: my $newdir=$udir.'/userfiles/'.$ufile.'/';
2147: if (!&mkpath($newdir)) {
2148: &Failure($client, "failed\n", "$cmd:$tail");
2149: }
2150: &Reply($client, "ok\n", "$cmd:$tail");
2151: } else {
2152: &Failure($client, "not_home\n", "$cmd:$tail");
2153: }
2154: }
2155: return 1;
2156: }
2157: ®ister_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
2158:
2159: #
2160: # rename a file in a user's home directory userfiles subdirectory.
2161: # Parameters:
2162: # cmd - the Lond request keyword that got us here.
2163: # tail - the part of the command past the keyword.
2164: # client- File descriptor connected with the client.
2165: #
2166: # Returns:
2167: # 1 - Continue processing.
2168: sub rename_user_file_handler {
2169: my ($cmd, $tail, $client) = @_;
2170:
2171: my ($udom,$uname,$old,$new) = split(/:/, $tail);
2172: $old=&unescape($old);
2173: $new=&unescape($new);
2174: if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
2175: # any files paths with /../ in them refuse to deal with
2176: &Failure($client, "refused\n", "$cmd:$tail");
2177: } else {
2178: my $udir = &propath($udom,$uname);
2179: if (-e $udir) {
2180: my $oldfile=$udir.'/userfiles/'.$old;
2181: my $newfile=$udir.'/userfiles/'.$new;
2182: if (-e $newfile) {
2183: &Failure($client, "exists\n", "$cmd:$tail");
2184: } elsif (! -e $oldfile) {
2185: &Failure($client, "not_found\n", "$cmd:$tail");
2186: } else {
2187: if (!rename($oldfile,$newfile)) {
2188: &Failure($client, "failed\n", "$cmd:$tail");
2189: } else {
2190: &Reply($client, "ok\n", "$cmd:$tail");
2191: }
2192: }
2193: } else {
2194: &Failure($client, "not_home\n", "$cmd:$tail");
2195: }
2196: }
2197: return 1;
2198: }
2199: ®ister_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
2200:
2201: #
2202: # Authenticate access to a user file by checking that the token the user's
2203: # passed also exists in their session file
2204: #
2205: # Parameters:
2206: # cmd - The request keyword that dispatched to tus.
2207: # tail - The tail of the request (colon separated parameters).
2208: # client - Filehandle open on the client.
2209: # Return:
2210: # 1.
2211: sub token_auth_user_file_handler {
2212: my ($cmd, $tail, $client) = @_;
2213:
2214: my ($fname, $session) = split(/:/, $tail);
2215:
2216: chomp($session);
2217: my $reply="non_auth\n";
2218: if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
2219: $session.'.id')) {
2220: while (my $line=<ENVIN>) {
2221: if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply="ok\n"; }
2222: }
2223: close(ENVIN);
2224: &Reply($client, $reply, "$cmd:$tail");
2225: } else {
2226: &Failure($client, "invalid_token\n", "$cmd:$tail");
2227: }
2228: return 1;
2229:
2230: }
2231: ®ister_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
2232:
2233: #
2234: # Unsubscribe from a resource.
2235: #
2236: # Parameters:
2237: # $cmd - The command that got us here.
2238: # $tail - Tail of the command (remaining parameters).
2239: # $client - File descriptor connected to client.
2240: # Returns
2241: # 0 - Requested to exit, caller should shut down.
2242: # 1 - Continue processing.
2243: #
2244: sub unsubscribe_handler {
2245: my ($cmd, $tail, $client) = @_;
2246:
2247: my $userinput= "$cmd:$tail";
2248:
2249: my ($fname) = split(/:/,$tail); # Split in case there's extrs.
2250:
2251: &Debug("Unsubscribing $fname");
2252: if (-e $fname) {
2253: &Debug("Exists");
2254: &Reply($client, &unsub($fname,$clientip), $userinput);
2255: } else {
2256: &Failure($client, "not_found\n", $userinput);
2257: }
2258: return 1;
2259: }
2260: ®ister_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
2261:
2262: # Subscribe to a resource
2263: #
2264: # Parameters:
2265: # $cmd - The command that got us here.
2266: # $tail - Tail of the command (remaining parameters).
2267: # $client - File descriptor connected to client.
2268: # Returns
2269: # 0 - Requested to exit, caller should shut down.
2270: # 1 - Continue processing.
2271: #
2272: sub subscribe_handler {
2273: my ($cmd, $tail, $client)= @_;
2274:
2275: my $userinput = "$cmd:$tail";
2276:
2277: &Reply( $client, &subscribe($userinput,$clientip), $userinput);
2278:
2279: return 1;
2280: }
2281: ®ister_handler("sub", \&subscribe_handler, 0, 1, 0);
2282:
2283: #
2284: # Determine the version of a resource (?) Or is it return
2285: # the top version of the resource? Not yet clear from the
2286: # code in currentversion.
2287: #
2288: # Parameters:
2289: # $cmd - The command that got us here.
2290: # $tail - Tail of the command (remaining parameters).
2291: # $client - File descriptor connected to client.
2292: # Returns
2293: # 0 - Requested to exit, caller should shut down.
2294: # 1 - Continue processing.
2295: #
2296: sub current_version_handler {
2297: my ($cmd, $tail, $client) = @_;
2298:
2299: my $userinput= "$cmd:$tail";
2300:
2301: my $fname = $tail;
2302: &Reply( $client, ¤tversion($fname)."\n", $userinput);
2303: return 1;
2304:
2305: }
2306: ®ister_handler("currentversion", \¤t_version_handler, 0, 1, 0);
2307:
2308: # Make an entry in a user's activity log.
2309: #
2310: # Parameters:
2311: # $cmd - The command that got us here.
2312: # $tail - Tail of the command (remaining parameters).
2313: # $client - File descriptor connected to client.
2314: # Returns
2315: # 0 - Requested to exit, caller should shut down.
2316: # 1 - Continue processing.
2317: #
2318: sub activity_log_handler {
2319: my ($cmd, $tail, $client) = @_;
2320:
2321:
2322: my $userinput= "$cmd:$tail";
2323:
2324: my ($udom,$uname,$what)=split(/:/,$tail);
2325: chomp($what);
2326: my $proname=&propath($udom,$uname);
2327: my $now=time;
2328: my $hfh;
2329: if ($hfh=IO::File->new(">>$proname/activity.log")) {
2330: print $hfh "$now:$clientname:$what\n";
2331: &Reply( $client, "ok\n", $userinput);
2332: } else {
2333: &Failure($client, "error: ".($!+0)." IO::File->new Failed "
2334: ."while attempting log\n",
2335: $userinput);
2336: }
2337:
2338: return 1;
2339: }
2340: ®ister_handler("log", \&activity_log_handler, 0, 1, 0);
2341:
2342: #
2343: # Put a namespace entry in a user profile hash.
2344: # My druthers would be for this to be an encrypted interaction too.
2345: # anything that might be an inadvertent covert channel about either
2346: # user authentication or user personal information....
2347: #
2348: # Parameters:
2349: # $cmd - The command that got us here.
2350: # $tail - Tail of the command (remaining parameters).
2351: # $client - File descriptor connected to client.
2352: # Returns
2353: # 0 - Requested to exit, caller should shut down.
2354: # 1 - Continue processing.
2355: #
2356: sub put_user_profile_entry {
2357: my ($cmd, $tail, $client) = @_;
2358:
2359: my $userinput = "$cmd:$tail";
2360:
2361: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
2362: if ($namespace ne 'roles') {
2363: chomp($what);
2364: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2365: &GDBM_WRCREAT(),"P",$what);
2366: if($hashref) {
2367: my @pairs=split(/\&/,$what);
2368: foreach my $pair (@pairs) {
2369: my ($key,$value)=split(/=/,$pair);
2370: $hashref->{$key}=$value;
2371: }
2372: if (untie(%$hashref)) {
2373: &Reply( $client, "ok\n", $userinput);
2374: } else {
2375: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2376: "while attempting put\n",
2377: $userinput);
2378: }
2379: } else {
2380: &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
2381: "while attempting put\n", $userinput);
2382: }
2383: } else {
2384: &Failure( $client, "refused\n", $userinput);
2385: }
2386:
2387: return 1;
2388: }
2389: ®ister_handler("put", \&put_user_profile_entry, 0, 1, 0);
2390:
2391: #
2392: # Increment a profile entry in the user history file.
2393: # The history contains keyword value pairs. In this case,
2394: # The value itself is a pair of numbers. The first, the current value
2395: # the second an increment that this function applies to the current
2396: # value.
2397: #
2398: # Parameters:
2399: # $cmd - The command that got us here.
2400: # $tail - Tail of the command (remaining parameters).
2401: # $client - File descriptor connected to client.
2402: # Returns
2403: # 0 - Requested to exit, caller should shut down.
2404: # 1 - Continue processing.
2405: #
2406: sub increment_user_value_handler {
2407: my ($cmd, $tail, $client) = @_;
2408:
2409: my $userinput = "$cmd:$tail";
2410:
2411: my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
2412: if ($namespace ne 'roles') {
2413: chomp($what);
2414: my $hashref = &tie_user_hash($udom, $uname,
2415: $namespace, &GDBM_WRCREAT(),
2416: "P",$what);
2417: if ($hashref) {
2418: my @pairs=split(/\&/,$what);
2419: foreach my $pair (@pairs) {
2420: my ($key,$value)=split(/=/,$pair);
2421: # We could check that we have a number...
2422: if (! defined($value) || $value eq '') {
2423: $value = 1;
2424: }
2425: $hashref->{$key}+=$value;
2426: }
2427: if (untie(%$hashref)) {
2428: &Reply( $client, "ok\n", $userinput);
2429: } else {
2430: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2431: "while attempting inc\n", $userinput);
2432: }
2433: } else {
2434: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2435: "while attempting inc\n", $userinput);
2436: }
2437: } else {
2438: &Failure($client, "refused\n", $userinput);
2439: }
2440:
2441: return 1;
2442: }
2443: ®ister_handler("inc", \&increment_user_value_handler, 0, 1, 0);
2444:
2445: #
2446: # Put a new role for a user. Roles are LonCAPA's packaging of permissions.
2447: # Each 'role' a user has implies a set of permissions. Adding a new role
2448: # for a person grants the permissions packaged with that role
2449: # to that user when the role is selected.
2450: #
2451: # Parameters:
2452: # $cmd - The command string (rolesput).
2453: # $tail - The remainder of the request line. For rolesput this
2454: # consists of a colon separated list that contains:
2455: # The domain and user that is granting the role (logged).
2456: # The domain and user that is getting the role.
2457: # The roles being granted as a set of & separated pairs.
2458: # each pair a key value pair.
2459: # $client - File descriptor connected to the client.
2460: # Returns:
2461: # 0 - If the daemon should exit
2462: # 1 - To continue processing.
2463: #
2464: #
2465: sub roles_put_handler {
2466: my ($cmd, $tail, $client) = @_;
2467:
2468: my $userinput = "$cmd:$tail";
2469:
2470: my ( $exedom, $exeuser, $udom, $uname, $what) = split(/:/,$tail);
2471:
2472:
2473: my $namespace='roles';
2474: chomp($what);
2475: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2476: &GDBM_WRCREAT(), "P",
2477: "$exedom:$exeuser:$what");
2478: #
2479: # Log the attempt to set a role. The {}'s here ensure that the file
2480: # handle is open for the minimal amount of time. Since the flush
2481: # is done on close this improves the chances the log will be an un-
2482: # corrupted ordered thing.
2483: if ($hashref) {
2484: my $pass_entry = &get_auth_type($udom, $uname);
2485: my ($auth_type,$pwd) = split(/:/, $pass_entry);
2486: $auth_type = $auth_type.":";
2487: my @pairs=split(/\&/,$what);
2488: foreach my $pair (@pairs) {
2489: my ($key,$value)=split(/=/,$pair);
2490: &manage_permissions($key, $udom, $uname,
2491: $auth_type);
2492: $hashref->{$key}=$value;
2493: }
2494: if (untie($hashref)) {
2495: &Reply($client, "ok\n", $userinput);
2496: } else {
2497: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2498: "while attempting rolesput\n", $userinput);
2499: }
2500: } else {
2501: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2502: "while attempting rolesput\n", $userinput);
2503: }
2504: return 1;
2505: }
2506: ®ister_handler("rolesput", \&roles_put_handler, 1,1,0); # Encoded client only.
2507:
2508: #
2509: # Deletes (removes) a role for a user. This is equivalent to removing
2510: # a permissions package associated with the role from the user's profile.
2511: #
2512: # Parameters:
2513: # $cmd - The command (rolesdel)
2514: # $tail - The remainder of the request line. This consists
2515: # of:
2516: # The domain and user requesting the change (logged)
2517: # The domain and user being changed.
2518: # The roles being revoked. These are shipped to us
2519: # as a bunch of & separated role name keywords.
2520: # $client - The file handle open on the client.
2521: # Returns:
2522: # 1 - Continue processing
2523: # 0 - Exit.
2524: #
2525: sub roles_delete_handler {
2526: my ($cmd, $tail, $client) = @_;
2527:
2528: my $userinput = "$cmd:$tail";
2529:
2530: my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
2531: &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
2532: "what = ".$what);
2533: my $namespace='roles';
2534: chomp($what);
2535: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2536: &GDBM_WRCREAT(), "D",
2537: "$exedom:$exeuser:$what");
2538:
2539: if ($hashref) {
2540: my @rolekeys=split(/\&/,$what);
2541:
2542: foreach my $key (@rolekeys) {
2543: delete $hashref->{$key};
2544: }
2545: if (untie(%$hashref)) {
2546: &Reply($client, "ok\n", $userinput);
2547: } else {
2548: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2549: "while attempting rolesdel\n", $userinput);
2550: }
2551: } else {
2552: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2553: "while attempting rolesdel\n", $userinput);
2554: }
2555:
2556: return 1;
2557: }
2558: ®ister_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
2559:
2560: # Unencrypted get from a user's profile database. See
2561: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
2562: # This function retrieves a keyed item from a specific named database in the
2563: # user's directory.
2564: #
2565: # Parameters:
2566: # $cmd - Command request keyword (get).
2567: # $tail - Tail of the command. This is a colon separated list
2568: # consisting of the domain and username that uniquely
2569: # identifies the profile,
2570: # The 'namespace' which selects the gdbm file to
2571: # do the lookup in,
2572: # & separated list of keys to lookup. Note that
2573: # the values are returned as an & separated list too.
2574: # $client - File descriptor open on the client.
2575: # Returns:
2576: # 1 - Continue processing.
2577: # 0 - Exit.
2578: #
2579: sub get_profile_entry {
2580: my ($cmd, $tail, $client) = @_;
2581:
2582: my $userinput= "$cmd:$tail";
2583:
2584: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2585: chomp($what);
2586:
2587: my $replystring = read_profile($udom, $uname, $namespace, $what);
2588: my ($first) = split(/:/,$replystring);
2589: if($first ne "error") {
2590: &Reply($client, "$replystring\n", $userinput);
2591: } else {
2592: &Failure($client, $replystring." while attempting get\n", $userinput);
2593: }
2594: return 1;
2595:
2596:
2597: }
2598: ®ister_handler("get", \&get_profile_entry, 0,1,0);
2599:
2600: #
2601: # Process the encrypted get request. Note that the request is sent
2602: # in clear, but the reply is encrypted. This is a small covert channel:
2603: # information about the sensitive keys is given to the snooper. Just not
2604: # information about the values of the sensitive key. Hmm if I wanted to
2605: # know these I'd snoop for the egets. Get the profile item names from them
2606: # and then issue a get for them since there's no enforcement of the
2607: # requirement of an encrypted get for particular profile items. If I
2608: # were re-doing this, I'd force the request to be encrypted as well as the
2609: # reply. I'd also just enforce encrypted transactions for all gets since
2610: # that would prevent any covert channel snooping.
2611: #
2612: # Parameters:
2613: # $cmd - Command keyword of request (eget).
2614: # $tail - Tail of the command. See GetProfileEntry
# for more information about this.
2615: # $client - File open on the client.
2616: # Returns:
2617: # 1 - Continue processing
2618: # 0 - server should exit.
2619: sub get_profile_entry_encrypted {
2620: my ($cmd, $tail, $client) = @_;
2621:
2622: my $userinput = "$cmd:$tail";
2623:
2624: my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
2625: chomp($what);
2626: my $qresult = read_profile($udom, $uname, $namespace, $what);
2627: my ($first) = split(/:/, $qresult);
2628: if($first ne "error") {
2629:
2630: if ($cipher) {
2631: my $cmdlength=length($qresult);
2632: $qresult.=" ";
2633: my $encqresult='';
2634: for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
2635: $encqresult.= unpack("H16",
2636: $cipher->encrypt(substr($qresult,
2637: $encidx,
2638: 8)));
2639: }
2640: &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
2641: } else {
2642: &Failure( $client, "error:no_key\n", $userinput);
2643: }
2644: } else {
2645: &Failure($client, "$qresult while attempting eget\n", $userinput);
2646:
2647: }
2648:
2649: return 1;
2650: }
2651: ®ister_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
2652:
2653: #
2654: # Deletes a key in a user profile database.
2655: #
2656: # Parameters:
2657: # $cmd - Command keyword (del).
2658: # $tail - Command tail. IN this case a colon
2659: # separated list containing:
2660: # The domain and user that identifies uniquely
2661: # the identity of the user.
2662: # The profile namespace (name of the profile
2663: # database file).
2664: # & separated list of keywords to delete.
2665: # $client - File open on client socket.
2666: # Returns:
2667: # 1 - Continue processing
2668: # 0 - Exit server.
2669: #
2670: #
2671: sub delete_profile_entry {
2672: my ($cmd, $tail, $client) = @_;
2673:
2674: my $userinput = "cmd:$tail";
2675:
2676: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2677: chomp($what);
2678: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2679: &GDBM_WRCREAT(),
2680: "D",$what);
2681: if ($hashref) {
2682: my @keys=split(/\&/,$what);
2683: foreach my $key (@keys) {
2684: delete($hashref->{$key});
2685: }
2686: if (untie(%$hashref)) {
2687: &Reply($client, "ok\n", $userinput);
2688: } else {
2689: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2690: "while attempting del\n", $userinput);
2691: }
2692: } else {
2693: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2694: "while attempting del\n", $userinput);
2695: }
2696: return 1;
2697: }
2698: ®ister_handler("del", \&delete_profile_entry, 0, 1, 0);
2699:
2700: #
2701: # List the set of keys that are defined in a profile database file.
2702: # A successful reply from this will contain an & separated list of
2703: # the keys.
2704: # Parameters:
2705: # $cmd - Command request (keys).
2706: # $tail - Remainder of the request, a colon separated
2707: # list containing domain/user that identifies the
2708: # user being queried, and the database namespace
2709: # (database filename essentially).
2710: # $client - File open on the client.
2711: # Returns:
2712: # 1 - Continue processing.
2713: # 0 - Exit the server.
2714: #
2715: sub get_profile_keys {
2716: my ($cmd, $tail, $client) = @_;
2717:
2718: my $userinput = "$cmd:$tail";
2719:
2720: my ($udom,$uname,$namespace)=split(/:/,$tail);
2721: my $qresult='';
2722: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2723: &GDBM_READER());
2724: if ($hashref) {
2725: foreach my $key (keys %$hashref) {
2726: $qresult.="$key&";
2727: }
2728: if (untie(%$hashref)) {
2729: $qresult=~s/\&$//;
2730: &Reply($client, "$qresult\n", $userinput);
2731: } else {
2732: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2733: "while attempting keys\n", $userinput);
2734: }
2735: } else {
2736: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2737: "while attempting keys\n", $userinput);
2738: }
2739:
2740: return 1;
2741: }
2742: ®ister_handler("keys", \&get_profile_keys, 0, 1, 0);
2743:
2744: #
2745: # Dump the contents of a user profile database.
2746: # Note that this constitutes a very large covert channel too since
2747: # the dump will return sensitive information that is not encrypted.
2748: # The naive security assumption is that the session negotiation ensures
2749: # our client is trusted and I don't believe that's assured at present.
2750: # Sure want badly to go to ssl or tls. Of course if my peer isn't really
2751: # a LonCAPA node they could have negotiated an encryption key too so >sigh<.
2752: #
2753: # Parameters:
2754: # $cmd - The command request keyword (currentdump).
2755: # $tail - Remainder of the request, consisting of a colon
2756: # separated list that has the domain/username and
2757: # the namespace to dump (database file).
2758: # $client - file open on the remote client.
2759: # Returns:
2760: # 1 - Continue processing.
2761: # 0 - Exit the server.
2762: #
2763: sub dump_profile_database {
2764: my ($cmd, $tail, $client) = @_;
2765:
2766: my $userinput = "$cmd:$tail";
2767:
2768: my ($udom,$uname,$namespace) = split(/:/,$tail);
2769: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2770: &GDBM_READER());
2771: if ($hashref) {
2772: # Structure of %data:
2773: # $data{$symb}->{$parameter}=$value;
2774: # $data{$symb}->{'v.'.$parameter}=$version;
2775: # since $parameter will be unescaped, we do not
2776: # have to worry about silly parameter names...
2777:
2778: my $qresult='';
2779: my %data = (); # A hash of anonymous hashes..
2780: while (my ($key,$value) = each(%$hashref)) {
2781: my ($v,$symb,$param) = split(/:/,$key);
2782: next if ($v eq 'version' || $symb eq 'keys');
2783: next if (exists($data{$symb}) &&
2784: exists($data{$symb}->{$param}) &&
2785: $data{$symb}->{'v.'.$param} > $v);
2786: $data{$symb}->{$param}=$value;
2787: $data{$symb}->{'v.'.$param}=$v;
2788: }
2789: if (untie(%$hashref)) {
2790: while (my ($symb,$param_hash) = each(%data)) {
2791: while(my ($param,$value) = each (%$param_hash)){
2792: next if ($param =~ /^v\./); # Ignore versions...
2793: #
2794: # Just dump the symb=value pairs separated by &
2795: #
2796: $qresult.=$symb.':'.$param.'='.$value.'&';
2797: }
2798: }
2799: chop($qresult);
2800: &Reply($client , "$qresult\n", $userinput);
2801: } else {
2802: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2803: "while attempting currentdump\n", $userinput);
2804: }
2805: } else {
2806: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2807: "while attempting currentdump\n", $userinput);
2808: }
2809:
2810: return 1;
2811: }
2812: ®ister_handler("currentdump", \&dump_profile_database, 0, 1, 0);
2813:
2814: #
2815: # Dump a profile database with an optional regular expression
2816: # to match against the keys. In this dump, no effort is made
2817: # to separate symb from version information. Presumably the
2818: # databases that are dumped by this command are of a different
2819: # structure. Need to look at this and improve the documentation of
2820: # both this and the currentdump handler.
2821: # Parameters:
2822: # $cmd - The command keyword.
2823: # $tail - All of the characters after the $cmd:
2824: # These are expected to be a colon
2825: # separated list containing:
2826: # domain/user - identifying the user.
2827: # namespace - identifying the database.
2828: # regexp - optional regular expression
2829: # that is matched against
2830: # database keywords to do
2831: # selective dumps.
2832: # $client - Channel open on the client.
2833: # Returns:
2834: # 1 - Continue processing.
2835: # Side effects:
2836: # response is written to $client.
2837: #
2838: sub dump_with_regexp {
2839: my ($cmd, $tail, $client) = @_;
2840:
2841:
2842: my $userinput = "$cmd:$tail";
2843:
2844: my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);
2845: if (defined($regexp)) {
2846: $regexp=&unescape($regexp);
2847: } else {
2848: $regexp='.';
2849: }
2850: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2851: &GDBM_READER());
2852: if ($hashref) {
2853: my $qresult='';
2854: while (my ($key,$value) = each(%$hashref)) {
2855: if ($regexp eq '.') {
2856: $qresult.=$key.'='.$value.'&';
2857: } else {
2858: my $unescapeKey = &unescape($key);
2859: if (eval('$unescapeKey=~/$regexp/')) {
2860: $qresult.="$key=$value&";
2861: }
2862: }
2863: }
2864: if (untie(%$hashref)) {
2865: chop($qresult);
2866: &Reply($client, "$qresult\n", $userinput);
2867: } else {
2868: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2869: "while attempting dump\n", $userinput);
2870: }
2871: } else {
2872: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2873: "while attempting dump\n", $userinput);
2874: }
2875:
2876: return 1;
2877: }
2878: ®ister_handler("dump", \&dump_with_regexp, 0, 1, 0);
2879:
2880: # Store a set of key=value pairs associated with a versioned name.
2881: #
2882: # Parameters:
2883: # $cmd - Request command keyword.
2884: # $tail - Tail of the request. This is a colon
2885: # separated list containing:
2886: # domain/user - User and authentication domain.
2887: # namespace - Name of the database being modified
2888: # rid - Resource keyword to modify.
2889: # what - new value associated with rid.
2890: #
2891: # $client - Socket open on the client.
2892: #
2893: #
2894: # Returns:
2895: # 1 (keep on processing).
2896: # Side-Effects:
2897: # Writes to the client
2898: sub store_handler {
2899: my ($cmd, $tail, $client) = @_;
2900:
2901: my $userinput = "$cmd:$tail";
2902:
2903: my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
2904: if ($namespace ne 'roles') {
2905:
2906: chomp($what);
2907: my @pairs=split(/\&/,$what);
2908: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2909: &GDBM_WRCREAT(), "S",
2910: "$rid:$what");
2911: if ($hashref) {
2912: my $now = time;
2913: my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
2914: my $key;
2915: $hashref->{"version:$rid"}++;
2916: my $version=$hashref->{"version:$rid"};
2917: my $allkeys='';
2918: foreach my $pair (@pairs) {
2919: my ($key,$value)=split(/=/,$pair);
2920: $allkeys.=$key.':';
2921: $hashref->{"$version:$rid:$key"}=$value;
2922: }
2923: $hashref->{"$version:$rid:timestamp"}=$now;
2924: $allkeys.='timestamp';
2925: $hashref->{"$version:keys:$rid"}=$allkeys;
2926: if (untie($hashref)) {
2927: &Reply($client, "ok\n", $userinput);
2928: } else {
2929: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2930: "while attempting store\n", $userinput);
2931: }
2932: } else {
2933: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2934: "while attempting store\n", $userinput);
2935: }
2936: } else {
2937: &Failure($client, "refused\n", $userinput);
2938: }
2939:
2940: return 1;
2941: }
2942: ®ister_handler("store", \&store_handler, 0, 1, 0);
2943:
2944: #
2945: # Dump out all versions of a resource that has key=value pairs associated
2946: # with it for each version. These resources are built up via the store
2947: # command.
2948: #
2949: # Parameters:
2950: # $cmd - Command keyword.
2951: # $tail - Remainder of the request which consists of:
2952: # domain/user - User and auth. domain.
2953: # namespace - name of resource database.
2954: # rid - Resource id.
2955: # $client - socket open on the client.
2956: #
2957: # Returns:
2958: # 1 indicating the caller should not yet exit.
2959: # Side-effects:
2960: # Writes a reply to the client.
2961: # The reply is a string of the following shape:
2962: # version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
2963: # Where the 1 above represents version 1.
2964: # this continues for all pairs of keys in all versions.
2965: #
2966: #
2967: #
2968: #
2969: sub restore_handler {
2970: my ($cmd, $tail, $client) = @_;
2971:
2972: my $userinput = "$cmd:$tail"; # Only used for logging purposes.
2973:
2974: my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
2975: $namespace=~s/\//\_/g;
2976: $namespace=~s/\W//g;
2977: chomp($rid);
2978: my $proname=&propath($udom,$uname);
2979: my $qresult='';
2980: my %hash;
2981: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
2982: &GDBM_READER(),0640)) {
2983: my $version=$hash{"version:$rid"};
2984: $qresult.="version=$version&";
2985: my $scope;
2986: for ($scope=1;$scope<=$version;$scope++) {
2987: my $vkeys=$hash{"$scope:keys:$rid"};
2988: my @keys=split(/:/,$vkeys);
2989: my $key;
2990: $qresult.="$scope:keys=$vkeys&";
2991: foreach $key (@keys) {
2992: $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
2993: }
2994: }
2995: if (untie(%hash)) {
2996: $qresult=~s/\&$//;
2997: &Reply( $client, "$qresult\n", $userinput);
2998: } else {
2999: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3000: "while attempting restore\n", $userinput);
3001: }
3002: } else {
3003: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3004: "while attempting restore\n", $userinput);
3005: }
3006:
3007: return 1;
3008:
3009:
3010: }
3011: ®ister_handler("restore", \&restore_handler, 0,1,0);
3012:
3013: #
3014: # Add a chat message to to a discussion board.
3015: #
3016: # Parameters:
3017: # $cmd - Request keyword.
3018: # $tail - Tail of the command. A colon separated list
3019: # containing:
3020: # cdom - Domain on which the chat board lives
3021: # cnum - Identifier of the discussion group.
3022: # post - Body of the posting.
3023: # $client - Socket open on the client.
3024: # Returns:
3025: # 1 - Indicating caller should keep on processing.
3026: #
3027: # Side-effects:
3028: # writes a reply to the client.
3029: #
3030: #
3031: sub send_chat_handler {
3032: my ($cmd, $tail, $client) = @_;
3033:
3034:
3035: my $userinput = "$cmd:$tail";
3036:
3037: my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
3038: &chat_add($cdom,$cnum,$newpost);
3039: &Reply($client, "ok\n", $userinput);
3040:
3041: return 1;
3042: }
3043: ®ister_handler("chatsend", \&send_chat_handler, 0, 1, 0);
3044:
3045: #
3046: # Retrieve the set of chat messagss from a discussion board.
3047: #
3048: # Parameters:
3049: # $cmd - Command keyword that initiated the request.
3050: # $tail - Remainder of the request after the command
3051: # keyword. In this case a colon separated list of
3052: # chat domain - Which discussion board.
3053: # chat id - Discussion thread(?)
3054: # domain/user - Authentication domain and username
3055: # of the requesting person.
3056: # $client - Socket open on the client program.
3057: # Returns:
3058: # 1 - continue processing
3059: # Side effects:
3060: # Response is written to the client.
3061: #
3062: sub retrieve_chat_handler {
3063: my ($cmd, $tail, $client) = @_;
3064:
3065:
3066: my $userinput = "$cmd:$tail";
3067:
3068: my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
3069: my $reply='';
3070: foreach (&get_chat($cdom,$cnum,$udom,$uname)) {
3071: $reply.=&escape($_).':';
3072: }
3073: $reply=~s/\:$//;
3074: &Reply($client, $reply."\n", $userinput);
3075:
3076:
3077: return 1;
3078: }
3079: ®ister_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
3080:
3081: #
3082: # Initiate a query of an sql database. SQL query repsonses get put in
3083: # a file for later retrieval. This prevents sql query results from
3084: # bottlenecking the system. Note that with loncnew, perhaps this is
3085: # less of an issue since multiple outstanding requests can be concurrently
3086: # serviced.
3087: #
3088: # Parameters:
3089: # $cmd - COmmand keyword that initiated the request.
3090: # $tail - Remainder of the command after the keyword.
3091: # For this function, this consists of a query and
3092: # 3 arguments that are self-documentingly labelled
3093: # in the original arg1, arg2, arg3.
3094: # $client - Socket open on the client.
3095: # Return:
3096: # 1 - Indicating processing should continue.
3097: # Side-effects:
3098: # a reply is written to $client.
3099: #
3100: sub send_query_handler {
3101: my ($cmd, $tail, $client) = @_;
3102:
3103:
3104: my $userinput = "$cmd:$tail";
3105:
3106: my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
3107: $query=~s/\n*$//g;
3108: &Reply($client, "". &sql_reply("$clientname\&$query".
3109: "\&$arg1"."\&$arg2"."\&$arg3")."\n",
3110: $userinput);
3111:
3112: return 1;
3113: }
3114: ®ister_handler("querysend", \&send_query_handler, 0, 1, 0);
3115:
3116: #
3117: # Add a reply to an sql query. SQL queries are done asyncrhonously.
3118: # The query is submitted via a "querysend" transaction.
3119: # There it is passed on to the lonsql daemon, queued and issued to
3120: # mysql.
3121: # This transaction is invoked when the sql transaction is complete
3122: # it stores the query results in flie and indicates query completion.
3123: # presumably local software then fetches this response... I'm guessing
3124: # the sequence is: lonc does a querysend, we ask lonsql to do it.
3125: # lonsql on completion of the query interacts with the lond of our
3126: # client to do a query reply storing two files:
3127: # - id - The results of the query.
3128: # - id.end - Indicating the transaction completed.
3129: # NOTE: id is a unique id assigned to the query and querysend time.
3130: # Parameters:
3131: # $cmd - Command keyword that initiated this request.
3132: # $tail - Remainder of the tail. In this case that's a colon
3133: # separated list containing the query Id and the
3134: # results of the query.
3135: # $client - Socket open on the client.
3136: # Return:
3137: # 1 - Indicating that we should continue processing.
3138: # Side effects:
3139: # ok written to the client.
3140: #
3141: sub reply_query_handler {
3142: my ($cmd, $tail, $client) = @_;
3143:
3144:
3145: my $userinput = "$cmd:$tail";
3146:
3147: my ($cmd,$id,$reply)=split(/:/,$userinput);
3148: my $store;
3149: my $execdir=$perlvar{'lonDaemons'};
3150: if ($store=IO::File->new(">$execdir/tmp/$id")) {
3151: $reply=~s/\&/\n/g;
3152: print $store $reply;
3153: close $store;
3154: my $store2=IO::File->new(">$execdir/tmp/$id.end");
3155: print $store2 "done\n";
3156: close $store2;
3157: &Reply($client, "ok\n", $userinput);
3158: } else {
3159: &Failure($client, "error: ".($!+0)
3160: ." IO::File->new Failed ".
3161: "while attempting queryreply\n", $userinput);
3162: }
3163:
3164:
3165: return 1;
3166: }
3167: ®ister_handler("queryreply", \&reply_query_handler, 0, 1, 0);
3168:
3169: #
3170: # Process the courseidput request. Not quite sure what this means
3171: # at the system level sense. It appears a gdbm file in the
3172: # /home/httpd/lonUsers/$domain/nohist_courseids is tied and
3173: # a set of entries made in that database.
3174: #
3175: # Parameters:
3176: # $cmd - The command keyword that initiated this request.
3177: # $tail - Tail of the command. In this case consists of a colon
3178: # separated list contaning the domain to apply this to and
3179: # an ampersand separated list of keyword=value pairs.
3180: # Each value is a colon separated list that includes:
3181: # description, institutional code and course owner.
3182: # For backward compatibility with versions included
3183: # in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
3184: # code and/or course owner are preserved from the existing
3185: # record when writing a new record in response to 1.1 or
3186: # 1.2 implementations of lonnet::flushcourselogs().
3187: #
3188: # $client - Socket open on the client.
3189: # Returns:
3190: # 1 - indicating that processing should continue
3191: #
3192: # Side effects:
3193: # reply is written to the client.
3194: #
3195: sub put_course_id_handler {
3196: my ($cmd, $tail, $client) = @_;
3197:
3198:
3199: my $userinput = "$cmd:$tail";
3200:
3201: my ($udom, $what) = split(/:/, $tail,2);
3202: chomp($what);
3203: my $now=time;
3204: my @pairs=split(/\&/,$what);
3205:
3206: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3207: if ($hashref) {
3208: foreach my $pair (@pairs) {
3209: my ($key,$courseinfo) = split(/=/,$pair,2);
3210: $courseinfo =~ s/=/:/g;
3211:
3212: my @current_items = split(/:/,$hashref->{$key});
3213: shift(@current_items); # remove description
3214: pop(@current_items); # remove last access
3215: my $numcurrent = scalar(@current_items);
3216:
3217: my @new_items = split(/:/,$courseinfo);
3218: my $numnew = scalar(@new_items);
3219: if ($numcurrent > 0) {
3220: if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
3221: $courseinfo .= ':'.join(':',@current_items);
3222: } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
3223: $courseinfo .= ':'.$current_items[$numcurrent-1];
3224: }
3225: }
3226: $hashref->{$key}=$courseinfo.':'.$now;
3227: }
3228: if (untie(%$hashref)) {
3229: &Reply( $client, "ok\n", $userinput);
3230: } else {
3231: &Failure($client, "error: ".($!+0)
3232: ." untie(GDBM) Failed ".
3233: "while attempting courseidput\n", $userinput);
3234: }
3235: } else {
3236: &Failure($client, "error: ".($!+0)
3237: ." tie(GDBM) Failed ".
3238: "while attempting courseidput\n", $userinput);
3239: }
3240:
3241:
3242: return 1;
3243: }
3244: ®ister_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
3245:
3246: # Retrieves the value of a course id resource keyword pattern
3247: # defined since a starting date. Both the starting date and the
3248: # keyword pattern are optional. If the starting date is not supplied it
3249: # is treated as the beginning of time. If the pattern is not found,
3250: # it is treatred as "." matching everything.
3251: #
3252: # Parameters:
3253: # $cmd - Command keyword that resulted in us being dispatched.
3254: # $tail - The remainder of the command that, in this case, consists
3255: # of a colon separated list of:
3256: # domain - The domain in which the course database is
3257: # defined.
3258: # since - Optional parameter describing the minimum
3259: # time of definition(?) of the resources that
3260: # will match the dump.
3261: # description - regular expression that is used to filter
3262: # the dump. Only keywords matching this regexp
3263: # will be used.
3264: # institutional code - optional supplied code to filter
3265: # the dump. Only courses with an institutional code
3266: # that match the supplied code will be returned.
3267: # owner - optional supplied username of owner to filter
3268: # the dump. Only courses for which the course
3269: # owner matches the supplied username will be
3270: # returned. Implicit assumption that owner
3271: # is a user in the domain in which the
3272: # course database is defined.
3273: # $client - The socket open on the client.
3274: # Returns:
3275: # 1 - Continue processing.
3276: # Side Effects:
3277: # a reply is written to $client.
3278: sub dump_course_id_handler {
3279: my ($cmd, $tail, $client) = @_;
3280:
3281: my $userinput = "$cmd:$tail";
3282:
3283: my ($udom,$since,$description,$instcodefilter,$ownerfilter) =split(/:/,$tail);
3284: if (defined($description)) {
3285: $description=&unescape($description);
3286: } else {
3287: $description='.';
3288: }
3289: if (defined($instcodefilter)) {
3290: $instcodefilter=&unescape($instcodefilter);
3291: } else {
3292: $instcodefilter='.';
3293: }
3294: if (defined($ownerfilter)) {
3295: $ownerfilter=&unescape($ownerfilter);
3296: } else {
3297: $ownerfilter='.';
3298: }
3299:
3300: unless (defined($since)) { $since=0; }
3301: my $qresult='';
3302: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3303: if ($hashref) {
3304: while (my ($key,$value) = each(%$hashref)) {
3305: my ($descr,$lasttime,$inst_code,$owner);
3306: my @courseitems = split(/:/,$value);
3307: $lasttime = pop(@courseitems);
3308: ($descr,$inst_code,$owner)=@courseitems;
3309: if ($lasttime<$since) { next; }
3310: my $match = 1;
3311: unless ($description eq '.') {
3312: my $unescapeDescr = &unescape($descr);
3313: unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
3314: $match = 0;
3315: }
3316: }
3317: unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
3318: my $unescapeInstcode = &unescape($inst_code);
3319: unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
3320: $match = 0;
3321: }
3322: }
3323: unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
3324: my $unescapeOwner = &unescape($owner);
3325: unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
3326: $match = 0;
3327: }
3328: }
3329: if ($match == 1) {
3330: $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
3331: }
3332: }
3333: if (untie(%$hashref)) {
3334: chop($qresult);
3335: &Reply($client, "$qresult\n", $userinput);
3336: } else {
3337: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3338: "while attempting courseiddump\n", $userinput);
3339: }
3340: } else {
3341: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3342: "while attempting courseiddump\n", $userinput);
3343: }
3344:
3345:
3346: return 1;
3347: }
3348: ®ister_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
3349:
3350: #
3351: # Puts an id to a domains id database.
3352: #
3353: # Parameters:
3354: # $cmd - The command that triggered us.
3355: # $tail - Remainder of the request other than the command. This is a
3356: # colon separated list containing:
3357: # $domain - The domain for which we are writing the id.
3358: # $pairs - The id info to write... this is and & separated list
3359: # of keyword=value.
3360: # $client - Socket open on the client.
3361: # Returns:
3362: # 1 - Continue processing.
3363: # Side effects:
3364: # reply is written to $client.
3365: #
3366: sub put_id_handler {
3367: my ($cmd,$tail,$client) = @_;
3368:
3369:
3370: my $userinput = "$cmd:$tail";
3371:
3372: my ($udom,$what)=split(/:/,$tail);
3373: chomp($what);
3374: my @pairs=split(/\&/,$what);
3375: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
3376: "P", $what);
3377: if ($hashref) {
3378: foreach my $pair (@pairs) {
3379: my ($key,$value)=split(/=/,$pair);
3380: $hashref->{$key}=$value;
3381: }
3382: if (untie(%$hashref)) {
3383: &Reply($client, "ok\n", $userinput);
3384: } else {
3385: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3386: "while attempting idput\n", $userinput);
3387: }
3388: } else {
3389: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3390: "while attempting idput\n", $userinput);
3391: }
3392:
3393: return 1;
3394: }
3395: ®ister_handler("idput", \&put_id_handler, 0, 1, 0);
3396:
3397: #
3398: # Retrieves a set of id values from the id database.
3399: # Returns an & separated list of results, one for each requested id to the
3400: # client.
3401: #
3402: # Parameters:
3403: # $cmd - Command keyword that caused us to be dispatched.
3404: # $tail - Tail of the command. Consists of a colon separated:
3405: # domain - the domain whose id table we dump
3406: # ids Consists of an & separated list of
3407: # id keywords whose values will be fetched.
3408: # nonexisting keywords will have an empty value.
3409: # $client - Socket open on the client.
3410: #
3411: # Returns:
3412: # 1 - indicating processing should continue.
3413: # Side effects:
3414: # An & separated list of results is written to $client.
3415: #
3416: sub get_id_handler {
3417: my ($cmd, $tail, $client) = @_;
3418:
3419:
3420: my $userinput = "$client:$tail";
3421:
3422: my ($udom,$what)=split(/:/,$tail);
3423: chomp($what);
3424: my @queries=split(/\&/,$what);
3425: my $qresult='';
3426: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
3427: if ($hashref) {
3428: for (my $i=0;$i<=$#queries;$i++) {
3429: $qresult.="$hashref->{$queries[$i]}&";
3430: }
3431: if (untie(%$hashref)) {
3432: $qresult=~s/\&$//;
3433: &Reply($client, "$qresult\n", $userinput);
3434: } else {
3435: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3436: "while attempting idget\n",$userinput);
3437: }
3438: } else {
3439: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3440: "while attempting idget\n",$userinput);
3441: }
3442:
3443: return 1;
3444: }
3445: ®ister_handler("idget", \&get_id_handler, 0, 1, 0);
3446:
3447: #
3448: # Process the tmpput command I'm not sure what this does.. Seems to
3449: # create a file in the lonDaemons/tmp directory of the form $id.tmp
3450: # where Id is the client's ip concatenated with a sequence number.
3451: # The file will contain some value that is passed in. Is this e.g.
3452: # a login token?
3453: #
3454: # Parameters:
3455: # $cmd - The command that got us dispatched.
3456: # $tail - The remainder of the request following $cmd:
3457: # In this case this will be the contents of the file.
3458: # $client - Socket connected to the client.
3459: # Returns:
3460: # 1 indicating processing can continue.
3461: # Side effects:
3462: # A file is created in the local filesystem.
3463: # A reply is sent to the client.
3464: sub tmp_put_handler {
3465: my ($cmd, $what, $client) = @_;
3466:
3467: my $userinput = "$cmd:$what"; # Reconstruct for logging.
3468:
3469:
3470: my $store;
3471: $tmpsnum++;
3472: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
3473: $id=~s/\W/\_/g;
3474: $what=~s/\n//g;
3475: my $execdir=$perlvar{'lonDaemons'};
3476: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
3477: print $store $what;
3478: close $store;
3479: &Reply($client, "$id\n", $userinput);
3480: } else {
3481: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
3482: "while attempting tmpput\n", $userinput);
3483: }
3484: return 1;
3485:
3486: }
3487: ®ister_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
3488:
3489: # Processes the tmpget command. This command returns the contents
3490: # of a temporary resource file(?) created via tmpput.
3491: #
3492: # Paramters:
3493: # $cmd - Command that got us dispatched.
3494: # $id - Tail of the command, contain the id of the resource
3495: # we want to fetch.
3496: # $client - socket open on the client.
3497: # Return:
3498: # 1 - Inidcating processing can continue.
3499: # Side effects:
3500: # A reply is sent to the client.
3501: #
3502: sub tmp_get_handler {
3503: my ($cmd, $id, $client) = @_;
3504:
3505: my $userinput = "$cmd:$id";
3506:
3507:
3508: $id=~s/\W/\_/g;
3509: my $store;
3510: my $execdir=$perlvar{'lonDaemons'};
3511: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
3512: my $reply=<$store>;
3513: &Reply( $client, "$reply\n", $userinput);
3514: close $store;
3515: } else {
3516: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
3517: "while attempting tmpget\n", $userinput);
3518: }
3519:
3520: return 1;
3521: }
3522: ®ister_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
3523:
3524: #
3525: # Process the tmpdel command. This command deletes a temp resource
3526: # created by the tmpput command.
3527: #
3528: # Parameters:
3529: # $cmd - Command that got us here.
3530: # $id - Id of the temporary resource created.
3531: # $client - socket open on the client process.
3532: #
3533: # Returns:
3534: # 1 - Indicating processing should continue.
3535: # Side Effects:
3536: # A file is deleted
3537: # A reply is sent to the client.
3538: sub tmp_del_handler {
3539: my ($cmd, $id, $client) = @_;
3540:
3541: my $userinput= "$cmd:$id";
3542:
3543: chomp($id);
3544: $id=~s/\W/\_/g;
3545: my $execdir=$perlvar{'lonDaemons'};
3546: if (unlink("$execdir/tmp/$id.tmp")) {
3547: &Reply($client, "ok\n", $userinput);
3548: } else {
3549: &Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
3550: "while attempting tmpdel\n", $userinput);
3551: }
3552:
3553: return 1;
3554:
3555: }
3556: ®ister_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
3557:
3558: #
3559: # Processes the setannounce command. This command
3560: # creates a file named announce.txt in the top directory of
3561: # the documentn root and sets its contents. The announce.txt file is
3562: # printed in its entirety at the LonCAPA login page. Note:
3563: # once the announcement.txt fileis created it cannot be deleted.
3564: # However, setting the contents of the file to empty removes the
3565: # announcement from the login page of loncapa so who cares.
3566: #
3567: # Parameters:
3568: # $cmd - The command that got us dispatched.
3569: # $announcement - The text of the announcement.
3570: # $client - Socket open on the client process.
3571: # Retunrns:
3572: # 1 - Indicating request processing should continue
3573: # Side Effects:
3574: # The file {DocRoot}/announcement.txt is created.
3575: # A reply is sent to $client.
3576: #
3577: sub set_announce_handler {
3578: my ($cmd, $announcement, $client) = @_;
3579:
3580: my $userinput = "$cmd:$announcement";
3581:
3582: chomp($announcement);
3583: $announcement=&unescape($announcement);
3584: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
3585: '/announcement.txt')) {
3586: print $store $announcement;
3587: close $store;
3588: &Reply($client, "ok\n", $userinput);
3589: } else {
3590: &Failure($client, "error: ".($!+0)."\n", $userinput);
3591: }
3592:
3593: return 1;
3594: }
3595: ®ister_handler("setannounce", \&set_announce_handler, 0, 1, 0);
3596:
3597: #
3598: # Return the version of the daemon. This can be used to determine
3599: # the compatibility of cross version installations or, alternatively to
3600: # simply know who's out of date and who isn't. Note that the version
3601: # is returned concatenated with the tail.
3602: # Parameters:
3603: # $cmd - the request that dispatched to us.
3604: # $tail - Tail of the request (client's version?).
3605: # $client - Socket open on the client.
3606: #Returns:
3607: # 1 - continue processing requests.
3608: # Side Effects:
3609: # Replies with version to $client.
3610: sub get_version_handler {
3611: my ($cmd, $tail, $client) = @_;
3612:
3613: my $userinput = $cmd.$tail;
3614:
3615: &Reply($client, &version($userinput)."\n", $userinput);
3616:
3617:
3618: return 1;
3619: }
3620: ®ister_handler("version", \&get_version_handler, 0, 1, 0);
3621:
3622: # Set the current host and domain. This is used to support
3623: # multihomed systems. Each IP of the system, or even separate daemons
3624: # on the same IP can be treated as handling a separate lonCAPA virtual
3625: # machine. This command selects the virtual lonCAPA. The client always
3626: # knows the right one since it is lonc and it is selecting the domain/system
3627: # from the hosts.tab file.
3628: # Parameters:
3629: # $cmd - Command that dispatched us.
3630: # $tail - Tail of the command (domain/host requested).
3631: # $socket - Socket open on the client.
3632: #
3633: # Returns:
3634: # 1 - Indicates the program should continue to process requests.
3635: # Side-effects:
3636: # The default domain/system context is modified for this daemon.
3637: # a reply is sent to the client.
3638: #
3639: sub set_virtual_host_handler {
3640: my ($cmd, $tail, $socket) = @_;
3641:
3642: my $userinput ="$cmd:$tail";
3643:
3644: &Reply($client, &sethost($userinput)."\n", $userinput);
3645:
3646:
3647: return 1;
3648: }
3649: ®ister_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
3650:
3651: # Process a request to exit:
3652: # - "bye" is sent to the client.
3653: # - The client socket is shutdown and closed.
3654: # - We indicate to the caller that we should exit.
3655: # Formal Parameters:
3656: # $cmd - The command that got us here.
3657: # $tail - Tail of the command (empty).
3658: # $client - Socket open on the tail.
3659: # Returns:
3660: # 0 - Indicating the program should exit!!
3661: #
3662: sub exit_handler {
3663: my ($cmd, $tail, $client) = @_;
3664:
3665: my $userinput = "$cmd:$tail";
3666:
3667: &logthis("Client $clientip ($clientname) hanging up: $userinput");
3668: &Reply($client, "bye\n", $userinput);
3669: $client->shutdown(2); # shutdown the socket forcibly.
3670: $client->close();
3671:
3672: return 0;
3673: }
3674: ®ister_handler("exit", \&exit_handler, 0,1,1);
3675: ®ister_handler("init", \&exit_handler, 0,1,1);
3676: ®ister_handler("quit", \&exit_handler, 0,1,1);
3677:
3678: # Determine if auto-enrollment is enabled.
3679: # Note that the original had what I believe to be a defect.
3680: # The original returned 0 if the requestor was not a registerd client.
3681: # It should return "refused".
3682: # Formal Parameters:
3683: # $cmd - The command that invoked us.
3684: # $tail - The tail of the command (Extra command parameters.
3685: # $client - The socket open on the client that issued the request.
3686: # Returns:
3687: # 1 - Indicating processing should continue.
3688: #
3689: sub enrollment_enabled_handler {
3690: my ($cmd, $tail, $client) = @_;
3691: my $userinput = $cmd.":".$tail; # For logging purposes.
3692:
3693:
3694: my $cdom = split(/:/, $tail); # Domain we're asking about.
3695: my $outcome = &localenroll::run($cdom);
3696: &Reply($client, "$outcome\n", $userinput);
3697:
3698: return 1;
3699: }
3700: ®ister_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
3701:
3702: # Get the official sections for which auto-enrollment is possible.
3703: # Since the admin people won't know about 'unofficial sections'
3704: # we cannot auto-enroll on them.
3705: # Formal Parameters:
3706: # $cmd - The command request that got us dispatched here.
3707: # $tail - The remainder of the request. In our case this
3708: # will be split into:
3709: # $coursecode - The course name from the admin point of view.
3710: # $cdom - The course's domain(?).
3711: # $client - Socket open on the client.
3712: # Returns:
3713: # 1 - Indiciting processing should continue.
3714: #
3715: sub get_sections_handler {
3716: my ($cmd, $tail, $client) = @_;
3717: my $userinput = "$cmd:$tail";
3718:
3719: my ($coursecode, $cdom) = split(/:/, $tail);
3720: my @secs = &localenroll::get_sections($coursecode,$cdom);
3721: my $seclist = &escape(join(':',@secs));
3722:
3723: &Reply($client, "$seclist\n", $userinput);
3724:
3725:
3726: return 1;
3727: }
3728: ®ister_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
3729:
3730: # Validate the owner of a new course section.
3731: #
3732: # Formal Parameters:
3733: # $cmd - Command that got us dispatched.
3734: # $tail - the remainder of the command. For us this consists of a
3735: # colon separated string containing:
3736: # $inst - Course Id from the institutions point of view.
3737: # $owner - Proposed owner of the course.
3738: # $cdom - Domain of the course (from the institutions
3739: # point of view?)..
3740: # $client - Socket open on the client.
3741: #
3742: # Returns:
3743: # 1 - Processing should continue.
3744: #
3745: sub validate_course_owner_handler {
3746: my ($cmd, $tail, $client) = @_;
3747: my $userinput = "$cmd:$tail";
3748: my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
3749:
3750: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
3751: &Reply($client, "$outcome\n", $userinput);
3752:
3753:
3754:
3755: return 1;
3756: }
3757: ®ister_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
3758:
3759: #
3760: # Validate a course section in the official schedule of classes
3761: # from the institutions point of view (part of autoenrollment).
3762: #
3763: # Formal Parameters:
3764: # $cmd - The command request that got us dispatched.
3765: # $tail - The tail of the command. In this case,
3766: # this is a colon separated set of words that will be split
3767: # into:
3768: # $inst_course_id - The course/section id from the
3769: # institutions point of view.
3770: # $cdom - The domain from the institutions
3771: # point of view.
3772: # $client - Socket open on the client.
3773: # Returns:
3774: # 1 - Indicating processing should continue.
3775: #
3776: sub validate_course_section_handler {
3777: my ($cmd, $tail, $client) = @_;
3778: my $userinput = "$cmd:$tail";
3779: my ($inst_course_id, $cdom) = split(/:/, $tail);
3780:
3781: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
3782: &Reply($client, "$outcome\n", $userinput);
3783:
3784:
3785: return 1;
3786: }
3787: ®ister_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
3788:
3789: #
3790: # Create a password for a new auto-enrollment user.
3791: # I think/guess, this password allows access to the institutions
3792: # AIS class list server/services. Stuart can correct this comment
3793: # when he finds out how wrong I am.
3794: #
3795: # Formal Parameters:
3796: # $cmd - The command request that got us dispatched.
3797: # $tail - The tail of the command. In this case this is a colon separated
3798: # set of words that will be split into:
3799: # $authparam - An authentication parameter (username??).
3800: # $cdom - The domain of the course from the institution's
3801: # point of view.
3802: # $client - The socket open on the client.
3803: # Returns:
3804: # 1 - continue processing.
3805: #
3806: sub create_auto_enroll_password_handler {
3807: my ($cmd, $tail, $client) = @_;
3808: my $userinput = "$cmd:$tail";
3809:
3810: my ($authparam, $cdom) = split(/:/, $userinput);
3811:
3812: my ($create_passwd,$authchk);
3813: ($authparam,
3814: $create_passwd,
3815: $authchk) = &localenroll::create_password($authparam,$cdom);
3816:
3817: &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
3818: $userinput);
3819:
3820:
3821: return 1;
3822: }
3823: ®ister_handler("autocreatepassword", \&create_auto_enroll_password_handler,
3824: 0, 1, 0);
3825:
3826: # Retrieve and remove temporary files created by/during autoenrollment.
3827: #
3828: # Formal Parameters:
3829: # $cmd - The command that got us dispatched.
3830: # $tail - The tail of the command. In our case this is a colon
3831: # separated list that will be split into:
3832: # $filename - The name of the file to remove.
3833: # The filename is given as a path relative to
3834: # the LonCAPA temp file directory.
3835: # $client - Socket open on the client.
3836: #
3837: # Returns:
3838: # 1 - Continue processing.
3839: sub retrieve_auto_file_handler {
3840: my ($cmd, $tail, $client) = @_;
3841: my $userinput = "cmd:$tail";
3842:
3843: my ($filename) = split(/:/, $tail);
3844:
3845: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
3846: if ( (-e $source) && ($filename ne '') ) {
3847: my $reply = '';
3848: if (open(my $fh,$source)) {
3849: while (<$fh>) {
3850: chomp($_);
3851: $_ =~ s/^\s+//g;
3852: $_ =~ s/\s+$//g;
3853: $reply .= $_;
3854: }
3855: close($fh);
3856: &Reply($client, &escape($reply)."\n", $userinput);
3857:
3858: # Does this have to be uncommented??!? (RF).
3859: #
3860: # unlink($source);
3861: } else {
3862: &Failure($client, "error\n", $userinput);
3863: }
3864: } else {
3865: &Failure($client, "error\n", $userinput);
3866: }
3867:
3868:
3869: return 1;
3870: }
3871: ®ister_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
3872:
3873: #
3874: # Read and retrieve institutional code format (for support form).
3875: # Formal Parameters:
3876: # $cmd - Command that dispatched us.
3877: # $tail - Tail of the command. In this case it conatins
3878: # the course domain and the coursename.
3879: # $client - Socket open on the client.
3880: # Returns:
3881: # 1 - Continue processing.
3882: #
3883: sub get_institutional_code_format_handler {
3884: my ($cmd, $tail, $client) = @_;
3885: my $userinput = "$cmd:$tail";
3886:
3887: my $reply;
3888: my($cdom,$course) = split(/:/,$tail);
3889: my @pairs = split/\&/,$course;
3890: my %instcodes = ();
3891: my %codes = ();
3892: my @codetitles = ();
3893: my %cat_titles = ();
3894: my %cat_order = ();
3895: foreach (@pairs) {
3896: my ($key,$value) = split/=/,$_;
3897: $instcodes{&unescape($key)} = &unescape($value);
3898: }
3899: my $formatreply = &localenroll::instcode_format($cdom,
3900: \%instcodes,
3901: \%codes,
3902: \@codetitles,
3903: \%cat_titles,
3904: \%cat_order);
3905: if ($formatreply eq 'ok') {
3906: my $codes_str = &hash2str(%codes);
3907: my $codetitles_str = &array2str(@codetitles);
3908: my $cat_titles_str = &hash2str(%cat_titles);
3909: my $cat_order_str = &hash2str(%cat_order);
3910: &Reply($client,
3911: $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
3912: .$cat_order_str."\n",
3913: $userinput);
3914: } else {
3915: # this else branch added by RF since if not ok, lonc will
3916: # hang waiting on reply until timeout.
3917: #
3918: &Reply($client, "format_error\n", $userinput);
3919: }
3920:
3921: return 1;
3922: }
3923: ®ister_handler("autoinstcodeformat",
3924: \&get_institutional_code_format_handler,0,1,0);
3925:
3926: #
3927: # Gets a student's photo to exist (in the correct image type) in the user's
3928: # directory.
3929: # Formal Parameters:
3930: # $cmd - The command request that got us dispatched.
3931: # $tail - A colon separated set of words that will be split into:
3932: # $domain - student's domain
3933: # $uname - student username
3934: # $type - image type desired
3935: # $client - The socket open on the client.
3936: # Returns:
3937: # 1 - continue processing.
3938: sub student_photo_handler {
3939: my ($cmd, $tail, $client) = @_;
3940: my ($domain,$uname,$type) = split(/:/, $tail);
3941:
3942: my $path=&propath($domain,$uname).
3943: '/userfiles/internal/studentphoto.'.$type;
3944: if (-e $path) {
3945: &Reply($client,"ok\n","$cmd:$tail");
3946: return 1;
3947: }
3948: &mkpath($path);
3949: my $file=&localstudentphoto::fetch($domain,$uname);
3950: if (!$file) {
3951: &Failure($client,"unavailable\n","$cmd:$tail");
3952: return 1;
3953: }
3954: if (!-e $path) { &convert_photo($file,$path); }
3955: if (-e $path) {
3956: &Reply($client,"ok\n","$cmd:$tail");
3957: return 1;
3958: }
3959: &Failure($client,"unable_to_convert\n","$cmd:$tail");
3960: return 1;
3961: }
3962: ®ister_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
3963:
3964: # mkpath makes all directories for a file, expects an absolute path with a
3965: # file or a trailing / if just a dir is passed
3966: # returns 1 on success 0 on failure
3967: sub mkpath {
3968: my ($file)=@_;
3969: my @parts=split(/\//,$file,-1);
3970: my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
3971: for (my $i=3;$i<= ($#parts-1);$i++) {
3972: $now.='/'.$parts[$i];
3973: if (!-e $now) {
3974: if (!mkdir($now,0770)) { return 0; }
3975: }
3976: }
3977: return 1;
3978: }
3979:
3980: #---------------------------------------------------------------
3981: #
3982: # Getting, decoding and dispatching requests:
3983: #
3984: #
3985: # Get a Request:
3986: # Gets a Request message from the client. The transaction
3987: # is defined as a 'line' of text. We remove the new line
3988: # from the text line.
3989: #
3990: sub get_request {
3991: my $input = <$client>;
3992: chomp($input);
3993:
3994: &Debug("get_request: Request = $input\n");
3995:
3996: &status('Processing '.$clientname.':'.$input);
3997:
3998: return $input;
3999: }
4000: #---------------------------------------------------------------
4001: #
4002: # Process a request. This sub should shrink as each action
4003: # gets farmed out into a separat sub that is registered
4004: # with the dispatch hash.
4005: #
4006: # Parameters:
4007: # user_input - The request received from the client (lonc).
4008: # Returns:
4009: # true to keep processing, false if caller should exit.
4010: #
4011: sub process_request {
4012: my ($userinput) = @_; # Easier for now to break style than to
4013: # fix all the userinput -> user_input.
4014: my $wasenc = 0; # True if request was encrypted.
4015: # ------------------------------------------------------------ See if encrypted
4016: if ($userinput =~ /^enc/) {
4017: $userinput = decipher($userinput);
4018: $wasenc=1;
4019: if(!$userinput) { # Cipher not defined.
4020: &Failure($client, "error: Encrypted data without negotated key\n");
4021: return 0;
4022: }
4023: }
4024: Debug("process_request: $userinput\n");
4025:
4026: #
4027: # The 'correct way' to add a command to lond is now to
4028: # write a sub to execute it and Add it to the command dispatch
4029: # hash via a call to register_handler.. The comments to that
4030: # sub should give you enough to go on to show how to do this
4031: # along with the examples that are building up as this code
4032: # is getting refactored. Until all branches of the
4033: # if/elseif monster below have been factored out into
4034: # separate procesor subs, if the dispatch hash is missing
4035: # the command keyword, we will fall through to the remainder
4036: # of the if/else chain below in order to keep this thing in
4037: # working order throughout the transmogrification.
4038:
4039: my ($command, $tail) = split(/:/, $userinput, 2);
4040: chomp($command);
4041: chomp($tail);
4042: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
4043: $command =~ s/(\r)//; # And this too for parameterless commands.
4044: if(!$tail) {
4045: $tail =""; # defined but blank.
4046: }
4047:
4048: &Debug("Command received: $command, encoded = $wasenc");
4049:
4050: if(defined $Dispatcher{$command}) {
4051:
4052: my $dispatch_info = $Dispatcher{$command};
4053: my $handler = $$dispatch_info[0];
4054: my $need_encode = $$dispatch_info[1];
4055: my $client_types = $$dispatch_info[2];
4056: Debug("Matched dispatch hash: mustencode: $need_encode "
4057: ."ClientType $client_types");
4058:
4059: # Validate the request:
4060:
4061: my $ok = 1;
4062: my $requesterprivs = 0;
4063: if(&isClient()) {
4064: $requesterprivs |= $CLIENT_OK;
4065: }
4066: if(&isManager()) {
4067: $requesterprivs |= $MANAGER_OK;
4068: }
4069: if($need_encode && (!$wasenc)) {
4070: Debug("Must encode but wasn't: $need_encode $wasenc");
4071: $ok = 0;
4072: }
4073: if(($client_types & $requesterprivs) == 0) {
4074: Debug("Client not privileged to do this operation");
4075: $ok = 0;
4076: }
4077:
4078: if($ok) {
4079: Debug("Dispatching to handler $command $tail");
4080: my $keep_going = &$handler($command, $tail, $client);
4081: return $keep_going;
4082: } else {
4083: Debug("Refusing to dispatch because client did not match requirements");
4084: Failure($client, "refused\n", $userinput);
4085: return 1;
4086: }
4087:
4088: }
4089:
4090: print $client "unknown_cmd\n";
4091: # -------------------------------------------------------------------- complete
4092: Debug("process_request - returning 1");
4093: return 1;
4094: }
4095: #
4096: # Decipher encoded traffic
4097: # Parameters:
4098: # input - Encoded data.
4099: # Returns:
4100: # Decoded data or undef if encryption key was not yet negotiated.
4101: # Implicit input:
4102: # cipher - This global holds the negotiated encryption key.
4103: #
4104: sub decipher {
4105: my ($input) = @_;
4106: my $output = '';
4107:
4108:
4109: if($cipher) {
4110: my($enc, $enclength, $encinput) = split(/:/, $input);
4111: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
4112: $output .=
4113: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
4114: }
4115: return substr($output, 0, $enclength);
4116: } else {
4117: return undef;
4118: }
4119: }
4120:
4121: #
4122: # Register a command processor. This function is invoked to register a sub
4123: # to process a request. Once registered, the ProcessRequest sub can automatically
4124: # dispatch requests to an appropriate sub, and do the top level validity checking
4125: # as well:
4126: # - Is the keyword recognized.
4127: # - Is the proper client type attempting the request.
4128: # - Is the request encrypted if it has to be.
4129: # Parameters:
4130: # $request_name - Name of the request being registered.
4131: # This is the command request that will match
4132: # against the hash keywords to lookup the information
4133: # associated with the dispatch information.
4134: # $procedure - Reference to a sub to call to process the request.
4135: # All subs get called as follows:
4136: # Procedure($cmd, $tail, $replyfd, $key)
4137: # $cmd - the actual keyword that invoked us.
4138: # $tail - the tail of the request that invoked us.
4139: # $replyfd- File descriptor connected to the client
4140: # $must_encode - True if the request must be encoded to be good.
4141: # $client_ok - True if it's ok for a client to request this.
4142: # $manager_ok - True if it's ok for a manager to request this.
4143: # Side effects:
4144: # - On success, the Dispatcher hash has an entry added for the key $RequestName
4145: # - On failure, the program will die as it's a bad internal bug to try to
4146: # register a duplicate command handler.
4147: #
4148: sub register_handler {
4149: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
4150:
4151: # Don't allow duplication#
4152:
4153: if (defined $Dispatcher{$request_name}) {
4154: die "Attempting to define a duplicate request handler for $request_name\n";
4155: }
4156: # Build the client type mask:
4157:
4158: my $client_type_mask = 0;
4159: if($client_ok) {
4160: $client_type_mask |= $CLIENT_OK;
4161: }
4162: if($manager_ok) {
4163: $client_type_mask |= $MANAGER_OK;
4164: }
4165:
4166: # Enter the hash:
4167:
4168: my @entry = ($procedure, $must_encode, $client_type_mask);
4169:
4170: $Dispatcher{$request_name} = \@entry;
4171:
4172: }
4173:
4174:
4175: #------------------------------------------------------------------
4176:
4177:
4178:
4179:
4180: #
4181: # Convert an error return code from lcpasswd to a string value.
4182: #
4183: sub lcpasswdstrerror {
4184: my $ErrorCode = shift;
4185: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
4186: return "lcpasswd Unrecognized error return value ".$ErrorCode;
4187: } else {
4188: return $passwderrors[$ErrorCode];
4189: }
4190: }
4191:
4192: #
4193: # Convert an error return code from lcuseradd to a string value:
4194: #
4195: sub lcuseraddstrerror {
4196: my $ErrorCode = shift;
4197: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
4198: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
4199: } else {
4200: return $adderrors[$ErrorCode];
4201: }
4202: }
4203:
4204: # grabs exception and records it to log before exiting
4205: sub catchexception {
4206: my ($error)=@_;
4207: $SIG{'QUIT'}='DEFAULT';
4208: $SIG{__DIE__}='DEFAULT';
4209: &status("Catching exception");
4210: &logthis("<font color='red'>CRITICAL: "
4211: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
4212: ."a crash with this error msg->[$error]</font>");
4213: &logthis('Famous last words: '.$status.' - '.$lastlog);
4214: if ($client) { print $client "error: $error\n"; }
4215: $server->close();
4216: die($error);
4217: }
4218: sub timeout {
4219: &status("Handling Timeout");
4220: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
4221: &catchexception('Timeout');
4222: }
4223: # -------------------------------- Set signal handlers to record abnormal exits
4224:
4225:
4226: $SIG{'QUIT'}=\&catchexception;
4227: $SIG{__DIE__}=\&catchexception;
4228:
4229: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
4230: &status("Read loncapa.conf and loncapa_apache.conf");
4231: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
4232: %perlvar=%{$perlvarref};
4233: undef $perlvarref;
4234:
4235: # ----------------------------- Make sure this process is running from user=www
4236: my $wwwid=getpwnam('www');
4237: if ($wwwid!=$<) {
4238: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
4239: my $subj="LON: $currenthostid User ID mismatch";
4240: system("echo 'User ID mismatch. lond must be run as user www.' |\
4241: mailto $emailto -s '$subj' > /dev/null");
4242: exit 1;
4243: }
4244:
4245: # --------------------------------------------- Check if other instance running
4246:
4247: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
4248:
4249: if (-e $pidfile) {
4250: my $lfh=IO::File->new("$pidfile");
4251: my $pide=<$lfh>;
4252: chomp($pide);
4253: if (kill 0 => $pide) { die "already running"; }
4254: }
4255:
4256: # ------------------------------------------------------------- Read hosts file
4257:
4258:
4259:
4260: # establish SERVER socket, bind and listen.
4261: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
4262: Type => SOCK_STREAM,
4263: Proto => 'tcp',
4264: Reuse => 1,
4265: Listen => 10 )
4266: or die "making socket: $@\n";
4267:
4268: # --------------------------------------------------------- Do global variables
4269:
4270: # global variables
4271:
4272: my %children = (); # keys are current child process IDs
4273:
4274: sub REAPER { # takes care of dead children
4275: $SIG{CHLD} = \&REAPER;
4276: &status("Handling child death");
4277: my $pid;
4278: do {
4279: $pid = waitpid(-1,&WNOHANG());
4280: if (defined($children{$pid})) {
4281: &logthis("Child $pid died");
4282: delete($children{$pid});
4283: } elsif ($pid > 0) {
4284: &logthis("Unknown Child $pid died");
4285: }
4286: } while ( $pid > 0 );
4287: foreach my $child (keys(%children)) {
4288: $pid = waitpid($child,&WNOHANG());
4289: if ($pid > 0) {
4290: &logthis("Child $child - $pid looks like we missed it's death");
4291: delete($children{$pid});
4292: }
4293: }
4294: &status("Finished Handling child death");
4295: }
4296:
4297: sub HUNTSMAN { # signal handler for SIGINT
4298: &status("Killing children (INT)");
4299: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
4300: kill 'INT' => keys %children;
4301: &logthis("Free socket: ".shutdown($server,2)); # free up socket
4302: my $execdir=$perlvar{'lonDaemons'};
4303: unlink("$execdir/logs/lond.pid");
4304: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
4305: &status("Done killing children");
4306: exit; # clean up with dignity
4307: }
4308:
4309: sub HUPSMAN { # signal handler for SIGHUP
4310: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
4311: &status("Killing children for restart (HUP)");
4312: kill 'INT' => keys %children;
4313: &logthis("Free socket: ".shutdown($server,2)); # free up socket
4314: &logthis("<font color='red'>CRITICAL: Restarting</font>");
4315: my $execdir=$perlvar{'lonDaemons'};
4316: unlink("$execdir/logs/lond.pid");
4317: &status("Restarting self (HUP)");
4318: exec("$execdir/lond"); # here we go again
4319: }
4320:
4321: #
4322: # Kill off hashes that describe the host table prior to re-reading it.
4323: # Hashes affected are:
4324: # %hostid, %hostdom %hostip %hostdns.
4325: #
4326: sub KillHostHashes {
4327: foreach my $key (keys %hostid) {
4328: delete $hostid{$key};
4329: }
4330: foreach my $key (keys %hostdom) {
4331: delete $hostdom{$key};
4332: }
4333: foreach my $key (keys %hostip) {
4334: delete $hostip{$key};
4335: }
4336: foreach my $key (keys %hostdns) {
4337: delete $hostdns{$key};
4338: }
4339: }
4340: #
4341: # Read in the host table from file and distribute it into the various hashes:
4342: #
4343: # - %hostid - Indexed by IP, the loncapa hostname.
4344: # - %hostdom - Indexed by loncapa hostname, the domain.
4345: # - %hostip - Indexed by hostid, the Ip address of the host.
4346: sub ReadHostTable {
4347:
4348: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
4349: my $myloncapaname = $perlvar{'lonHostID'};
4350: Debug("My loncapa name is : $myloncapaname");
4351: while (my $configline=<CONFIG>) {
4352: if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
4353: my ($id,$domain,$role,$name)=split(/:/,$configline);
4354: $name=~s/\s//g;
4355: my $ip = gethostbyname($name);
4356: if (length($ip) ne 4) {
4357: &logthis("Skipping host $id name $name no IP $ip found\n");
4358: next;
4359: }
4360: $ip=inet_ntoa($ip);
4361: $hostid{$ip}=$id; # LonCAPA name of host by IP.
4362: $hostdom{$id}=$domain; # LonCAPA domain name of host.
4363: $hostip{$id}=$ip; # IP address of host.
4364: $hostdns{$name} = $id; # LonCAPA name of host by DNS.
4365:
4366: if ($id eq $perlvar{'lonHostID'}) {
4367: Debug("Found me in the host table: $name");
4368: $thisserver=$name;
4369: }
4370: }
4371: }
4372: close(CONFIG);
4373: }
4374: #
4375: # Reload the Apache daemon's state.
4376: # This is done by invoking /home/httpd/perl/apachereload
4377: # a setuid perl script that can be root for us to do this job.
4378: #
4379: sub ReloadApache {
4380: my $execdir = $perlvar{'lonDaemons'};
4381: my $script = $execdir."/apachereload";
4382: system($script);
4383: }
4384:
4385: #
4386: # Called in response to a USR2 signal.
4387: # - Reread hosts.tab
4388: # - All children connected to hosts that were removed from hosts.tab
4389: # are killed via SIGINT
4390: # - All children connected to previously existing hosts are sent SIGUSR1
4391: # - Our internal hosts hash is updated to reflect the new contents of
4392: # hosts.tab causing connections from hosts added to hosts.tab to
4393: # now be honored.
4394: #
4395: sub UpdateHosts {
4396: &status("Reload hosts.tab");
4397: logthis('<font color="blue"> Updating connections </font>');
4398: #
4399: # The %children hash has the set of IP's we currently have children
4400: # on. These need to be matched against records in the hosts.tab
4401: # Any ip's no longer in the table get killed off they correspond to
4402: # either dropped or changed hosts. Note that the re-read of the table
4403: # will take care of new and changed hosts as connections come into being.
4404:
4405:
4406: KillHostHashes;
4407: ReadHostTable;
4408:
4409: foreach my $child (keys %children) {
4410: my $childip = $children{$child};
4411: if(!$hostid{$childip}) {
4412: logthis('<font color="blue"> UpdateHosts killing child '
4413: ." $child for ip $childip </font>");
4414: kill('INT', $child);
4415: } else {
4416: logthis('<font color="green"> keeping child for ip '
4417: ." $childip (pid=$child) </font>");
4418: }
4419: }
4420: ReloadApache;
4421: &status("Finished reloading hosts.tab");
4422: }
4423:
4424:
4425: sub checkchildren {
4426: &status("Checking on the children (sending signals)");
4427: &initnewstatus();
4428: &logstatus();
4429: &logthis('Going to check on the children');
4430: my $docdir=$perlvar{'lonDocRoot'};
4431: foreach (sort keys %children) {
4432: #sleep 1;
4433: unless (kill 'USR1' => $_) {
4434: &logthis ('Child '.$_.' is dead');
4435: &logstatus($$.' is dead');
4436: delete($children{$_});
4437: }
4438: }
4439: sleep 5;
4440: $SIG{ALRM} = sub { Debug("timeout");
4441: die "timeout"; };
4442: $SIG{__DIE__} = 'DEFAULT';
4443: &status("Checking on the children (waiting for reports)");
4444: foreach (sort keys %children) {
4445: unless (-e "$docdir/lon-status/londchld/$_.txt") {
4446: eval {
4447: alarm(300);
4448: &logthis('Child '.$_.' did not respond');
4449: kill 9 => $_;
4450: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
4451: #$subj="LON: $currenthostid killed lond process $_";
4452: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
4453: #$execdir=$perlvar{'lonDaemons'};
4454: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
4455: delete($children{$_});
4456: alarm(0);
4457: }
4458: }
4459: }
4460: $SIG{ALRM} = 'DEFAULT';
4461: $SIG{__DIE__} = \&catchexception;
4462: &status("Finished checking children");
4463: &logthis('Finished Checking children');
4464: }
4465:
4466: # --------------------------------------------------------------------- Logging
4467:
4468: sub logthis {
4469: my $message=shift;
4470: my $execdir=$perlvar{'lonDaemons'};
4471: my $fh=IO::File->new(">>$execdir/logs/lond.log");
4472: my $now=time;
4473: my $local=localtime($now);
4474: $lastlog=$local.': '.$message;
4475: print $fh "$local ($$): $message\n";
4476: }
4477:
4478: # ------------------------- Conditional log if $DEBUG true.
4479: sub Debug {
4480: my $message = shift;
4481: if($DEBUG) {
4482: &logthis($message);
4483: }
4484: }
4485:
4486: #
4487: # Sub to do replies to client.. this gives a hook for some
4488: # debug tracing too:
4489: # Parameters:
4490: # fd - File open on client.
4491: # reply - Text to send to client.
4492: # request - Original request from client.
4493: #
4494: sub Reply {
4495: my ($fd, $reply, $request) = @_;
4496: print $fd $reply;
4497: Debug("Request was $request Reply was $reply");
4498:
4499: $Transactions++;
4500:
4501:
4502: }
4503:
4504:
4505: #
4506: # Sub to report a failure.
4507: # This function:
4508: # - Increments the failure statistic counters.
4509: # - Invokes Reply to send the error message to the client.
4510: # Parameters:
4511: # fd - File descriptor open on the client
4512: # reply - Reply text to emit.
4513: # request - The original request message (used by Reply
4514: # to debug if that's enabled.
4515: # Implicit outputs:
4516: # $Failures- The number of failures is incremented.
4517: # Reply (invoked here) sends a message to the
4518: # client:
4519: #
4520: sub Failure {
4521: my $fd = shift;
4522: my $reply = shift;
4523: my $request = shift;
4524:
4525: $Failures++;
4526: Reply($fd, $reply, $request); # That's simple eh?
4527: }
4528: # ------------------------------------------------------------------ Log status
4529:
4530: sub logstatus {
4531: &status("Doing logging");
4532: my $docdir=$perlvar{'lonDocRoot'};
4533: {
4534: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
4535: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
4536: $fh->close();
4537: }
4538: &status("Finished $$.txt");
4539: {
4540: open(LOG,">>$docdir/lon-status/londstatus.txt");
4541: flock(LOG,LOCK_EX);
4542: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
4543: .$status."\t".$lastlog."\t $keymode\n";
4544: flock(LOG,LOCK_UN);
4545: close(LOG);
4546: }
4547: &status("Finished logging");
4548: }
4549:
4550: sub initnewstatus {
4551: my $docdir=$perlvar{'lonDocRoot'};
4552: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
4553: my $now=time;
4554: my $local=localtime($now);
4555: print $fh "LOND status $local - parent $$\n\n";
4556: opendir(DIR,"$docdir/lon-status/londchld");
4557: while (my $filename=readdir(DIR)) {
4558: unlink("$docdir/lon-status/londchld/$filename");
4559: }
4560: closedir(DIR);
4561: }
4562:
4563: # -------------------------------------------------------------- Status setting
4564:
4565: sub status {
4566: my $what=shift;
4567: my $now=time;
4568: my $local=localtime($now);
4569: $status=$local.': '.$what;
4570: $0='lond: '.$what.' '.$local;
4571: }
4572:
4573: # -------------------------------------------------------- Escape Special Chars
4574:
4575: sub escape {
4576: my $str=shift;
4577: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
4578: return $str;
4579: }
4580:
4581: # ----------------------------------------------------- Un-Escape Special Chars
4582:
4583: sub unescape {
4584: my $str=shift;
4585: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
4586: return $str;
4587: }
4588:
4589: # ----------------------------------------------------------- Send USR1 to lonc
4590:
4591: sub reconlonc {
4592: my $peerfile=shift;
4593: &logthis("Trying to reconnect for $peerfile");
4594: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
4595: if (my $fh=IO::File->new("$loncfile")) {
4596: my $loncpid=<$fh>;
4597: chomp($loncpid);
4598: if (kill 0 => $loncpid) {
4599: &logthis("lonc at pid $loncpid responding, sending USR1");
4600: kill USR1 => $loncpid;
4601: } else {
4602: &logthis(
4603: "<font color='red'>CRITICAL: "
4604: ."lonc at pid $loncpid not responding, giving up</font>");
4605: }
4606: } else {
4607: &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
4608: }
4609: }
4610:
4611: # -------------------------------------------------- Non-critical communication
4612:
4613: sub subreply {
4614: my ($cmd,$server)=@_;
4615: my $peerfile="$perlvar{'lonSockDir'}/$server";
4616: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
4617: Type => SOCK_STREAM,
4618: Timeout => 10)
4619: or return "con_lost";
4620: print $sclient "$cmd\n";
4621: my $answer=<$sclient>;
4622: chomp($answer);
4623: if (!$answer) { $answer="con_lost"; }
4624: return $answer;
4625: }
4626:
4627: sub reply {
4628: my ($cmd,$server)=@_;
4629: my $answer;
4630: if ($server ne $currenthostid) {
4631: $answer=subreply($cmd,$server);
4632: if ($answer eq 'con_lost') {
4633: $answer=subreply("ping",$server);
4634: if ($answer ne $server) {
4635: &logthis("sub reply: answer != server answer is $answer, server is $server");
4636: &reconlonc("$perlvar{'lonSockDir'}/$server");
4637: }
4638: $answer=subreply($cmd,$server);
4639: }
4640: } else {
4641: $answer='self_reply';
4642: }
4643: return $answer;
4644: }
4645:
4646: # -------------------------------------------------------------- Talk to lonsql
4647:
4648: sub sql_reply {
4649: my ($cmd)=@_;
4650: my $answer=&sub_sql_reply($cmd);
4651: if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
4652: return $answer;
4653: }
4654:
4655: sub sub_sql_reply {
4656: my ($cmd)=@_;
4657: my $unixsock="mysqlsock";
4658: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
4659: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
4660: Type => SOCK_STREAM,
4661: Timeout => 10)
4662: or return "con_lost";
4663: print $sclient "$cmd\n";
4664: my $answer=<$sclient>;
4665: chomp($answer);
4666: if (!$answer) { $answer="con_lost"; }
4667: return $answer;
4668: }
4669:
4670: # -------------------------------------------- Return path to profile directory
4671:
4672: sub propath {
4673: my ($udom,$uname)=@_;
4674: $udom=~s/\W//g;
4675: $uname=~s/\W//g;
4676: my $subdir=$uname.'__';
4677: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
4678: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
4679: return $proname;
4680: }
4681:
4682: # --------------------------------------- Is this the home server of an author?
4683:
4684: sub ishome {
4685: my $author=shift;
4686: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
4687: my ($udom,$uname)=split(/\//,$author);
4688: my $proname=propath($udom,$uname);
4689: if (-e $proname) {
4690: return 'owner';
4691: } else {
4692: return 'not_owner';
4693: }
4694: }
4695:
4696: # ======================================================= Continue main program
4697: # ---------------------------------------------------- Fork once and dissociate
4698:
4699: my $fpid=fork;
4700: exit if $fpid;
4701: die "Couldn't fork: $!" unless defined ($fpid);
4702:
4703: POSIX::setsid() or die "Can't start new session: $!";
4704:
4705: # ------------------------------------------------------- Write our PID on disk
4706:
4707: my $execdir=$perlvar{'lonDaemons'};
4708: open (PIDSAVE,">$execdir/logs/lond.pid");
4709: print PIDSAVE "$$\n";
4710: close(PIDSAVE);
4711: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
4712: &status('Starting');
4713:
4714:
4715:
4716: # ----------------------------------------------------- Install signal handlers
4717:
4718:
4719: $SIG{CHLD} = \&REAPER;
4720: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
4721: $SIG{HUP} = \&HUPSMAN;
4722: $SIG{USR1} = \&checkchildren;
4723: $SIG{USR2} = \&UpdateHosts;
4724:
4725: # Read the host hashes:
4726:
4727: ReadHostTable;
4728:
4729: # --------------------------------------------------------------
4730: # Accept connections. When a connection comes in, it is validated
4731: # and if good, a child process is created to process transactions
4732: # along the connection.
4733:
4734: while (1) {
4735: &status('Starting accept');
4736: $client = $server->accept() or next;
4737: &status('Accepted '.$client.' off to spawn');
4738: make_new_child($client);
4739: &status('Finished spawning');
4740: }
4741:
4742: sub make_new_child {
4743: my $pid;
4744: # my $cipher; # Now global
4745: my $sigset;
4746:
4747: $client = shift;
4748: &status('Starting new child '.$client);
4749: &logthis('<font color="green"> Attempting to start child ('.$client.
4750: ")</font>");
4751: # block signal for fork
4752: $sigset = POSIX::SigSet->new(SIGINT);
4753: sigprocmask(SIG_BLOCK, $sigset)
4754: or die "Can't block SIGINT for fork: $!\n";
4755:
4756: die "fork: $!" unless defined ($pid = fork);
4757:
4758: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
4759: # connection liveness.
4760:
4761: #
4762: # Figure out who we're talking to so we can record the peer in
4763: # the pid hash.
4764: #
4765: my $caller = getpeername($client);
4766: my ($port,$iaddr);
4767: if (defined($caller) && length($caller) > 0) {
4768: ($port,$iaddr)=unpack_sockaddr_in($caller);
4769: } else {
4770: &logthis("Unable to determine who caller was, getpeername returned nothing");
4771: }
4772: if (defined($iaddr)) {
4773: $clientip = inet_ntoa($iaddr);
4774: Debug("Connected with $clientip");
4775: } else {
4776: &logthis("Unable to determine clientip");
4777: $clientip='Unavailable';
4778: }
4779:
4780: if ($pid) {
4781: # Parent records the child's birth and returns.
4782: sigprocmask(SIG_UNBLOCK, $sigset)
4783: or die "Can't unblock SIGINT for fork: $!\n";
4784: $children{$pid} = $clientip;
4785: &status('Started child '.$pid);
4786: return;
4787: } else {
4788: # Child can *not* return from this subroutine.
4789: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
4790: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
4791: #don't get intercepted
4792: $SIG{USR1}= \&logstatus;
4793: $SIG{ALRM}= \&timeout;
4794: $lastlog='Forked ';
4795: $status='Forked';
4796:
4797: # unblock signals
4798: sigprocmask(SIG_UNBLOCK, $sigset)
4799: or die "Can't unblock SIGINT for fork: $!\n";
4800:
4801: # my $tmpsnum=0; # Now global
4802: #---------------------------------------------------- kerberos 5 initialization
4803: &Authen::Krb5::init_context();
4804: &Authen::Krb5::init_ets();
4805:
4806: &status('Accepted connection');
4807: # =============================================================================
4808: # do something with the connection
4809: # -----------------------------------------------------------------------------
4810: # see if we know client and 'check' for spoof IP by ineffective challenge
4811:
4812: ReadManagerTable; # May also be a manager!!
4813:
4814: my $outsideip=$clientip;
4815: if ($clientip eq '127.0.0.1') {
4816: $outsideip=$hostip{$perlvar{'lonHostID'}};
4817: }
4818:
4819: my $clientrec=($hostid{$outsideip} ne undef);
4820: my $ismanager=($managers{$outsideip} ne undef);
4821: $clientname = "[unknonwn]";
4822: if($clientrec) { # Establish client type.
4823: $ConnectionType = "client";
4824: $clientname = $hostid{$outsideip};
4825: if($ismanager) {
4826: $ConnectionType = "both";
4827: }
4828: } else {
4829: $ConnectionType = "manager";
4830: $clientname = $managers{$outsideip};
4831: }
4832: my $clientok;
4833:
4834: if ($clientrec || $ismanager) {
4835: &status("Waiting for init from $clientip $clientname");
4836: &logthis('<font color="yellow">INFO: Connection, '.
4837: $clientip.
4838: " ($clientname) connection type = $ConnectionType </font>" );
4839: &status("Connecting $clientip ($clientname))");
4840: my $remotereq=<$client>;
4841: chomp($remotereq);
4842: Debug("Got init: $remotereq");
4843: my $inikeyword = split(/:/, $remotereq);
4844: if ($remotereq =~ /^init/) {
4845: &sethost("sethost:$perlvar{'lonHostID'}");
4846: #
4847: # If the remote is attempting a local init... give that a try:
4848: #
4849: my ($i, $inittype) = split(/:/, $remotereq);
4850:
4851: # If the connection type is ssl, but I didn't get my
4852: # certificate files yet, then I'll drop back to
4853: # insecure (if allowed).
4854:
4855: if($inittype eq "ssl") {
4856: my ($ca, $cert) = lonssl::CertificateFile;
4857: my $kfile = lonssl::KeyFile;
4858: if((!$ca) ||
4859: (!$cert) ||
4860: (!$kfile)) {
4861: $inittype = ""; # This forces insecure attempt.
4862: &logthis("<font color=\"blue\"> Certificates not "
4863: ."installed -- trying insecure auth</font>");
4864: } else { # SSL certificates are in place so
4865: } # Leave the inittype alone.
4866: }
4867:
4868: if($inittype eq "local") {
4869: my $key = LocalConnection($client, $remotereq);
4870: if($key) {
4871: Debug("Got local key $key");
4872: $clientok = 1;
4873: my $cipherkey = pack("H32", $key);
4874: $cipher = new IDEA($cipherkey);
4875: print $client "ok:local\n";
4876: &logthis('<font color="green"'
4877: . "Successful local authentication </font>");
4878: $keymode = "local"
4879: } else {
4880: Debug("Failed to get local key");
4881: $clientok = 0;
4882: shutdown($client, 3);
4883: close $client;
4884: }
4885: } elsif ($inittype eq "ssl") {
4886: my $key = SSLConnection($client);
4887: if ($key) {
4888: $clientok = 1;
4889: my $cipherkey = pack("H32", $key);
4890: $cipher = new IDEA($cipherkey);
4891: &logthis('<font color="green">'
4892: ."Successfull ssl authentication with $clientname </font>");
4893: $keymode = "ssl";
4894:
4895: } else {
4896: $clientok = 0;
4897: close $client;
4898: }
4899:
4900: } else {
4901: my $ok = InsecureConnection($client);
4902: if($ok) {
4903: $clientok = 1;
4904: &logthis('<font color="green">'
4905: ."Successful insecure authentication with $clientname </font>");
4906: print $client "ok\n";
4907: $keymode = "insecure";
4908: } else {
4909: &logthis('<font color="yellow">'
4910: ."Attempted insecure connection disallowed </font>");
4911: close $client;
4912: $clientok = 0;
4913:
4914: }
4915: }
4916: } else {
4917: &logthis(
4918: "<font color='blue'>WARNING: "
4919: ."$clientip failed to initialize: >$remotereq< </font>");
4920: &status('No init '.$clientip);
4921: }
4922:
4923: } else {
4924: &logthis(
4925: "<font color='blue'>WARNING: Unknown client $clientip</font>");
4926: &status('Hung up on '.$clientip);
4927: }
4928:
4929: if ($clientok) {
4930: # ---------------- New known client connecting, could mean machine online again
4931:
4932: foreach my $id (keys(%hostip)) {
4933: if ($hostip{$id} ne $clientip ||
4934: $hostip{$currenthostid} eq $clientip) {
4935: # no need to try to do recon's to myself
4936: next;
4937: }
4938: &reconlonc("$perlvar{'lonSockDir'}/$id");
4939: }
4940: &logthis("<font color='green'>Established connection: $clientname</font>");
4941: &status('Will listen to '.$clientname);
4942: # ------------------------------------------------------------ Process requests
4943: my $keep_going = 1;
4944: my $user_input;
4945: while(($user_input = get_request) && $keep_going) {
4946: alarm(120);
4947: Debug("Main: Got $user_input\n");
4948: $keep_going = &process_request($user_input);
4949: alarm(0);
4950: &status('Listening to '.$clientname." ($keymode)");
4951: }
4952:
4953: # --------------------------------------------- client unknown or fishy, refuse
4954: } else {
4955: print $client "refused\n";
4956: $client->close();
4957: &logthis("<font color='blue'>WARNING: "
4958: ."Rejected client $clientip, closing connection</font>");
4959: }
4960: }
4961:
4962: # =============================================================================
4963:
4964: &logthis("<font color='red'>CRITICAL: "
4965: ."Disconnect from $clientip ($clientname)</font>");
4966:
4967:
4968: # this exit is VERY important, otherwise the child will become
4969: # a producer of more and more children, forking yourself into
4970: # process death.
4971: exit;
4972:
4973: }
4974: #
4975: # Determine if a user is an author for the indicated domain.
4976: #
4977: # Parameters:
4978: # domain - domain to check in .
4979: # user - Name of user to check.
4980: #
4981: # Return:
4982: # 1 - User is an author for domain.
4983: # 0 - User is not an author for domain.
4984: sub is_author {
4985: my ($domain, $user) = @_;
4986:
4987: &Debug("is_author: $user @ $domain");
4988:
4989: my $hashref = &tie_user_hash($domain, $user, "roles",
4990: &GDBM_READER());
4991:
4992: # Author role should show up as a key /domain/_au
4993:
4994: my $key = "/$domain/_au";
4995: my $value = $hashref->{$key};
4996:
4997: if(defined($value)) {
4998: &Debug("$user @ $domain is an author");
4999: }
5000:
5001: return defined($value);
5002: }
5003: #
5004: # Checks to see if the input roleput request was to set
5005: # an author role. If so, invokes the lchtmldir script to set
5006: # up a correct public_html
5007: # Parameters:
5008: # request - The request sent to the rolesput subchunk.
5009: # We're looking for /domain/_au
5010: # domain - The domain in which the user is having roles doctored.
5011: # user - Name of the user for which the role is being put.
5012: # authtype - The authentication type associated with the user.
5013: #
5014: sub manage_permissions
5015: {
5016:
5017:
5018: my ($request, $domain, $user, $authtype) = @_;
5019:
5020: &Debug("manage_permissions: $request $domain $user $authtype");
5021:
5022: # See if the request is of the form /$domain/_au
5023: if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
5024: my $execdir = $perlvar{'lonDaemons'};
5025: my $userhome= "/home/$user" ;
5026: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
5027: &Debug("Setting homedir permissions for $userhome");
5028: system("$execdir/lchtmldir $userhome $user $authtype");
5029: }
5030: }
5031:
5032:
5033: #
5034: # Return the full path of a user password file, whether it exists or not.
5035: # Parameters:
5036: # domain - Domain in which the password file lives.
5037: # user - name of the user.
5038: # Returns:
5039: # Full passwd path:
5040: #
5041: sub password_path {
5042: my ($domain, $user) = @_;
5043: return &propath($domain, $user).'/passwd';
5044: }
5045:
5046: # Password Filename
5047: # Returns the path to a passwd file given domain and user... only if
5048: # it exists.
5049: # Parameters:
5050: # domain - Domain in which to search.
5051: # user - username.
5052: # Returns:
5053: # - If the password file exists returns its path.
5054: # - If the password file does not exist, returns undefined.
5055: #
5056: sub password_filename {
5057: my ($domain, $user) = @_;
5058:
5059: Debug ("PasswordFilename called: dom = $domain user = $user");
5060:
5061: my $path = &password_path($domain, $user);
5062: Debug("PasswordFilename got path: $path");
5063: if(-e $path) {
5064: return $path;
5065: } else {
5066: return undef;
5067: }
5068: }
5069:
5070: #
5071: # Rewrite the contents of the user's passwd file.
5072: # Parameters:
5073: # domain - domain of the user.
5074: # name - User's name.
5075: # contents - New contents of the file.
5076: # Returns:
5077: # 0 - Failed.
5078: # 1 - Success.
5079: #
5080: sub rewrite_password_file {
5081: my ($domain, $user, $contents) = @_;
5082:
5083: my $file = &password_filename($domain, $user);
5084: if (defined $file) {
5085: my $pf = IO::File->new(">$file");
5086: if($pf) {
5087: print $pf "$contents\n";
5088: return 1;
5089: } else {
5090: return 0;
5091: }
5092: } else {
5093: return 0;
5094: }
5095:
5096: }
5097:
5098: #
5099: # get_auth_type - Determines the authorization type of a user in a domain.
5100:
5101: # Returns the authorization type or nouser if there is no such user.
5102: #
5103: sub get_auth_type
5104: {
5105:
5106: my ($domain, $user) = @_;
5107:
5108: Debug("get_auth_type( $domain, $user ) \n");
5109: my $proname = &propath($domain, $user);
5110: my $passwdfile = "$proname/passwd";
5111: if( -e $passwdfile ) {
5112: my $pf = IO::File->new($passwdfile);
5113: my $realpassword = <$pf>;
5114: chomp($realpassword);
5115: Debug("Password info = $realpassword\n");
5116: my ($authtype, $contentpwd) = split(/:/, $realpassword);
5117: Debug("Authtype = $authtype, content = $contentpwd\n");
5118: return "$authtype:$contentpwd";
5119: } else {
5120: Debug("Returning nouser");
5121: return "nouser";
5122: }
5123: }
5124:
5125: #
5126: # Validate a user given their domain, name and password. This utility
5127: # function is used by both AuthenticateHandler and ChangePasswordHandler
5128: # to validate the login credentials of a user.
5129: # Parameters:
5130: # $domain - The domain being logged into (this is required due to
5131: # the capability for multihomed systems.
5132: # $user - The name of the user being validated.
5133: # $password - The user's propoposed password.
5134: #
5135: # Returns:
5136: # 1 - The domain,user,pasword triplet corresponds to a valid
5137: # user.
5138: # 0 - The domain,user,password triplet is not a valid user.
5139: #
5140: sub validate_user {
5141: my ($domain, $user, $password) = @_;
5142:
5143:
5144: # Why negative ~pi you may well ask? Well this function is about
5145: # authentication, and therefore very important to get right.
5146: # I've initialized the flag that determines whether or not I've
5147: # validated correctly to a value it's not supposed to get.
5148: # At the end of this function. I'll ensure that it's not still that
5149: # value so we don't just wind up returning some accidental value
5150: # as a result of executing an unforseen code path that
5151: # did not set $validated. At the end of valid execution paths,
5152: # validated shoule be 1 for success or 0 for failuer.
5153:
5154: my $validated = -3.14159;
5155:
5156: # How we authenticate is determined by the type of authentication
5157: # the user has been assigned. If the authentication type is
5158: # "nouser", the user does not exist so we will return 0.
5159:
5160: my $contents = &get_auth_type($domain, $user);
5161: my ($howpwd, $contentpwd) = split(/:/, $contents);
5162:
5163: my $null = pack("C",0); # Used by kerberos auth types.
5164:
5165: if ($howpwd ne 'nouser') {
5166:
5167: if($howpwd eq "internal") { # Encrypted is in local password file.
5168: $validated = (crypt($password, $contentpwd) eq $contentpwd);
5169: }
5170: elsif ($howpwd eq "unix") { # User is a normal unix user.
5171: $contentpwd = (getpwnam($user))[1];
5172: if($contentpwd) {
5173: if($contentpwd eq 'x') { # Shadow password file...
5174: my $pwauth_path = "/usr/local/sbin/pwauth";
5175: open PWAUTH, "|$pwauth_path" or
5176: die "Cannot invoke authentication";
5177: print PWAUTH "$user\n$password\n";
5178: close PWAUTH;
5179: $validated = ! $?;
5180:
5181: } else { # Passwords in /etc/passwd.
5182: $validated = (crypt($password,
5183: $contentpwd) eq $contentpwd);
5184: }
5185: } else {
5186: $validated = 0;
5187: }
5188: }
5189: elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
5190: if(! ($password =~ /$null/) ) {
5191: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
5192: "",
5193: $contentpwd,,
5194: 'krbtgt',
5195: $contentpwd,
5196: 1,
5197: $password);
5198: if(!$k4error) {
5199: $validated = 1;
5200: } else {
5201: $validated = 0;
5202: &logthis('krb4: '.$user.', '.$contentpwd.', '.
5203: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
5204: }
5205: } else {
5206: $validated = 0; # Password has a match with null.
5207: }
5208: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
5209: if(!($password =~ /$null/)) { # Null password not allowed.
5210: my $krbclient = &Authen::Krb5::parse_name($user.'@'
5211: .$contentpwd);
5212: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
5213: my $krbserver = &Authen::Krb5::parse_name($krbservice);
5214: my $credentials= &Authen::Krb5::cc_default();
5215: $credentials->initialize($krbclient);
5216: my $krbreturn = &Authen::Krb5::get_in_tkt_with_password($krbclient,
5217: $krbserver,
5218: $password,
5219: $credentials);
5220: $validated = ($krbreturn == 1);
5221: } else {
5222: $validated = 0;
5223: }
5224: } elsif ($howpwd eq "localauth") {
5225: # Authenticate via installation specific authentcation method:
5226: $validated = &localauth::localauth($user,
5227: $password,
5228: $contentpwd);
5229: } else { # Unrecognized auth is also bad.
5230: $validated = 0;
5231: }
5232: } else {
5233: $validated = 0;
5234: }
5235: #
5236: # $validated has the correct stat of the authentication:
5237: #
5238:
5239: unless ($validated != -3.14159) {
5240: # I >really really< want to know if this happens.
5241: # since it indicates that user authentication is badly
5242: # broken in some code path.
5243: #
5244: die "ValidateUser - failed to set the value of validated $domain, $user $password";
5245: }
5246: return $validated;
5247: }
5248:
5249:
5250: sub addline {
5251: my ($fname,$hostid,$ip,$newline)=@_;
5252: my $contents;
5253: my $found=0;
5254: my $expr='^'.$hostid.':'.$ip.':';
5255: $expr =~ s/\./\\\./g;
5256: my $sh;
5257: if ($sh=IO::File->new("$fname.subscription")) {
5258: while (my $subline=<$sh>) {
5259: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
5260: }
5261: $sh->close();
5262: }
5263: $sh=IO::File->new(">$fname.subscription");
5264: if ($contents) { print $sh $contents; }
5265: if ($newline) { print $sh $newline; }
5266: $sh->close();
5267: return $found;
5268: }
5269:
5270: sub get_chat {
5271: my ($cdom,$cname,$udom,$uname)=@_;
5272: my %hash;
5273: my $proname=&propath($cdom,$cname);
5274: my @entries=();
5275: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
5276: &GDBM_READER(),0640)) {
5277: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
5278: untie %hash;
5279: }
5280: my @participants=();
5281: my $cutoff=time-60;
5282: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
5283: &GDBM_WRCREAT(),0640)) {
5284: $hash{$uname.':'.$udom}=time;
5285: foreach (sort keys %hash) {
5286: if ($hash{$_}>$cutoff) {
5287: $participants[$#participants+1]='active_participant:'.$_;
5288: }
5289: }
5290: untie %hash;
5291: }
5292: return (@participants,@entries);
5293: }
5294:
5295: sub chat_add {
5296: my ($cdom,$cname,$newchat)=@_;
5297: my %hash;
5298: my $proname=&propath($cdom,$cname);
5299: my @entries=();
5300: my $time=time;
5301: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
5302: &GDBM_WRCREAT(),0640)) {
5303: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
5304: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
5305: my ($thentime,$idnum)=split(/\_/,$lastid);
5306: my $newid=$time.'_000000';
5307: if ($thentime==$time) {
5308: $idnum=~s/^0+//;
5309: $idnum++;
5310: $idnum=substr('000000'.$idnum,-6,6);
5311: $newid=$time.'_'.$idnum;
5312: }
5313: $hash{$newid}=$newchat;
5314: my $expired=$time-3600;
5315: foreach (keys %hash) {
5316: my ($thistime)=($_=~/(\d+)\_/);
5317: if ($thistime<$expired) {
5318: delete $hash{$_};
5319: }
5320: }
5321: untie %hash;
5322: }
5323: {
5324: my $hfh;
5325: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
5326: print $hfh "$time:".&unescape($newchat)."\n";
5327: }
5328: }
5329: }
5330:
5331: sub unsub {
5332: my ($fname,$clientip)=@_;
5333: my $result;
5334: my $unsubs = 0; # Number of successful unsubscribes:
5335:
5336:
5337: # An old way subscriptions were handled was to have a
5338: # subscription marker file:
5339:
5340: Debug("Attempting unlink of $fname.$clientname");
5341: if (unlink("$fname.$clientname")) {
5342: $unsubs++; # Successful unsub via marker file.
5343: }
5344:
5345: # The more modern way to do it is to have a subscription list
5346: # file:
5347:
5348: if (-e "$fname.subscription") {
5349: my $found=&addline($fname,$clientname,$clientip,'');
5350: if ($found) {
5351: $unsubs++;
5352: }
5353: }
5354:
5355: # If either or both of these mechanisms succeeded in unsubscribing a
5356: # resource we can return ok:
5357:
5358: if($unsubs) {
5359: $result = "ok\n";
5360: } else {
5361: $result = "not_subscribed\n";
5362: }
5363:
5364: return $result;
5365: }
5366:
5367: sub currentversion {
5368: my $fname=shift;
5369: my $version=-1;
5370: my $ulsdir='';
5371: if ($fname=~/^(.+)\/[^\/]+$/) {
5372: $ulsdir=$1;
5373: }
5374: my ($fnamere1,$fnamere2);
5375: # remove version if already specified
5376: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
5377: # get the bits that go before and after the version number
5378: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
5379: $fnamere1=$1;
5380: $fnamere2='.'.$2;
5381: }
5382: if (-e $fname) { $version=1; }
5383: if (-e $ulsdir) {
5384: if(-d $ulsdir) {
5385: if (opendir(LSDIR,$ulsdir)) {
5386: my $ulsfn;
5387: while ($ulsfn=readdir(LSDIR)) {
5388: # see if this is a regular file (ignore links produced earlier)
5389: my $thisfile=$ulsdir.'/'.$ulsfn;
5390: unless (-l $thisfile) {
5391: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
5392: if ($1>$version) { $version=$1; }
5393: }
5394: }
5395: }
5396: closedir(LSDIR);
5397: $version++;
5398: }
5399: }
5400: }
5401: return $version;
5402: }
5403:
5404: sub thisversion {
5405: my $fname=shift;
5406: my $version=-1;
5407: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
5408: $version=$1;
5409: }
5410: return $version;
5411: }
5412:
5413: sub subscribe {
5414: my ($userinput,$clientip)=@_;
5415: my $result;
5416: my ($cmd,$fname)=split(/:/,$userinput);
5417: my $ownership=&ishome($fname);
5418: if ($ownership eq 'owner') {
5419: # explitly asking for the current version?
5420: unless (-e $fname) {
5421: my $currentversion=¤tversion($fname);
5422: if (&thisversion($fname)==$currentversion) {
5423: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
5424: my $root=$1;
5425: my $extension=$2;
5426: symlink($root.'.'.$extension,
5427: $root.'.'.$currentversion.'.'.$extension);
5428: unless ($extension=~/\.meta$/) {
5429: symlink($root.'.'.$extension.'.meta',
5430: $root.'.'.$currentversion.'.'.$extension.'.meta');
5431: }
5432: }
5433: }
5434: }
5435: if (-e $fname) {
5436: if (-d $fname) {
5437: $result="directory\n";
5438: } else {
5439: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
5440: my $now=time;
5441: my $found=&addline($fname,$clientname,$clientip,
5442: "$clientname:$clientip:$now\n");
5443: if ($found) { $result="$fname\n"; }
5444: # if they were subscribed to only meta data, delete that
5445: # subscription, when you subscribe to a file you also get
5446: # the metadata
5447: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
5448: $fname=~s/\/home\/httpd\/html\/res/raw/;
5449: $fname="http://$thisserver/".$fname;
5450: $result="$fname\n";
5451: }
5452: } else {
5453: $result="not_found\n";
5454: }
5455: } else {
5456: $result="rejected\n";
5457: }
5458: return $result;
5459: }
5460:
5461: sub make_passwd_file {
5462: my ($uname, $umode,$npass,$passfilename)=@_;
5463: my $result="ok\n";
5464: if ($umode eq 'krb4' or $umode eq 'krb5') {
5465: {
5466: my $pf = IO::File->new(">$passfilename");
5467: if ($pf) {
5468: print $pf "$umode:$npass\n";
5469: } else {
5470: $result = "pass_file_failed_error";
5471: }
5472: }
5473: } elsif ($umode eq 'internal') {
5474: my $salt=time;
5475: $salt=substr($salt,6,2);
5476: my $ncpass=crypt($npass,$salt);
5477: {
5478: &Debug("Creating internal auth");
5479: my $pf = IO::File->new(">$passfilename");
5480: if($pf) {
5481: print $pf "internal:$ncpass\n";
5482: } else {
5483: $result = "pass_file_failed_error";
5484: }
5485: }
5486: } elsif ($umode eq 'localauth') {
5487: {
5488: my $pf = IO::File->new(">$passfilename");
5489: if($pf) {
5490: print $pf "localauth:$npass\n";
5491: } else {
5492: $result = "pass_file_failed_error";
5493: }
5494: }
5495: } elsif ($umode eq 'unix') {
5496: {
5497: #
5498: # Don't allow the creation of privileged accounts!!! that would
5499: # be real bad!!!
5500: #
5501: my $uid = getpwnam($uname);
5502: if((defined $uid) && ($uid == 0)) {
5503: &logthis(">>>Attempted to create privilged account blocked");
5504: return "no_priv_account_error\n";
5505: }
5506:
5507: my $execpath ="$perlvar{'lonDaemons'}/"."lcuseradd";
5508:
5509: my $lc_error_file = $execdir."/tmp/lcuseradd".$$.".status";
5510: {
5511: &Debug("Executing external: ".$execpath);
5512: &Debug("user = ".$uname.", Password =". $npass);
5513: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
5514: print $se "$uname\n";
5515: print $se "$npass\n";
5516: print $se "$npass\n";
5517: print $se "$lc_error_file\n"; # Status -> unique file.
5518: }
5519: my $error = IO::File->new("< $lc_error_file");
5520: my $useraddok = <$error>;
5521: $error->close;
5522: unlink($lc_error_file);
5523:
5524: chomp $useraddok;
5525:
5526: if($useraddok > 0) {
5527: my $error_text = &lcuseraddstrerror($useraddok);
5528: &logthis("Failed lcuseradd: $error_text");
5529: $result = "lcuseradd_failed:$error_text\n";
5530: } else {
5531: my $pf = IO::File->new(">$passfilename");
5532: if($pf) {
5533: print $pf "unix:\n";
5534: } else {
5535: $result = "pass_file_failed_error";
5536: }
5537: }
5538: }
5539: } elsif ($umode eq 'none') {
5540: {
5541: my $pf = IO::File->new("> $passfilename");
5542: if($pf) {
5543: print $pf "none:\n";
5544: } else {
5545: $result = "pass_file_failed_error";
5546: }
5547: }
5548: } else {
5549: $result="auth_mode_error\n";
5550: }
5551: return $result;
5552: }
5553:
5554: sub convert_photo {
5555: my ($start,$dest)=@_;
5556: system("convert $start $dest");
5557: }
5558:
5559: sub sethost {
5560: my ($remotereq) = @_;
5561: my (undef,$hostid)=split(/:/,$remotereq);
5562: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
5563: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
5564: $currenthostid =$hostid;
5565: $currentdomainid=$hostdom{$hostid};
5566: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
5567: } else {
5568: &logthis("Requested host id $hostid not an alias of ".
5569: $perlvar{'lonHostID'}." refusing connection");
5570: return 'unable_to_set';
5571: }
5572: return 'ok';
5573: }
5574:
5575: sub version {
5576: my ($userinput)=@_;
5577: $remoteVERSION=(split(/:/,$userinput))[1];
5578: return "version:$VERSION";
5579: }
5580:
5581: #There is a copy of this in lonnet.pm
5582: sub userload {
5583: my $numusers=0;
5584: {
5585: opendir(LONIDS,$perlvar{'lonIDsDir'});
5586: my $filename;
5587: my $curtime=time;
5588: while ($filename=readdir(LONIDS)) {
5589: if ($filename eq '.' || $filename eq '..') {next;}
5590: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
5591: if ($curtime-$mtime < 1800) { $numusers++; }
5592: }
5593: closedir(LONIDS);
5594: }
5595: my $userloadpercent=0;
5596: my $maxuserload=$perlvar{'lonUserLoadLim'};
5597: if ($maxuserload) {
5598: $userloadpercent=100*$numusers/$maxuserload;
5599: }
5600: $userloadpercent=sprintf("%.2f",$userloadpercent);
5601: return $userloadpercent;
5602: }
5603:
5604: # Routines for serializing arrays and hashes (copies from lonnet)
5605:
5606: sub array2str {
5607: my (@array) = @_;
5608: my $result=&arrayref2str(\@array);
5609: $result=~s/^__ARRAY_REF__//;
5610: $result=~s/__END_ARRAY_REF__$//;
5611: return $result;
5612: }
5613:
5614: sub arrayref2str {
5615: my ($arrayref) = @_;
5616: my $result='__ARRAY_REF__';
5617: foreach my $elem (@$arrayref) {
5618: if(ref($elem) eq 'ARRAY') {
5619: $result.=&arrayref2str($elem).'&';
5620: } elsif(ref($elem) eq 'HASH') {
5621: $result.=&hashref2str($elem).'&';
5622: } elsif(ref($elem)) {
5623: #print("Got a ref of ".(ref($elem))." skipping.");
5624: } else {
5625: $result.=&escape($elem).'&';
5626: }
5627: }
5628: $result=~s/\&$//;
5629: $result .= '__END_ARRAY_REF__';
5630: return $result;
5631: }
5632:
5633: sub hash2str {
5634: my (%hash) = @_;
5635: my $result=&hashref2str(\%hash);
5636: $result=~s/^__HASH_REF__//;
5637: $result=~s/__END_HASH_REF__$//;
5638: return $result;
5639: }
5640:
5641: sub hashref2str {
5642: my ($hashref)=@_;
5643: my $result='__HASH_REF__';
5644: foreach (sort(keys(%$hashref))) {
5645: if (ref($_) eq 'ARRAY') {
5646: $result.=&arrayref2str($_).'=';
5647: } elsif (ref($_) eq 'HASH') {
5648: $result.=&hashref2str($_).'=';
5649: } elsif (ref($_)) {
5650: $result.='=';
5651: #print("Got a ref of ".(ref($_))." skipping.");
5652: } else {
5653: if ($_) {$result.=&escape($_).'=';} else { last; }
5654: }
5655:
5656: if(ref($hashref->{$_}) eq 'ARRAY') {
5657: $result.=&arrayref2str($hashref->{$_}).'&';
5658: } elsif(ref($hashref->{$_}) eq 'HASH') {
5659: $result.=&hashref2str($hashref->{$_}).'&';
5660: } elsif(ref($hashref->{$_})) {
5661: $result.='&';
5662: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
5663: } else {
5664: $result.=&escape($hashref->{$_}).'&';
5665: }
5666: }
5667: $result=~s/\&$//;
5668: $result .= '__END_HASH_REF__';
5669: return $result;
5670: }
5671:
5672: # ----------------------------------- POD (plain old documentation, CPAN style)
5673:
5674: =head1 NAME
5675:
5676: lond - "LON Daemon" Server (port "LOND" 5663)
5677:
5678: =head1 SYNOPSIS
5679:
5680: Usage: B<lond>
5681:
5682: Should only be run as user=www. This is a command-line script which
5683: is invoked by B<loncron>. There is no expectation that a typical user
5684: will manually start B<lond> from the command-line. (In other words,
5685: DO NOT START B<lond> YOURSELF.)
5686:
5687: =head1 DESCRIPTION
5688:
5689: There are two characteristics associated with the running of B<lond>,
5690: PROCESS MANAGEMENT (starting, stopping, handling child processes)
5691: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
5692: subscriptions, etc). These are described in two large
5693: sections below.
5694:
5695: B<PROCESS MANAGEMENT>
5696:
5697: Preforker - server who forks first. Runs as a daemon. HUPs.
5698: Uses IDEA encryption
5699:
5700: B<lond> forks off children processes that correspond to the other servers
5701: in the network. Management of these processes can be done at the
5702: parent process level or the child process level.
5703:
5704: B<logs/lond.log> is the location of log messages.
5705:
5706: The process management is now explained in terms of linux shell commands,
5707: subroutines internal to this code, and signal assignments:
5708:
5709: =over 4
5710:
5711: =item *
5712:
5713: PID is stored in B<logs/lond.pid>
5714:
5715: This is the process id number of the parent B<lond> process.
5716:
5717: =item *
5718:
5719: SIGTERM and SIGINT
5720:
5721: Parent signal assignment:
5722: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
5723:
5724: Child signal assignment:
5725: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
5726: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
5727: to restart a new child.)
5728:
5729: Command-line invocations:
5730: B<kill> B<-s> SIGTERM I<PID>
5731: B<kill> B<-s> SIGINT I<PID>
5732:
5733: Subroutine B<HUNTSMAN>:
5734: This is only invoked for the B<lond> parent I<PID>.
5735: This kills all the children, and then the parent.
5736: The B<lonc.pid> file is cleared.
5737:
5738: =item *
5739:
5740: SIGHUP
5741:
5742: Current bug:
5743: This signal can only be processed the first time
5744: on the parent process. Subsequent SIGHUP signals
5745: have no effect.
5746:
5747: Parent signal assignment:
5748: $SIG{HUP} = \&HUPSMAN;
5749:
5750: Child signal assignment:
5751: none (nothing happens)
5752:
5753: Command-line invocations:
5754: B<kill> B<-s> SIGHUP I<PID>
5755:
5756: Subroutine B<HUPSMAN>:
5757: This is only invoked for the B<lond> parent I<PID>,
5758: This kills all the children, and then the parent.
5759: The B<lond.pid> file is cleared.
5760:
5761: =item *
5762:
5763: SIGUSR1
5764:
5765: Parent signal assignment:
5766: $SIG{USR1} = \&USRMAN;
5767:
5768: Child signal assignment:
5769: $SIG{USR1}= \&logstatus;
5770:
5771: Command-line invocations:
5772: B<kill> B<-s> SIGUSR1 I<PID>
5773:
5774: Subroutine B<USRMAN>:
5775: When invoked for the B<lond> parent I<PID>,
5776: SIGUSR1 is sent to all the children, and the status of
5777: each connection is logged.
5778:
5779: =item *
5780:
5781: SIGUSR2
5782:
5783: Parent Signal assignment:
5784: $SIG{USR2} = \&UpdateHosts
5785:
5786: Child signal assignment:
5787: NONE
5788:
5789:
5790: =item *
5791:
5792: SIGCHLD
5793:
5794: Parent signal assignment:
5795: $SIG{CHLD} = \&REAPER;
5796:
5797: Child signal assignment:
5798: none
5799:
5800: Command-line invocations:
5801: B<kill> B<-s> SIGCHLD I<PID>
5802:
5803: Subroutine B<REAPER>:
5804: This is only invoked for the B<lond> parent I<PID>.
5805: Information pertaining to the child is removed.
5806: The socket port is cleaned up.
5807:
5808: =back
5809:
5810: B<SERVER-SIDE ACTIVITIES>
5811:
5812: Server-side information can be accepted in an encrypted or non-encrypted
5813: method.
5814:
5815: =over 4
5816:
5817: =item ping
5818:
5819: Query a client in the hosts.tab table; "Are you there?"
5820:
5821: =item pong
5822:
5823: Respond to a ping query.
5824:
5825: =item ekey
5826:
5827: Read in encrypted key, make cipher. Respond with a buildkey.
5828:
5829: =item load
5830:
5831: Respond with CPU load based on a computation upon /proc/loadavg.
5832:
5833: =item currentauth
5834:
5835: Reply with current authentication information (only over an
5836: encrypted channel).
5837:
5838: =item auth
5839:
5840: Only over an encrypted channel, reply as to whether a user's
5841: authentication information can be validated.
5842:
5843: =item passwd
5844:
5845: Allow for a password to be set.
5846:
5847: =item makeuser
5848:
5849: Make a user.
5850:
5851: =item passwd
5852:
5853: Allow for authentication mechanism and password to be changed.
5854:
5855: =item home
5856:
5857: Respond to a question "are you the home for a given user?"
5858:
5859: =item update
5860:
5861: Update contents of a subscribed resource.
5862:
5863: =item unsubscribe
5864:
5865: The server is unsubscribing from a resource.
5866:
5867: =item subscribe
5868:
5869: The server is subscribing to a resource.
5870:
5871: =item log
5872:
5873: Place in B<logs/lond.log>
5874:
5875: =item put
5876:
5877: stores hash in namespace
5878:
5879: =item rolesputy
5880:
5881: put a role into a user's environment
5882:
5883: =item get
5884:
5885: returns hash with keys from array
5886: reference filled in from namespace
5887:
5888: =item eget
5889:
5890: returns hash with keys from array
5891: reference filled in from namesp (encrypts the return communication)
5892:
5893: =item rolesget
5894:
5895: get a role from a user's environment
5896:
5897: =item del
5898:
5899: deletes keys out of array from namespace
5900:
5901: =item keys
5902:
5903: returns namespace keys
5904:
5905: =item dump
5906:
5907: dumps the complete (or key matching regexp) namespace into a hash
5908:
5909: =item store
5910:
5911: stores hash permanently
5912: for this url; hashref needs to be given and should be a \%hashname; the
5913: remaining args aren't required and if they aren't passed or are '' they will
5914: be derived from the ENV
5915:
5916: =item restore
5917:
5918: returns a hash for a given url
5919:
5920: =item querysend
5921:
5922: Tells client about the lonsql process that has been launched in response
5923: to a sent query.
5924:
5925: =item queryreply
5926:
5927: Accept information from lonsql and make appropriate storage in temporary
5928: file space.
5929:
5930: =item idput
5931:
5932: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
5933: for each student, defined perhaps by the institutional Registrar.)
5934:
5935: =item idget
5936:
5937: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
5938: for each student, defined perhaps by the institutional Registrar.)
5939:
5940: =item tmpput
5941:
5942: Accept and store information in temporary space.
5943:
5944: =item tmpget
5945:
5946: Send along temporarily stored information.
5947:
5948: =item ls
5949:
5950: List part of a user's directory.
5951:
5952: =item pushtable
5953:
5954: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
5955: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
5956: must be restored manually in case of a problem with the new table file.
5957: pushtable requires that the request be encrypted and validated via
5958: ValidateManager. The form of the command is:
5959: enc:pushtable tablename <tablecontents> \n
5960: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
5961: cleartext newline.
5962:
5963: =item Hanging up (exit or init)
5964:
5965: What to do when a client tells the server that they (the client)
5966: are leaving the network.
5967:
5968: =item unknown command
5969:
5970: If B<lond> is sent an unknown command (not in the list above),
5971: it replys to the client "unknown_cmd".
5972:
5973:
5974: =item UNKNOWN CLIENT
5975:
5976: If the anti-spoofing algorithm cannot verify the client,
5977: the client is rejected (with a "refused" message sent
5978: to the client, and the connection is closed.
5979:
5980: =back
5981:
5982: =head1 PREREQUISITES
5983:
5984: IO::Socket
5985: IO::File
5986: Apache::File
5987: Symbol
5988: POSIX
5989: Crypt::IDEA
5990: LWP::UserAgent()
5991: GDBM_File
5992: Authen::Krb4
5993: Authen::Krb5
5994:
5995: =head1 COREQUISITES
5996:
5997: =head1 OSNAMES
5998:
5999: linux
6000:
6001: =head1 SCRIPT CATEGORIES
6002:
6003: Server/Process
6004:
6005: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>