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