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