1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
4: #
5: # $Id: lond,v 1.307 2006/01/27 21:45:28 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.307 $'; #' 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: unlink("$fname");
1948: } else {
1949: my $transname="$fname.in.transfer";
1950: my $remoteurl=&reply("sub:$fname","$clientname");
1951: my $response;
1952: alarm(120);
1953: {
1954: my $ua=new LWP::UserAgent;
1955: my $request=new HTTP::Request('GET',"$remoteurl");
1956: $response=$ua->request($request,$transname);
1957: }
1958: alarm(0);
1959: if ($response->is_error()) {
1960: unlink($transname);
1961: my $message=$response->status_line;
1962: &logthis("LWP GET: $message for $fname ($remoteurl)");
1963: } else {
1964: if ($remoteurl!~/\.meta$/) {
1965: alarm(120);
1966: {
1967: my $ua=new LWP::UserAgent;
1968: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1969: my $mresponse=$ua->request($mrequest,$fname.'.meta');
1970: if ($mresponse->is_error()) {
1971: unlink($fname.'.meta');
1972: }
1973: }
1974: alarm(0);
1975: }
1976: rename($transname,$fname);
1977: use Cache::Memcached;
1978: my $memcache=
1979: new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1980: my $url=$fname;
1981: $url=~s-^/home/httpd/html--;
1982: $url=~s-\.meta$--;
1983: my $id=&escape('meta:'.$url);
1984: $memcache->delete($id);
1985: }
1986: }
1987: &Reply( $client, "ok\n", $userinput);
1988: } else {
1989: &Failure($client, "not_found\n", $userinput);
1990: }
1991: } else {
1992: &Failure($client, "rejected\n", $userinput);
1993: }
1994: return 1;
1995: }
1996: ®ister_handler("update", \&update_resource_handler, 0 ,1, 0);
1997:
1998: #
1999: # Fetch a user file from a remote server to the user's home directory
2000: # userfiles subdir.
2001: # Parameters:
2002: # $cmd - The command that got us here.
2003: # $tail - Tail of the command (remaining parameters).
2004: # $client - File descriptor connected to client.
2005: # Returns
2006: # 0 - Requested to exit, caller should shut down.
2007: # 1 - Continue processing.
2008: #
2009: sub fetch_user_file_handler {
2010:
2011: my ($cmd, $tail, $client) = @_;
2012:
2013: my $userinput = "$cmd:$tail";
2014: my $fname = $tail;
2015: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2016: my $udir=&propath($udom,$uname).'/userfiles';
2017: unless (-e $udir) {
2018: mkdir($udir,0770);
2019: }
2020: Debug("fetch user file for $fname");
2021: if (-e $udir) {
2022: $ufile=~s/^[\.\~]+//;
2023:
2024: # IF necessary, create the path right down to the file.
2025: # Note that any regular files in the way of this path are
2026: # wiped out to deal with some earlier folly of mine.
2027:
2028: if (!&mkpath($udir.'/'.$ufile)) {
2029: &Failure($client, "unable_to_create\n", $userinput);
2030: }
2031:
2032: my $destname=$udir.'/'.$ufile;
2033: my $transname=$udir.'/'.$ufile.'.in.transit';
2034: my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
2035: my $response;
2036: Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
2037: alarm(120);
2038: {
2039: my $ua=new LWP::UserAgent;
2040: my $request=new HTTP::Request('GET',"$remoteurl");
2041: $response=$ua->request($request,$transname);
2042: }
2043: alarm(0);
2044: if ($response->is_error()) {
2045: unlink($transname);
2046: my $message=$response->status_line;
2047: &logthis("LWP GET: $message for $fname ($remoteurl)");
2048: &Failure($client, "failed\n", $userinput);
2049: } else {
2050: Debug("Renaming $transname to $destname");
2051: if (!rename($transname,$destname)) {
2052: &logthis("Unable to move $transname to $destname");
2053: unlink($transname);
2054: &Failure($client, "failed\n", $userinput);
2055: } else {
2056: &Reply($client, "ok\n", $userinput);
2057: }
2058: }
2059: } else {
2060: &Failure($client, "not_home\n", $userinput);
2061: }
2062: return 1;
2063: }
2064: ®ister_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
2065:
2066: #
2067: # Remove a file from a user's home directory userfiles subdirectory.
2068: # Parameters:
2069: # cmd - the Lond request keyword that got us here.
2070: # tail - the part of the command past the keyword.
2071: # client- File descriptor connected with the client.
2072: #
2073: # Returns:
2074: # 1 - Continue processing.
2075: sub remove_user_file_handler {
2076: my ($cmd, $tail, $client) = @_;
2077:
2078: my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2079:
2080: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2081: if ($ufile =~m|/\.\./|) {
2082: # any files paths with /../ in them refuse
2083: # to deal with
2084: &Failure($client, "refused\n", "$cmd:$tail");
2085: } else {
2086: my $udir = &propath($udom,$uname);
2087: if (-e $udir) {
2088: my $file=$udir.'/userfiles/'.$ufile;
2089: if (-e $file) {
2090: #
2091: # If the file is a regular file unlink is fine...
2092: # However it's possible the client wants a dir.
2093: # removed, in which case rmdir is more approprate:
2094: #
2095: if (-f $file){
2096: unlink($file);
2097: } elsif(-d $file) {
2098: rmdir($file);
2099: }
2100: if (-e $file) {
2101: # File is still there after we deleted it ?!?
2102:
2103: &Failure($client, "failed\n", "$cmd:$tail");
2104: } else {
2105: &Reply($client, "ok\n", "$cmd:$tail");
2106: }
2107: } else {
2108: &Failure($client, "not_found\n", "$cmd:$tail");
2109: }
2110: } else {
2111: &Failure($client, "not_home\n", "$cmd:$tail");
2112: }
2113: }
2114: return 1;
2115: }
2116: ®ister_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
2117:
2118: #
2119: # make a directory in a user's home directory userfiles subdirectory.
2120: # Parameters:
2121: # cmd - the Lond request keyword that got us here.
2122: # tail - the part of the command past the keyword.
2123: # client- File descriptor connected with the client.
2124: #
2125: # Returns:
2126: # 1 - Continue processing.
2127: sub mkdir_user_file_handler {
2128: my ($cmd, $tail, $client) = @_;
2129:
2130: my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2131: $dir=&unescape($dir);
2132: my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
2133: if ($ufile =~m|/\.\./|) {
2134: # any files paths with /../ in them refuse
2135: # to deal with
2136: &Failure($client, "refused\n", "$cmd:$tail");
2137: } else {
2138: my $udir = &propath($udom,$uname);
2139: if (-e $udir) {
2140: my $newdir=$udir.'/userfiles/'.$ufile.'/';
2141: if (!&mkpath($newdir)) {
2142: &Failure($client, "failed\n", "$cmd:$tail");
2143: }
2144: &Reply($client, "ok\n", "$cmd:$tail");
2145: } else {
2146: &Failure($client, "not_home\n", "$cmd:$tail");
2147: }
2148: }
2149: return 1;
2150: }
2151: ®ister_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
2152:
2153: #
2154: # rename a file in a user's home directory userfiles subdirectory.
2155: # Parameters:
2156: # cmd - the Lond request keyword that got us here.
2157: # tail - the part of the command past the keyword.
2158: # client- File descriptor connected with the client.
2159: #
2160: # Returns:
2161: # 1 - Continue processing.
2162: sub rename_user_file_handler {
2163: my ($cmd, $tail, $client) = @_;
2164:
2165: my ($udom,$uname,$old,$new) = split(/:/, $tail);
2166: $old=&unescape($old);
2167: $new=&unescape($new);
2168: if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
2169: # any files paths with /../ in them refuse to deal with
2170: &Failure($client, "refused\n", "$cmd:$tail");
2171: } else {
2172: my $udir = &propath($udom,$uname);
2173: if (-e $udir) {
2174: my $oldfile=$udir.'/userfiles/'.$old;
2175: my $newfile=$udir.'/userfiles/'.$new;
2176: if (-e $newfile) {
2177: &Failure($client, "exists\n", "$cmd:$tail");
2178: } elsif (! -e $oldfile) {
2179: &Failure($client, "not_found\n", "$cmd:$tail");
2180: } else {
2181: if (!rename($oldfile,$newfile)) {
2182: &Failure($client, "failed\n", "$cmd:$tail");
2183: } else {
2184: &Reply($client, "ok\n", "$cmd:$tail");
2185: }
2186: }
2187: } else {
2188: &Failure($client, "not_home\n", "$cmd:$tail");
2189: }
2190: }
2191: return 1;
2192: }
2193: ®ister_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
2194:
2195: #
2196: # Authenticate access to a user file by checking that the token the user's
2197: # passed also exists in their session file
2198: #
2199: # Parameters:
2200: # cmd - The request keyword that dispatched to tus.
2201: # tail - The tail of the request (colon separated parameters).
2202: # client - Filehandle open on the client.
2203: # Return:
2204: # 1.
2205: sub token_auth_user_file_handler {
2206: my ($cmd, $tail, $client) = @_;
2207:
2208: my ($fname, $session) = split(/:/, $tail);
2209:
2210: chomp($session);
2211: my $reply="non_auth\n";
2212: if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
2213: $session.'.id')) {
2214: while (my $line=<ENVIN>) {
2215: if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply="ok\n"; }
2216: }
2217: close(ENVIN);
2218: &Reply($client, $reply, "$cmd:$tail");
2219: } else {
2220: &Failure($client, "invalid_token\n", "$cmd:$tail");
2221: }
2222: return 1;
2223:
2224: }
2225: ®ister_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
2226:
2227: #
2228: # Unsubscribe from a resource.
2229: #
2230: # Parameters:
2231: # $cmd - The command that got us here.
2232: # $tail - Tail of the command (remaining parameters).
2233: # $client - File descriptor connected to client.
2234: # Returns
2235: # 0 - Requested to exit, caller should shut down.
2236: # 1 - Continue processing.
2237: #
2238: sub unsubscribe_handler {
2239: my ($cmd, $tail, $client) = @_;
2240:
2241: my $userinput= "$cmd:$tail";
2242:
2243: my ($fname) = split(/:/,$tail); # Split in case there's extrs.
2244:
2245: &Debug("Unsubscribing $fname");
2246: if (-e $fname) {
2247: &Debug("Exists");
2248: &Reply($client, &unsub($fname,$clientip), $userinput);
2249: } else {
2250: &Failure($client, "not_found\n", $userinput);
2251: }
2252: return 1;
2253: }
2254: ®ister_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
2255:
2256: # Subscribe to a resource
2257: #
2258: # Parameters:
2259: # $cmd - The command that got us here.
2260: # $tail - Tail of the command (remaining parameters).
2261: # $client - File descriptor connected to client.
2262: # Returns
2263: # 0 - Requested to exit, caller should shut down.
2264: # 1 - Continue processing.
2265: #
2266: sub subscribe_handler {
2267: my ($cmd, $tail, $client)= @_;
2268:
2269: my $userinput = "$cmd:$tail";
2270:
2271: &Reply( $client, &subscribe($userinput,$clientip), $userinput);
2272:
2273: return 1;
2274: }
2275: ®ister_handler("sub", \&subscribe_handler, 0, 1, 0);
2276:
2277: #
2278: # Determine the version of a resource (?) Or is it return
2279: # the top version of the resource? Not yet clear from the
2280: # code in currentversion.
2281: #
2282: # Parameters:
2283: # $cmd - The command that got us here.
2284: # $tail - Tail of the command (remaining parameters).
2285: # $client - File descriptor connected to client.
2286: # Returns
2287: # 0 - Requested to exit, caller should shut down.
2288: # 1 - Continue processing.
2289: #
2290: sub current_version_handler {
2291: my ($cmd, $tail, $client) = @_;
2292:
2293: my $userinput= "$cmd:$tail";
2294:
2295: my $fname = $tail;
2296: &Reply( $client, ¤tversion($fname)."\n", $userinput);
2297: return 1;
2298:
2299: }
2300: ®ister_handler("currentversion", \¤t_version_handler, 0, 1, 0);
2301:
2302: # Make an entry in a user's activity log.
2303: #
2304: # Parameters:
2305: # $cmd - The command that got us here.
2306: # $tail - Tail of the command (remaining parameters).
2307: # $client - File descriptor connected to client.
2308: # Returns
2309: # 0 - Requested to exit, caller should shut down.
2310: # 1 - Continue processing.
2311: #
2312: sub activity_log_handler {
2313: my ($cmd, $tail, $client) = @_;
2314:
2315:
2316: my $userinput= "$cmd:$tail";
2317:
2318: my ($udom,$uname,$what)=split(/:/,$tail);
2319: chomp($what);
2320: my $proname=&propath($udom,$uname);
2321: my $now=time;
2322: my $hfh;
2323: if ($hfh=IO::File->new(">>$proname/activity.log")) {
2324: print $hfh "$now:$clientname:$what\n";
2325: &Reply( $client, "ok\n", $userinput);
2326: } else {
2327: &Failure($client, "error: ".($!+0)." IO::File->new Failed "
2328: ."while attempting log\n",
2329: $userinput);
2330: }
2331:
2332: return 1;
2333: }
2334: ®ister_handler("log", \&activity_log_handler, 0, 1, 0);
2335:
2336: #
2337: # Put a namespace entry in a user profile hash.
2338: # My druthers would be for this to be an encrypted interaction too.
2339: # anything that might be an inadvertent covert channel about either
2340: # user authentication or user personal information....
2341: #
2342: # Parameters:
2343: # $cmd - The command that got us here.
2344: # $tail - Tail of the command (remaining parameters).
2345: # $client - File descriptor connected to client.
2346: # Returns
2347: # 0 - Requested to exit, caller should shut down.
2348: # 1 - Continue processing.
2349: #
2350: sub put_user_profile_entry {
2351: my ($cmd, $tail, $client) = @_;
2352:
2353: my $userinput = "$cmd:$tail";
2354:
2355: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
2356: if ($namespace ne 'roles') {
2357: chomp($what);
2358: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2359: &GDBM_WRCREAT(),"P",$what);
2360: if($hashref) {
2361: my @pairs=split(/\&/,$what);
2362: foreach my $pair (@pairs) {
2363: my ($key,$value)=split(/=/,$pair);
2364: $hashref->{$key}=$value;
2365: }
2366: if (untie(%$hashref)) {
2367: &Reply( $client, "ok\n", $userinput);
2368: } else {
2369: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2370: "while attempting put\n",
2371: $userinput);
2372: }
2373: } else {
2374: &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
2375: "while attempting put\n", $userinput);
2376: }
2377: } else {
2378: &Failure( $client, "refused\n", $userinput);
2379: }
2380:
2381: return 1;
2382: }
2383: ®ister_handler("put", \&put_user_profile_entry, 0, 1, 0);
2384:
2385: # Put a piece of new data in hash, returns error if entry already exists
2386: # Parameters:
2387: # $cmd - The command that got us here.
2388: # $tail - Tail of the command (remaining parameters).
2389: # $client - File descriptor connected to client.
2390: # Returns
2391: # 0 - Requested to exit, caller should shut down.
2392: # 1 - Continue processing.
2393: #
2394: sub newput_user_profile_entry {
2395: my ($cmd, $tail, $client) = @_;
2396:
2397: my $userinput = "$cmd:$tail";
2398:
2399: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
2400: if ($namespace eq 'roles') {
2401: &Failure( $client, "refused\n", $userinput);
2402: return 1;
2403: }
2404:
2405: chomp($what);
2406:
2407: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2408: &GDBM_WRCREAT(),"N",$what);
2409: if(!$hashref) {
2410: &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
2411: "while attempting put\n", $userinput);
2412: return 1;
2413: }
2414:
2415: my @pairs=split(/\&/,$what);
2416: foreach my $pair (@pairs) {
2417: my ($key,$value)=split(/=/,$pair);
2418: if (exists($hashref->{$key})) {
2419: &Failure($client, "key_exists: ".$key."\n",$userinput);
2420: return 1;
2421: }
2422: }
2423:
2424: foreach my $pair (@pairs) {
2425: my ($key,$value)=split(/=/,$pair);
2426: $hashref->{$key}=$value;
2427: }
2428:
2429: if (untie(%$hashref)) {
2430: &Reply( $client, "ok\n", $userinput);
2431: } else {
2432: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2433: "while attempting put\n",
2434: $userinput);
2435: }
2436: return 1;
2437: }
2438: ®ister_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
2439:
2440: #
2441: # Increment a profile entry in the user history file.
2442: # The history contains keyword value pairs. In this case,
2443: # The value itself is a pair of numbers. The first, the current value
2444: # the second an increment that this function applies to the current
2445: # value.
2446: #
2447: # Parameters:
2448: # $cmd - The command that got us here.
2449: # $tail - Tail of the command (remaining parameters).
2450: # $client - File descriptor connected to client.
2451: # Returns
2452: # 0 - Requested to exit, caller should shut down.
2453: # 1 - Continue processing.
2454: #
2455: sub increment_user_value_handler {
2456: my ($cmd, $tail, $client) = @_;
2457:
2458: my $userinput = "$cmd:$tail";
2459:
2460: my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
2461: if ($namespace ne 'roles') {
2462: chomp($what);
2463: my $hashref = &tie_user_hash($udom, $uname,
2464: $namespace, &GDBM_WRCREAT(),
2465: "P",$what);
2466: if ($hashref) {
2467: my @pairs=split(/\&/,$what);
2468: foreach my $pair (@pairs) {
2469: my ($key,$value)=split(/=/,$pair);
2470: $value = &unescape($value);
2471: # We could check that we have a number...
2472: if (! defined($value) || $value eq '') {
2473: $value = 1;
2474: }
2475: $hashref->{$key}+=$value;
2476: if ($namespace eq 'nohist_resourcetracker') {
2477: if ($hashref->{$key} < 0) {
2478: $hashref->{$key} = 0;
2479: }
2480: }
2481: }
2482: if (untie(%$hashref)) {
2483: &Reply( $client, "ok\n", $userinput);
2484: } else {
2485: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2486: "while attempting inc\n", $userinput);
2487: }
2488: } else {
2489: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2490: "while attempting inc\n", $userinput);
2491: }
2492: } else {
2493: &Failure($client, "refused\n", $userinput);
2494: }
2495:
2496: return 1;
2497: }
2498: ®ister_handler("inc", \&increment_user_value_handler, 0, 1, 0);
2499:
2500: #
2501: # Put a new role for a user. Roles are LonCAPA's packaging of permissions.
2502: # Each 'role' a user has implies a set of permissions. Adding a new role
2503: # for a person grants the permissions packaged with that role
2504: # to that user when the role is selected.
2505: #
2506: # Parameters:
2507: # $cmd - The command string (rolesput).
2508: # $tail - The remainder of the request line. For rolesput this
2509: # consists of a colon separated list that contains:
2510: # The domain and user that is granting the role (logged).
2511: # The domain and user that is getting the role.
2512: # The roles being granted as a set of & separated pairs.
2513: # each pair a key value pair.
2514: # $client - File descriptor connected to the client.
2515: # Returns:
2516: # 0 - If the daemon should exit
2517: # 1 - To continue processing.
2518: #
2519: #
2520: sub roles_put_handler {
2521: my ($cmd, $tail, $client) = @_;
2522:
2523: my $userinput = "$cmd:$tail";
2524:
2525: my ( $exedom, $exeuser, $udom, $uname, $what) = split(/:/,$tail);
2526:
2527:
2528: my $namespace='roles';
2529: chomp($what);
2530: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2531: &GDBM_WRCREAT(), "P",
2532: "$exedom:$exeuser:$what");
2533: #
2534: # Log the attempt to set a role. The {}'s here ensure that the file
2535: # handle is open for the minimal amount of time. Since the flush
2536: # is done on close this improves the chances the log will be an un-
2537: # corrupted ordered thing.
2538: if ($hashref) {
2539: my $pass_entry = &get_auth_type($udom, $uname);
2540: my ($auth_type,$pwd) = split(/:/, $pass_entry);
2541: $auth_type = $auth_type.":";
2542: my @pairs=split(/\&/,$what);
2543: foreach my $pair (@pairs) {
2544: my ($key,$value)=split(/=/,$pair);
2545: &manage_permissions($key, $udom, $uname,
2546: $auth_type);
2547: $hashref->{$key}=$value;
2548: }
2549: if (untie($hashref)) {
2550: &Reply($client, "ok\n", $userinput);
2551: } else {
2552: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2553: "while attempting rolesput\n", $userinput);
2554: }
2555: } else {
2556: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2557: "while attempting rolesput\n", $userinput);
2558: }
2559: return 1;
2560: }
2561: ®ister_handler("rolesput", \&roles_put_handler, 1,1,0); # Encoded client only.
2562:
2563: #
2564: # Deletes (removes) a role for a user. This is equivalent to removing
2565: # a permissions package associated with the role from the user's profile.
2566: #
2567: # Parameters:
2568: # $cmd - The command (rolesdel)
2569: # $tail - The remainder of the request line. This consists
2570: # of:
2571: # The domain and user requesting the change (logged)
2572: # The domain and user being changed.
2573: # The roles being revoked. These are shipped to us
2574: # as a bunch of & separated role name keywords.
2575: # $client - The file handle open on the client.
2576: # Returns:
2577: # 1 - Continue processing
2578: # 0 - Exit.
2579: #
2580: sub roles_delete_handler {
2581: my ($cmd, $tail, $client) = @_;
2582:
2583: my $userinput = "$cmd:$tail";
2584:
2585: my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
2586: &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
2587: "what = ".$what);
2588: my $namespace='roles';
2589: chomp($what);
2590: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2591: &GDBM_WRCREAT(), "D",
2592: "$exedom:$exeuser:$what");
2593:
2594: if ($hashref) {
2595: my @rolekeys=split(/\&/,$what);
2596:
2597: foreach my $key (@rolekeys) {
2598: delete $hashref->{$key};
2599: }
2600: if (untie(%$hashref)) {
2601: &Reply($client, "ok\n", $userinput);
2602: } else {
2603: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2604: "while attempting rolesdel\n", $userinput);
2605: }
2606: } else {
2607: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2608: "while attempting rolesdel\n", $userinput);
2609: }
2610:
2611: return 1;
2612: }
2613: ®ister_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
2614:
2615: # Unencrypted get from a user's profile database. See
2616: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
2617: # This function retrieves a keyed item from a specific named database in the
2618: # user's directory.
2619: #
2620: # Parameters:
2621: # $cmd - Command request keyword (get).
2622: # $tail - Tail of the command. This is a colon separated list
2623: # consisting of the domain and username that uniquely
2624: # identifies the profile,
2625: # The 'namespace' which selects the gdbm file to
2626: # do the lookup in,
2627: # & separated list of keys to lookup. Note that
2628: # the values are returned as an & separated list too.
2629: # $client - File descriptor open on the client.
2630: # Returns:
2631: # 1 - Continue processing.
2632: # 0 - Exit.
2633: #
2634: sub get_profile_entry {
2635: my ($cmd, $tail, $client) = @_;
2636:
2637: my $userinput= "$cmd:$tail";
2638:
2639: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2640: chomp($what);
2641:
2642: my $replystring = read_profile($udom, $uname, $namespace, $what);
2643: my ($first) = split(/:/,$replystring);
2644: if($first ne "error") {
2645: &Reply($client, "$replystring\n", $userinput);
2646: } else {
2647: &Failure($client, $replystring." while attempting get\n", $userinput);
2648: }
2649: return 1;
2650:
2651:
2652: }
2653: ®ister_handler("get", \&get_profile_entry, 0,1,0);
2654:
2655: #
2656: # Process the encrypted get request. Note that the request is sent
2657: # in clear, but the reply is encrypted. This is a small covert channel:
2658: # information about the sensitive keys is given to the snooper. Just not
2659: # information about the values of the sensitive key. Hmm if I wanted to
2660: # know these I'd snoop for the egets. Get the profile item names from them
2661: # and then issue a get for them since there's no enforcement of the
2662: # requirement of an encrypted get for particular profile items. If I
2663: # were re-doing this, I'd force the request to be encrypted as well as the
2664: # reply. I'd also just enforce encrypted transactions for all gets since
2665: # that would prevent any covert channel snooping.
2666: #
2667: # Parameters:
2668: # $cmd - Command keyword of request (eget).
2669: # $tail - Tail of the command. See GetProfileEntry
# for more information about this.
2670: # $client - File open on the client.
2671: # Returns:
2672: # 1 - Continue processing
2673: # 0 - server should exit.
2674: sub get_profile_entry_encrypted {
2675: my ($cmd, $tail, $client) = @_;
2676:
2677: my $userinput = "$cmd:$tail";
2678:
2679: my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
2680: chomp($what);
2681: my $qresult = read_profile($udom, $uname, $namespace, $what);
2682: my ($first) = split(/:/, $qresult);
2683: if($first ne "error") {
2684:
2685: if ($cipher) {
2686: my $cmdlength=length($qresult);
2687: $qresult.=" ";
2688: my $encqresult='';
2689: for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
2690: $encqresult.= unpack("H16",
2691: $cipher->encrypt(substr($qresult,
2692: $encidx,
2693: 8)));
2694: }
2695: &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
2696: } else {
2697: &Failure( $client, "error:no_key\n", $userinput);
2698: }
2699: } else {
2700: &Failure($client, "$qresult while attempting eget\n", $userinput);
2701:
2702: }
2703:
2704: return 1;
2705: }
2706: ®ister_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
2707:
2708: #
2709: # Deletes a key in a user profile database.
2710: #
2711: # Parameters:
2712: # $cmd - Command keyword (del).
2713: # $tail - Command tail. IN this case a colon
2714: # separated list containing:
2715: # The domain and user that identifies uniquely
2716: # the identity of the user.
2717: # The profile namespace (name of the profile
2718: # database file).
2719: # & separated list of keywords to delete.
2720: # $client - File open on client socket.
2721: # Returns:
2722: # 1 - Continue processing
2723: # 0 - Exit server.
2724: #
2725: #
2726: sub delete_profile_entry {
2727: my ($cmd, $tail, $client) = @_;
2728:
2729: my $userinput = "cmd:$tail";
2730:
2731: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2732: chomp($what);
2733: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2734: &GDBM_WRCREAT(),
2735: "D",$what);
2736: if ($hashref) {
2737: my @keys=split(/\&/,$what);
2738: foreach my $key (@keys) {
2739: delete($hashref->{$key});
2740: }
2741: if (untie(%$hashref)) {
2742: &Reply($client, "ok\n", $userinput);
2743: } else {
2744: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2745: "while attempting del\n", $userinput);
2746: }
2747: } else {
2748: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2749: "while attempting del\n", $userinput);
2750: }
2751: return 1;
2752: }
2753: ®ister_handler("del", \&delete_profile_entry, 0, 1, 0);
2754:
2755: #
2756: # List the set of keys that are defined in a profile database file.
2757: # A successful reply from this will contain an & separated list of
2758: # the keys.
2759: # Parameters:
2760: # $cmd - Command request (keys).
2761: # $tail - Remainder of the request, a colon separated
2762: # list containing domain/user that identifies the
2763: # user being queried, and the database namespace
2764: # (database filename essentially).
2765: # $client - File open on the client.
2766: # Returns:
2767: # 1 - Continue processing.
2768: # 0 - Exit the server.
2769: #
2770: sub get_profile_keys {
2771: my ($cmd, $tail, $client) = @_;
2772:
2773: my $userinput = "$cmd:$tail";
2774:
2775: my ($udom,$uname,$namespace)=split(/:/,$tail);
2776: my $qresult='';
2777: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2778: &GDBM_READER());
2779: if ($hashref) {
2780: foreach my $key (keys %$hashref) {
2781: $qresult.="$key&";
2782: }
2783: if (untie(%$hashref)) {
2784: $qresult=~s/\&$//;
2785: &Reply($client, "$qresult\n", $userinput);
2786: } else {
2787: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2788: "while attempting keys\n", $userinput);
2789: }
2790: } else {
2791: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2792: "while attempting keys\n", $userinput);
2793: }
2794:
2795: return 1;
2796: }
2797: ®ister_handler("keys", \&get_profile_keys, 0, 1, 0);
2798:
2799: #
2800: # Dump the contents of a user profile database.
2801: # Note that this constitutes a very large covert channel too since
2802: # the dump will return sensitive information that is not encrypted.
2803: # The naive security assumption is that the session negotiation ensures
2804: # our client is trusted and I don't believe that's assured at present.
2805: # Sure want badly to go to ssl or tls. Of course if my peer isn't really
2806: # a LonCAPA node they could have negotiated an encryption key too so >sigh<.
2807: #
2808: # Parameters:
2809: # $cmd - The command request keyword (currentdump).
2810: # $tail - Remainder of the request, consisting of a colon
2811: # separated list that has the domain/username and
2812: # the namespace to dump (database file).
2813: # $client - file open on the remote client.
2814: # Returns:
2815: # 1 - Continue processing.
2816: # 0 - Exit the server.
2817: #
2818: sub dump_profile_database {
2819: my ($cmd, $tail, $client) = @_;
2820:
2821: my $userinput = "$cmd:$tail";
2822:
2823: my ($udom,$uname,$namespace) = split(/:/,$tail);
2824: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2825: &GDBM_READER());
2826: if ($hashref) {
2827: # Structure of %data:
2828: # $data{$symb}->{$parameter}=$value;
2829: # $data{$symb}->{'v.'.$parameter}=$version;
2830: # since $parameter will be unescaped, we do not
2831: # have to worry about silly parameter names...
2832:
2833: my $qresult='';
2834: my %data = (); # A hash of anonymous hashes..
2835: while (my ($key,$value) = each(%$hashref)) {
2836: my ($v,$symb,$param) = split(/:/,$key);
2837: next if ($v eq 'version' || $symb eq 'keys');
2838: next if (exists($data{$symb}) &&
2839: exists($data{$symb}->{$param}) &&
2840: $data{$symb}->{'v.'.$param} > $v);
2841: $data{$symb}->{$param}=$value;
2842: $data{$symb}->{'v.'.$param}=$v;
2843: }
2844: if (untie(%$hashref)) {
2845: while (my ($symb,$param_hash) = each(%data)) {
2846: while(my ($param,$value) = each (%$param_hash)){
2847: next if ($param =~ /^v\./); # Ignore versions...
2848: #
2849: # Just dump the symb=value pairs separated by &
2850: #
2851: $qresult.=$symb.':'.$param.'='.$value.'&';
2852: }
2853: }
2854: chop($qresult);
2855: &Reply($client , "$qresult\n", $userinput);
2856: } else {
2857: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2858: "while attempting currentdump\n", $userinput);
2859: }
2860: } else {
2861: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2862: "while attempting currentdump\n", $userinput);
2863: }
2864:
2865: return 1;
2866: }
2867: ®ister_handler("currentdump", \&dump_profile_database, 0, 1, 0);
2868:
2869: #
2870: # Dump a profile database with an optional regular expression
2871: # to match against the keys. In this dump, no effort is made
2872: # to separate symb from version information. Presumably the
2873: # databases that are dumped by this command are of a different
2874: # structure. Need to look at this and improve the documentation of
2875: # both this and the currentdump handler.
2876: # Parameters:
2877: # $cmd - The command keyword.
2878: # $tail - All of the characters after the $cmd:
2879: # These are expected to be a colon
2880: # separated list containing:
2881: # domain/user - identifying the user.
2882: # namespace - identifying the database.
2883: # regexp - optional regular expression
2884: # that is matched against
2885: # database keywords to do
2886: # selective dumps.
2887: # $client - Channel open on the client.
2888: # Returns:
2889: # 1 - Continue processing.
2890: # Side effects:
2891: # response is written to $client.
2892: #
2893: sub dump_with_regexp {
2894: my ($cmd, $tail, $client) = @_;
2895:
2896:
2897: my $userinput = "$cmd:$tail";
2898:
2899: my ($udom,$uname,$namespace,$regexp,$range)=split(/:/,$tail);
2900: if (defined($regexp)) {
2901: $regexp=&unescape($regexp);
2902: } else {
2903: $regexp='.';
2904: }
2905: my ($start,$end);
2906: if (defined($range)) {
2907: if ($range =~/^(\d+)\-(\d+)$/) {
2908: ($start,$end) = ($1,$2);
2909: } elsif ($range =~/^(\d+)$/) {
2910: ($start,$end) = (0,$1);
2911: } else {
2912: undef($range);
2913: }
2914: }
2915: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2916: &GDBM_READER());
2917: if ($hashref) {
2918: my $qresult='';
2919: my $count=0;
2920: while (my ($key,$value) = each(%$hashref)) {
2921: if ($regexp eq '.') {
2922: $count++;
2923: if (defined($range) && $count >= $end) { last; }
2924: if (defined($range) && $count < $start) { next; }
2925: $qresult.=$key.'='.$value.'&';
2926: } else {
2927: my $unescapeKey = &unescape($key);
2928: if (eval('$unescapeKey=~/$regexp/')) {
2929: $count++;
2930: if (defined($range) && $count >= $end) { last; }
2931: if (defined($range) && $count < $start) { next; }
2932: $qresult.="$key=$value&";
2933: }
2934: }
2935: }
2936: if (untie(%$hashref)) {
2937: chop($qresult);
2938: &Reply($client, "$qresult\n", $userinput);
2939: } else {
2940: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2941: "while attempting dump\n", $userinput);
2942: }
2943: } else {
2944: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2945: "while attempting dump\n", $userinput);
2946: }
2947:
2948: return 1;
2949: }
2950: ®ister_handler("dump", \&dump_with_regexp, 0, 1, 0);
2951:
2952: # Store a set of key=value pairs associated with a versioned name.
2953: #
2954: # Parameters:
2955: # $cmd - Request command keyword.
2956: # $tail - Tail of the request. This is a colon
2957: # separated list containing:
2958: # domain/user - User and authentication domain.
2959: # namespace - Name of the database being modified
2960: # rid - Resource keyword to modify.
2961: # what - new value associated with rid.
2962: #
2963: # $client - Socket open on the client.
2964: #
2965: #
2966: # Returns:
2967: # 1 (keep on processing).
2968: # Side-Effects:
2969: # Writes to the client
2970: sub store_handler {
2971: my ($cmd, $tail, $client) = @_;
2972:
2973: my $userinput = "$cmd:$tail";
2974:
2975: my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
2976: if ($namespace ne 'roles') {
2977:
2978: chomp($what);
2979: my @pairs=split(/\&/,$what);
2980: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2981: &GDBM_WRCREAT(), "S",
2982: "$rid:$what");
2983: if ($hashref) {
2984: my $now = time;
2985: my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
2986: my $key;
2987: $hashref->{"version:$rid"}++;
2988: my $version=$hashref->{"version:$rid"};
2989: my $allkeys='';
2990: foreach my $pair (@pairs) {
2991: my ($key,$value)=split(/=/,$pair);
2992: $allkeys.=$key.':';
2993: $hashref->{"$version:$rid:$key"}=$value;
2994: }
2995: $hashref->{"$version:$rid:timestamp"}=$now;
2996: $allkeys.='timestamp';
2997: $hashref->{"$version:keys:$rid"}=$allkeys;
2998: if (untie($hashref)) {
2999: &Reply($client, "ok\n", $userinput);
3000: } else {
3001: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3002: "while attempting store\n", $userinput);
3003: }
3004: } else {
3005: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3006: "while attempting store\n", $userinput);
3007: }
3008: } else {
3009: &Failure($client, "refused\n", $userinput);
3010: }
3011:
3012: return 1;
3013: }
3014: ®ister_handler("store", \&store_handler, 0, 1, 0);
3015:
3016: #
3017: # Dump out all versions of a resource that has key=value pairs associated
3018: # with it for each version. These resources are built up via the store
3019: # command.
3020: #
3021: # Parameters:
3022: # $cmd - Command keyword.
3023: # $tail - Remainder of the request which consists of:
3024: # domain/user - User and auth. domain.
3025: # namespace - name of resource database.
3026: # rid - Resource id.
3027: # $client - socket open on the client.
3028: #
3029: # Returns:
3030: # 1 indicating the caller should not yet exit.
3031: # Side-effects:
3032: # Writes a reply to the client.
3033: # The reply is a string of the following shape:
3034: # version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
3035: # Where the 1 above represents version 1.
3036: # this continues for all pairs of keys in all versions.
3037: #
3038: #
3039: #
3040: #
3041: sub restore_handler {
3042: my ($cmd, $tail, $client) = @_;
3043:
3044: my $userinput = "$cmd:$tail"; # Only used for logging purposes.
3045:
3046: my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
3047: $namespace=~s/\//\_/g;
3048: $namespace=~s/\W//g;
3049: chomp($rid);
3050: my $proname=&propath($udom,$uname);
3051: my $qresult='';
3052: my %hash;
3053: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
3054: &GDBM_READER(),0640)) {
3055: my $version=$hash{"version:$rid"};
3056: $qresult.="version=$version&";
3057: my $scope;
3058: for ($scope=1;$scope<=$version;$scope++) {
3059: my $vkeys=$hash{"$scope:keys:$rid"};
3060: my @keys=split(/:/,$vkeys);
3061: my $key;
3062: $qresult.="$scope:keys=$vkeys&";
3063: foreach $key (@keys) {
3064: $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
3065: }
3066: }
3067: if (untie(%hash)) {
3068: $qresult=~s/\&$//;
3069: &Reply( $client, "$qresult\n", $userinput);
3070: } else {
3071: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3072: "while attempting restore\n", $userinput);
3073: }
3074: } else {
3075: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3076: "while attempting restore\n", $userinput);
3077: }
3078:
3079: return 1;
3080:
3081:
3082: }
3083: ®ister_handler("restore", \&restore_handler, 0,1,0);
3084:
3085: #
3086: # Add a chat message to to a discussion board.
3087: #
3088: # Parameters:
3089: # $cmd - Request keyword.
3090: # $tail - Tail of the command. A colon separated list
3091: # containing:
3092: # cdom - Domain on which the chat board lives
3093: # cnum - Identifier of the discussion group.
3094: # post - Body of the posting.
3095: # $client - Socket open on the client.
3096: # Returns:
3097: # 1 - Indicating caller should keep on processing.
3098: #
3099: # Side-effects:
3100: # writes a reply to the client.
3101: #
3102: #
3103: sub send_chat_handler {
3104: my ($cmd, $tail, $client) = @_;
3105:
3106:
3107: my $userinput = "$cmd:$tail";
3108:
3109: my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
3110: &chat_add($cdom,$cnum,$newpost);
3111: &Reply($client, "ok\n", $userinput);
3112:
3113: return 1;
3114: }
3115: ®ister_handler("chatsend", \&send_chat_handler, 0, 1, 0);
3116:
3117: #
3118: # Retrieve the set of chat messagss from a discussion board.
3119: #
3120: # Parameters:
3121: # $cmd - Command keyword that initiated the request.
3122: # $tail - Remainder of the request after the command
3123: # keyword. In this case a colon separated list of
3124: # chat domain - Which discussion board.
3125: # chat id - Discussion thread(?)
3126: # domain/user - Authentication domain and username
3127: # of the requesting person.
3128: # $client - Socket open on the client program.
3129: # Returns:
3130: # 1 - continue processing
3131: # Side effects:
3132: # Response is written to the client.
3133: #
3134: sub retrieve_chat_handler {
3135: my ($cmd, $tail, $client) = @_;
3136:
3137:
3138: my $userinput = "$cmd:$tail";
3139:
3140: my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
3141: my $reply='';
3142: foreach (&get_chat($cdom,$cnum,$udom,$uname)) {
3143: $reply.=&escape($_).':';
3144: }
3145: $reply=~s/\:$//;
3146: &Reply($client, $reply."\n", $userinput);
3147:
3148:
3149: return 1;
3150: }
3151: ®ister_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
3152:
3153: #
3154: # Initiate a query of an sql database. SQL query repsonses get put in
3155: # a file for later retrieval. This prevents sql query results from
3156: # bottlenecking the system. Note that with loncnew, perhaps this is
3157: # less of an issue since multiple outstanding requests can be concurrently
3158: # serviced.
3159: #
3160: # Parameters:
3161: # $cmd - COmmand keyword that initiated the request.
3162: # $tail - Remainder of the command after the keyword.
3163: # For this function, this consists of a query and
3164: # 3 arguments that are self-documentingly labelled
3165: # in the original arg1, arg2, arg3.
3166: # $client - Socket open on the client.
3167: # Return:
3168: # 1 - Indicating processing should continue.
3169: # Side-effects:
3170: # a reply is written to $client.
3171: #
3172: sub send_query_handler {
3173: my ($cmd, $tail, $client) = @_;
3174:
3175:
3176: my $userinput = "$cmd:$tail";
3177:
3178: my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
3179: $query=~s/\n*$//g;
3180: &Reply($client, "". &sql_reply("$clientname\&$query".
3181: "\&$arg1"."\&$arg2"."\&$arg3")."\n",
3182: $userinput);
3183:
3184: return 1;
3185: }
3186: ®ister_handler("querysend", \&send_query_handler, 0, 1, 0);
3187:
3188: #
3189: # Add a reply to an sql query. SQL queries are done asyncrhonously.
3190: # The query is submitted via a "querysend" transaction.
3191: # There it is passed on to the lonsql daemon, queued and issued to
3192: # mysql.
3193: # This transaction is invoked when the sql transaction is complete
3194: # it stores the query results in flie and indicates query completion.
3195: # presumably local software then fetches this response... I'm guessing
3196: # the sequence is: lonc does a querysend, we ask lonsql to do it.
3197: # lonsql on completion of the query interacts with the lond of our
3198: # client to do a query reply storing two files:
3199: # - id - The results of the query.
3200: # - id.end - Indicating the transaction completed.
3201: # NOTE: id is a unique id assigned to the query and querysend time.
3202: # Parameters:
3203: # $cmd - Command keyword that initiated this request.
3204: # $tail - Remainder of the tail. In this case that's a colon
3205: # separated list containing the query Id and the
3206: # results of the query.
3207: # $client - Socket open on the client.
3208: # Return:
3209: # 1 - Indicating that we should continue processing.
3210: # Side effects:
3211: # ok written to the client.
3212: #
3213: sub reply_query_handler {
3214: my ($cmd, $tail, $client) = @_;
3215:
3216:
3217: my $userinput = "$cmd:$tail";
3218:
3219: my ($cmd,$id,$reply)=split(/:/,$userinput);
3220: my $store;
3221: my $execdir=$perlvar{'lonDaemons'};
3222: if ($store=IO::File->new(">$execdir/tmp/$id")) {
3223: $reply=~s/\&/\n/g;
3224: print $store $reply;
3225: close $store;
3226: my $store2=IO::File->new(">$execdir/tmp/$id.end");
3227: print $store2 "done\n";
3228: close $store2;
3229: &Reply($client, "ok\n", $userinput);
3230: } else {
3231: &Failure($client, "error: ".($!+0)
3232: ." IO::File->new Failed ".
3233: "while attempting queryreply\n", $userinput);
3234: }
3235:
3236:
3237: return 1;
3238: }
3239: ®ister_handler("queryreply", \&reply_query_handler, 0, 1, 0);
3240:
3241: #
3242: # Process the courseidput request. Not quite sure what this means
3243: # at the system level sense. It appears a gdbm file in the
3244: # /home/httpd/lonUsers/$domain/nohist_courseids is tied and
3245: # a set of entries made in that database.
3246: #
3247: # Parameters:
3248: # $cmd - The command keyword that initiated this request.
3249: # $tail - Tail of the command. In this case consists of a colon
3250: # separated list contaning the domain to apply this to and
3251: # an ampersand separated list of keyword=value pairs.
3252: # Each value is a colon separated list that includes:
3253: # description, institutional code and course owner.
3254: # For backward compatibility with versions included
3255: # in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
3256: # code and/or course owner are preserved from the existing
3257: # record when writing a new record in response to 1.1 or
3258: # 1.2 implementations of lonnet::flushcourselogs().
3259: #
3260: # $client - Socket open on the client.
3261: # Returns:
3262: # 1 - indicating that processing should continue
3263: #
3264: # Side effects:
3265: # reply is written to the client.
3266: #
3267: sub put_course_id_handler {
3268: my ($cmd, $tail, $client) = @_;
3269:
3270:
3271: my $userinput = "$cmd:$tail";
3272:
3273: my ($udom, $what) = split(/:/, $tail,2);
3274: chomp($what);
3275: my $now=time;
3276: my @pairs=split(/\&/,$what);
3277:
3278: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3279: if ($hashref) {
3280: foreach my $pair (@pairs) {
3281: my ($key,$courseinfo) = split(/=/,$pair,2);
3282: $courseinfo =~ s/=/:/g;
3283:
3284: my @current_items = split(/:/,$hashref->{$key});
3285: shift(@current_items); # remove description
3286: pop(@current_items); # remove last access
3287: my $numcurrent = scalar(@current_items);
3288:
3289: my @new_items = split(/:/,$courseinfo);
3290: my $numnew = scalar(@new_items);
3291: if ($numcurrent > 0) {
3292: if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
3293: $courseinfo .= ':'.join(':',@current_items);
3294: } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
3295: $courseinfo .= ':'.$current_items[$numcurrent-1];
3296: }
3297: }
3298: $hashref->{$key}=$courseinfo.':'.$now;
3299: }
3300: if (untie(%$hashref)) {
3301: &Reply( $client, "ok\n", $userinput);
3302: } else {
3303: &Failure($client, "error: ".($!+0)
3304: ." untie(GDBM) Failed ".
3305: "while attempting courseidput\n", $userinput);
3306: }
3307: } else {
3308: &Failure($client, "error: ".($!+0)
3309: ." tie(GDBM) Failed ".
3310: "while attempting courseidput\n", $userinput);
3311: }
3312:
3313:
3314: return 1;
3315: }
3316: ®ister_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
3317:
3318: # Retrieves the value of a course id resource keyword pattern
3319: # defined since a starting date. Both the starting date and the
3320: # keyword pattern are optional. If the starting date is not supplied it
3321: # is treated as the beginning of time. If the pattern is not found,
3322: # it is treatred as "." matching everything.
3323: #
3324: # Parameters:
3325: # $cmd - Command keyword that resulted in us being dispatched.
3326: # $tail - The remainder of the command that, in this case, consists
3327: # of a colon separated list of:
3328: # domain - The domain in which the course database is
3329: # defined.
3330: # since - Optional parameter describing the minimum
3331: # time of definition(?) of the resources that
3332: # will match the dump.
3333: # description - regular expression that is used to filter
3334: # the dump. Only keywords matching this regexp
3335: # will be used.
3336: # institutional code - optional supplied code to filter
3337: # the dump. Only courses with an institutional code
3338: # that match the supplied code will be returned.
3339: # owner - optional supplied username of owner to filter
3340: # the dump. Only courses for which the course
3341: # owner matches the supplied username will be
3342: # returned. Implicit assumption that owner
3343: # is a user in the domain in which the
3344: # course database is defined.
3345: # $client - The socket open on the client.
3346: # Returns:
3347: # 1 - Continue processing.
3348: # Side Effects:
3349: # a reply is written to $client.
3350: sub dump_course_id_handler {
3351: my ($cmd, $tail, $client) = @_;
3352:
3353: my $userinput = "$cmd:$tail";
3354:
3355: my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter) =split(/:/,$tail);
3356: if (defined($description)) {
3357: $description=&unescape($description);
3358: } else {
3359: $description='.';
3360: }
3361: if (defined($instcodefilter)) {
3362: $instcodefilter=&unescape($instcodefilter);
3363: } else {
3364: $instcodefilter='.';
3365: }
3366: if (defined($ownerfilter)) {
3367: $ownerfilter=&unescape($ownerfilter);
3368: } else {
3369: $ownerfilter='.';
3370: }
3371: if (defined($coursefilter)) {
3372: $coursefilter=&unescape($coursefilter);
3373: } else {
3374: $coursefilter='.';
3375: }
3376:
3377: unless (defined($since)) { $since=0; }
3378: my $qresult='';
3379: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3380: if ($hashref) {
3381: while (my ($key,$value) = each(%$hashref)) {
3382: my ($descr,$lasttime,$inst_code,$owner);
3383: my @courseitems = split(/:/,$value);
3384: $lasttime = pop(@courseitems);
3385: ($descr,$inst_code,$owner)=@courseitems;
3386: if ($lasttime<$since) { next; }
3387: my $match = 1;
3388: unless ($description eq '.') {
3389: my $unescapeDescr = &unescape($descr);
3390: unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
3391: $match = 0;
3392: }
3393: }
3394: unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
3395: my $unescapeInstcode = &unescape($inst_code);
3396: unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
3397: $match = 0;
3398: }
3399: }
3400: unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
3401: my $unescapeOwner = &unescape($owner);
3402: unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
3403: $match = 0;
3404: }
3405: }
3406: unless ($coursefilter eq '.' || !defined($coursefilter)) {
3407: my $unescapeCourse = &unescape($key);
3408: unless (eval('$unescapeCourse=~/^$udom(_)\Q$coursefilter\E$/')) {
3409: $match = 0;
3410: }
3411: }
3412: if ($match == 1) {
3413: $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
3414: }
3415: }
3416: if (untie(%$hashref)) {
3417: chop($qresult);
3418: &Reply($client, "$qresult\n", $userinput);
3419: } else {
3420: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3421: "while attempting courseiddump\n", $userinput);
3422: }
3423: } else {
3424: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3425: "while attempting courseiddump\n", $userinput);
3426: }
3427:
3428:
3429: return 1;
3430: }
3431: ®ister_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
3432:
3433: #
3434: # Puts an id to a domains id database.
3435: #
3436: # Parameters:
3437: # $cmd - The command that triggered us.
3438: # $tail - Remainder of the request other than the command. This is a
3439: # colon separated list containing:
3440: # $domain - The domain for which we are writing the id.
3441: # $pairs - The id info to write... this is and & separated list
3442: # of keyword=value.
3443: # $client - Socket open on the client.
3444: # Returns:
3445: # 1 - Continue processing.
3446: # Side effects:
3447: # reply is written to $client.
3448: #
3449: sub put_id_handler {
3450: my ($cmd,$tail,$client) = @_;
3451:
3452:
3453: my $userinput = "$cmd:$tail";
3454:
3455: my ($udom,$what)=split(/:/,$tail);
3456: chomp($what);
3457: my @pairs=split(/\&/,$what);
3458: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
3459: "P", $what);
3460: if ($hashref) {
3461: foreach my $pair (@pairs) {
3462: my ($key,$value)=split(/=/,$pair);
3463: $hashref->{$key}=$value;
3464: }
3465: if (untie(%$hashref)) {
3466: &Reply($client, "ok\n", $userinput);
3467: } else {
3468: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3469: "while attempting idput\n", $userinput);
3470: }
3471: } else {
3472: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3473: "while attempting idput\n", $userinput);
3474: }
3475:
3476: return 1;
3477: }
3478: ®ister_handler("idput", \&put_id_handler, 0, 1, 0);
3479:
3480: #
3481: # Retrieves a set of id values from the id database.
3482: # Returns an & separated list of results, one for each requested id to the
3483: # client.
3484: #
3485: # Parameters:
3486: # $cmd - Command keyword that caused us to be dispatched.
3487: # $tail - Tail of the command. Consists of a colon separated:
3488: # domain - the domain whose id table we dump
3489: # ids Consists of an & separated list of
3490: # id keywords whose values will be fetched.
3491: # nonexisting keywords will have an empty value.
3492: # $client - Socket open on the client.
3493: #
3494: # Returns:
3495: # 1 - indicating processing should continue.
3496: # Side effects:
3497: # An & separated list of results is written to $client.
3498: #
3499: sub get_id_handler {
3500: my ($cmd, $tail, $client) = @_;
3501:
3502:
3503: my $userinput = "$client:$tail";
3504:
3505: my ($udom,$what)=split(/:/,$tail);
3506: chomp($what);
3507: my @queries=split(/\&/,$what);
3508: my $qresult='';
3509: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
3510: if ($hashref) {
3511: for (my $i=0;$i<=$#queries;$i++) {
3512: $qresult.="$hashref->{$queries[$i]}&";
3513: }
3514: if (untie(%$hashref)) {
3515: $qresult=~s/\&$//;
3516: &Reply($client, "$qresult\n", $userinput);
3517: } else {
3518: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3519: "while attempting idget\n",$userinput);
3520: }
3521: } else {
3522: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3523: "while attempting idget\n",$userinput);
3524: }
3525:
3526: return 1;
3527: }
3528: ®ister_handler("idget", \&get_id_handler, 0, 1, 0);
3529:
3530: #
3531: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database
3532: #
3533: # Parameters
3534: # $cmd - Command keyword that caused us to be dispatched.
3535: # $tail - Tail of the command. Consists of a colon separated:
3536: # domain - the domain whose dcmail we are recording
3537: # email Consists of key=value pair
3538: # where key is unique msgid
3539: # and value is message (in XML)
3540: # $client - Socket open on the client.
3541: #
3542: # Returns:
3543: # 1 - indicating processing should continue.
3544: # Side effects
3545: # reply is written to $client.
3546: #
3547: sub put_dcmail_handler {
3548: my ($cmd,$tail,$client) = @_;
3549: my $userinput = "$cmd:$tail";
3550:
3551: my ($udom,$what)=split(/:/,$tail);
3552: chomp($what);
3553: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
3554: if ($hashref) {
3555: my ($key,$value)=split(/=/,$what);
3556: $hashref->{$key}=$value;
3557: }
3558: if (untie(%$hashref)) {
3559: &Reply($client, "ok\n", $userinput);
3560: } else {
3561: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3562: "while attempting dcmailput\n", $userinput);
3563: }
3564: return 1;
3565: }
3566: ®ister_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
3567:
3568: #
3569: # Retrieves broadcast e-mail from nohist_dcmail database
3570: # Returns to client an & separated list of key=value pairs,
3571: # where key is msgid and value is message information.
3572: #
3573: # Parameters
3574: # $cmd - Command keyword that caused us to be dispatched.
3575: # $tail - Tail of the command. Consists of a colon separated:
3576: # domain - the domain whose dcmail table we dump
3577: # startfilter - beginning of time window
3578: # endfilter - end of time window
3579: # sendersfilter - & separated list of username:domain
3580: # for senders to search for.
3581: # $client - Socket open on the client.
3582: #
3583: # Returns:
3584: # 1 - indicating processing should continue.
3585: # Side effects
3586: # reply (& separated list of msgid=messageinfo pairs) is
3587: # written to $client.
3588: #
3589: sub dump_dcmail_handler {
3590: my ($cmd, $tail, $client) = @_;
3591:
3592: my $userinput = "$cmd:$tail";
3593: my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
3594: chomp($sendersfilter);
3595: my @senders = ();
3596: if (defined($startfilter)) {
3597: $startfilter=&unescape($startfilter);
3598: } else {
3599: $startfilter='.';
3600: }
3601: if (defined($endfilter)) {
3602: $endfilter=&unescape($endfilter);
3603: } else {
3604: $endfilter='.';
3605: }
3606: if (defined($sendersfilter)) {
3607: $sendersfilter=&unescape($sendersfilter);
3608: @senders = map { &unescape($_) } split(/\&/,$sendersfilter);
3609: }
3610:
3611: my $qresult='';
3612: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
3613: if ($hashref) {
3614: while (my ($key,$value) = each(%$hashref)) {
3615: my $match = 1;
3616: my ($timestamp,$subj,$uname,$udom) =
3617: split(/:/,&unescape(&unescape($key)),5); # yes, twice really
3618: $subj = &unescape($subj);
3619: unless ($startfilter eq '.' || !defined($startfilter)) {
3620: if ($timestamp < $startfilter) {
3621: $match = 0;
3622: }
3623: }
3624: unless ($endfilter eq '.' || !defined($endfilter)) {
3625: if ($timestamp > $endfilter) {
3626: $match = 0;
3627: }
3628: }
3629: unless (@senders < 1) {
3630: unless (grep/^$uname:$udom$/,@senders) {
3631: $match = 0;
3632: }
3633: }
3634: if ($match == 1) {
3635: $qresult.=$key.'='.$value.'&';
3636: }
3637: }
3638: if (untie(%$hashref)) {
3639: chop($qresult);
3640: &Reply($client, "$qresult\n", $userinput);
3641: } else {
3642: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3643: "while attempting dcmaildump\n", $userinput);
3644: }
3645: } else {
3646: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3647: "while attempting dcmaildump\n", $userinput);
3648: }
3649: return 1;
3650: }
3651:
3652: ®ister_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
3653:
3654: #
3655: # Puts domain roles in nohist_domainroles database
3656: #
3657: # Parameters
3658: # $cmd - Command keyword that caused us to be dispatched.
3659: # $tail - Tail of the command. Consists of a colon separated:
3660: # domain - the domain whose roles we are recording
3661: # role - Consists of key=value pair
3662: # where key is unique role
3663: # and value is start/end date information
3664: # $client - Socket open on the client.
3665: #
3666: # Returns:
3667: # 1 - indicating processing should continue.
3668: # Side effects
3669: # reply is written to $client.
3670: #
3671:
3672: sub put_domainroles_handler {
3673: my ($cmd,$tail,$client) = @_;
3674:
3675: my $userinput = "$cmd:$tail";
3676: my ($udom,$what)=split(/:/,$tail);
3677: chomp($what);
3678: my @pairs=split(/\&/,$what);
3679: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
3680: if ($hashref) {
3681: foreach my $pair (@pairs) {
3682: my ($key,$value)=split(/=/,$pair);
3683: $hashref->{$key}=$value;
3684: }
3685: if (untie(%$hashref)) {
3686: &Reply($client, "ok\n", $userinput);
3687: } else {
3688: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3689: "while attempting domroleput\n", $userinput);
3690: }
3691: } else {
3692: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3693: "while attempting domroleput\n", $userinput);
3694: }
3695:
3696: return 1;
3697: }
3698:
3699: ®ister_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
3700:
3701: #
3702: # Retrieves domain roles from nohist_domainroles database
3703: # Returns to client an & separated list of key=value pairs,
3704: # where key is role and value is start and end date information.
3705: #
3706: # Parameters
3707: # $cmd - Command keyword that caused us to be dispatched.
3708: # $tail - Tail of the command. Consists of a colon separated:
3709: # domain - the domain whose domain roles table we dump
3710: # $client - Socket open on the client.
3711: #
3712: # Returns:
3713: # 1 - indicating processing should continue.
3714: # Side effects
3715: # reply (& separated list of role=start/end info pairs) is
3716: # written to $client.
3717: #
3718: sub dump_domainroles_handler {
3719: my ($cmd, $tail, $client) = @_;
3720:
3721: my $userinput = "$cmd:$tail";
3722: my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
3723: chomp($rolesfilter);
3724: my @roles = ();
3725: if (defined($startfilter)) {
3726: $startfilter=&unescape($startfilter);
3727: } else {
3728: $startfilter='.';
3729: }
3730: if (defined($endfilter)) {
3731: $endfilter=&unescape($endfilter);
3732: } else {
3733: $endfilter='.';
3734: }
3735: if (defined($rolesfilter)) {
3736: $rolesfilter=&unescape($rolesfilter);
3737: @roles = split(/\&/,$rolesfilter);
3738: }
3739:
3740: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
3741: if ($hashref) {
3742: my $qresult = '';
3743: while (my ($key,$value) = each(%$hashref)) {
3744: my $match = 1;
3745: my ($start,$end) = split(/:/,&unescape($value));
3746: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
3747: unless ($startfilter eq '.' || !defined($startfilter)) {
3748: if ($start >= $startfilter) {
3749: $match = 0;
3750: }
3751: }
3752: unless ($endfilter eq '.' || !defined($endfilter)) {
3753: if ($end <= $endfilter) {
3754: $match = 0;
3755: }
3756: }
3757: unless (@roles < 1) {
3758: unless (grep/^$trole$/,@roles) {
3759: $match = 0;
3760: }
3761: }
3762: if ($match == 1) {
3763: $qresult.=$key.'='.$value.'&';
3764: }
3765: }
3766: if (untie(%$hashref)) {
3767: chop($qresult);
3768: &Reply($client, "$qresult\n", $userinput);
3769: } else {
3770: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3771: "while attempting domrolesdump\n", $userinput);
3772: }
3773: } else {
3774: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3775: "while attempting domrolesdump\n", $userinput);
3776: }
3777: return 1;
3778: }
3779:
3780: ®ister_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
3781:
3782:
3783: # Process the tmpput command I'm not sure what this does.. Seems to
3784: # create a file in the lonDaemons/tmp directory of the form $id.tmp
3785: # where Id is the client's ip concatenated with a sequence number.
3786: # The file will contain some value that is passed in. Is this e.g.
3787: # a login token?
3788: #
3789: # Parameters:
3790: # $cmd - The command that got us dispatched.
3791: # $tail - The remainder of the request following $cmd:
3792: # In this case this will be the contents of the file.
3793: # $client - Socket connected to the client.
3794: # Returns:
3795: # 1 indicating processing can continue.
3796: # Side effects:
3797: # A file is created in the local filesystem.
3798: # A reply is sent to the client.
3799: sub tmp_put_handler {
3800: my ($cmd, $what, $client) = @_;
3801:
3802: my $userinput = "$cmd:$what"; # Reconstruct for logging.
3803:
3804:
3805: my $store;
3806: $tmpsnum++;
3807: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
3808: $id=~s/\W/\_/g;
3809: $what=~s/\n//g;
3810: my $execdir=$perlvar{'lonDaemons'};
3811: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
3812: print $store $what;
3813: close $store;
3814: &Reply($client, "$id\n", $userinput);
3815: } else {
3816: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
3817: "while attempting tmpput\n", $userinput);
3818: }
3819: return 1;
3820:
3821: }
3822: ®ister_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
3823:
3824: # Processes the tmpget command. This command returns the contents
3825: # of a temporary resource file(?) created via tmpput.
3826: #
3827: # Paramters:
3828: # $cmd - Command that got us dispatched.
3829: # $id - Tail of the command, contain the id of the resource
3830: # we want to fetch.
3831: # $client - socket open on the client.
3832: # Return:
3833: # 1 - Inidcating processing can continue.
3834: # Side effects:
3835: # A reply is sent to the client.
3836: #
3837: sub tmp_get_handler {
3838: my ($cmd, $id, $client) = @_;
3839:
3840: my $userinput = "$cmd:$id";
3841:
3842:
3843: $id=~s/\W/\_/g;
3844: my $store;
3845: my $execdir=$perlvar{'lonDaemons'};
3846: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
3847: my $reply=<$store>;
3848: &Reply( $client, "$reply\n", $userinput);
3849: close $store;
3850: } else {
3851: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
3852: "while attempting tmpget\n", $userinput);
3853: }
3854:
3855: return 1;
3856: }
3857: ®ister_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
3858:
3859: #
3860: # Process the tmpdel command. This command deletes a temp resource
3861: # created by the tmpput command.
3862: #
3863: # Parameters:
3864: # $cmd - Command that got us here.
3865: # $id - Id of the temporary resource created.
3866: # $client - socket open on the client process.
3867: #
3868: # Returns:
3869: # 1 - Indicating processing should continue.
3870: # Side Effects:
3871: # A file is deleted
3872: # A reply is sent to the client.
3873: sub tmp_del_handler {
3874: my ($cmd, $id, $client) = @_;
3875:
3876: my $userinput= "$cmd:$id";
3877:
3878: chomp($id);
3879: $id=~s/\W/\_/g;
3880: my $execdir=$perlvar{'lonDaemons'};
3881: if (unlink("$execdir/tmp/$id.tmp")) {
3882: &Reply($client, "ok\n", $userinput);
3883: } else {
3884: &Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
3885: "while attempting tmpdel\n", $userinput);
3886: }
3887:
3888: return 1;
3889:
3890: }
3891: ®ister_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
3892:
3893: #
3894: # Processes the setannounce command. This command
3895: # creates a file named announce.txt in the top directory of
3896: # the documentn root and sets its contents. The announce.txt file is
3897: # printed in its entirety at the LonCAPA login page. Note:
3898: # once the announcement.txt fileis created it cannot be deleted.
3899: # However, setting the contents of the file to empty removes the
3900: # announcement from the login page of loncapa so who cares.
3901: #
3902: # Parameters:
3903: # $cmd - The command that got us dispatched.
3904: # $announcement - The text of the announcement.
3905: # $client - Socket open on the client process.
3906: # Retunrns:
3907: # 1 - Indicating request processing should continue
3908: # Side Effects:
3909: # The file {DocRoot}/announcement.txt is created.
3910: # A reply is sent to $client.
3911: #
3912: sub set_announce_handler {
3913: my ($cmd, $announcement, $client) = @_;
3914:
3915: my $userinput = "$cmd:$announcement";
3916:
3917: chomp($announcement);
3918: $announcement=&unescape($announcement);
3919: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
3920: '/announcement.txt')) {
3921: print $store $announcement;
3922: close $store;
3923: &Reply($client, "ok\n", $userinput);
3924: } else {
3925: &Failure($client, "error: ".($!+0)."\n", $userinput);
3926: }
3927:
3928: return 1;
3929: }
3930: ®ister_handler("setannounce", \&set_announce_handler, 0, 1, 0);
3931:
3932: #
3933: # Return the version of the daemon. This can be used to determine
3934: # the compatibility of cross version installations or, alternatively to
3935: # simply know who's out of date and who isn't. Note that the version
3936: # is returned concatenated with the tail.
3937: # Parameters:
3938: # $cmd - the request that dispatched to us.
3939: # $tail - Tail of the request (client's version?).
3940: # $client - Socket open on the client.
3941: #Returns:
3942: # 1 - continue processing requests.
3943: # Side Effects:
3944: # Replies with version to $client.
3945: sub get_version_handler {
3946: my ($cmd, $tail, $client) = @_;
3947:
3948: my $userinput = $cmd.$tail;
3949:
3950: &Reply($client, &version($userinput)."\n", $userinput);
3951:
3952:
3953: return 1;
3954: }
3955: ®ister_handler("version", \&get_version_handler, 0, 1, 0);
3956:
3957: # Set the current host and domain. This is used to support
3958: # multihomed systems. Each IP of the system, or even separate daemons
3959: # on the same IP can be treated as handling a separate lonCAPA virtual
3960: # machine. This command selects the virtual lonCAPA. The client always
3961: # knows the right one since it is lonc and it is selecting the domain/system
3962: # from the hosts.tab file.
3963: # Parameters:
3964: # $cmd - Command that dispatched us.
3965: # $tail - Tail of the command (domain/host requested).
3966: # $socket - Socket open on the client.
3967: #
3968: # Returns:
3969: # 1 - Indicates the program should continue to process requests.
3970: # Side-effects:
3971: # The default domain/system context is modified for this daemon.
3972: # a reply is sent to the client.
3973: #
3974: sub set_virtual_host_handler {
3975: my ($cmd, $tail, $socket) = @_;
3976:
3977: my $userinput ="$cmd:$tail";
3978:
3979: &Reply($client, &sethost($userinput)."\n", $userinput);
3980:
3981:
3982: return 1;
3983: }
3984: ®ister_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
3985:
3986: # Process a request to exit:
3987: # - "bye" is sent to the client.
3988: # - The client socket is shutdown and closed.
3989: # - We indicate to the caller that we should exit.
3990: # Formal Parameters:
3991: # $cmd - The command that got us here.
3992: # $tail - Tail of the command (empty).
3993: # $client - Socket open on the tail.
3994: # Returns:
3995: # 0 - Indicating the program should exit!!
3996: #
3997: sub exit_handler {
3998: my ($cmd, $tail, $client) = @_;
3999:
4000: my $userinput = "$cmd:$tail";
4001:
4002: &logthis("Client $clientip ($clientname) hanging up: $userinput");
4003: &Reply($client, "bye\n", $userinput);
4004: $client->shutdown(2); # shutdown the socket forcibly.
4005: $client->close();
4006:
4007: return 0;
4008: }
4009: ®ister_handler("exit", \&exit_handler, 0,1,1);
4010: ®ister_handler("init", \&exit_handler, 0,1,1);
4011: ®ister_handler("quit", \&exit_handler, 0,1,1);
4012:
4013: # Determine if auto-enrollment is enabled.
4014: # Note that the original had what I believe to be a defect.
4015: # The original returned 0 if the requestor was not a registerd client.
4016: # It should return "refused".
4017: # Formal Parameters:
4018: # $cmd - The command that invoked us.
4019: # $tail - The tail of the command (Extra command parameters.
4020: # $client - The socket open on the client that issued the request.
4021: # Returns:
4022: # 1 - Indicating processing should continue.
4023: #
4024: sub enrollment_enabled_handler {
4025: my ($cmd, $tail, $client) = @_;
4026: my $userinput = $cmd.":".$tail; # For logging purposes.
4027:
4028:
4029: my $cdom = split(/:/, $tail); # Domain we're asking about.
4030: my $outcome = &localenroll::run($cdom);
4031: &Reply($client, "$outcome\n", $userinput);
4032:
4033: return 1;
4034: }
4035: ®ister_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
4036:
4037: # Get the official sections for which auto-enrollment is possible.
4038: # Since the admin people won't know about 'unofficial sections'
4039: # we cannot auto-enroll on them.
4040: # Formal Parameters:
4041: # $cmd - The command request that got us dispatched here.
4042: # $tail - The remainder of the request. In our case this
4043: # will be split into:
4044: # $coursecode - The course name from the admin point of view.
4045: # $cdom - The course's domain(?).
4046: # $client - Socket open on the client.
4047: # Returns:
4048: # 1 - Indiciting processing should continue.
4049: #
4050: sub get_sections_handler {
4051: my ($cmd, $tail, $client) = @_;
4052: my $userinput = "$cmd:$tail";
4053:
4054: my ($coursecode, $cdom) = split(/:/, $tail);
4055: my @secs = &localenroll::get_sections($coursecode,$cdom);
4056: my $seclist = &escape(join(':',@secs));
4057:
4058: &Reply($client, "$seclist\n", $userinput);
4059:
4060:
4061: return 1;
4062: }
4063: ®ister_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
4064:
4065: # Validate the owner of a new course section.
4066: #
4067: # Formal Parameters:
4068: # $cmd - Command that got us dispatched.
4069: # $tail - the remainder of the command. For us this consists of a
4070: # colon separated string containing:
4071: # $inst - Course Id from the institutions point of view.
4072: # $owner - Proposed owner of the course.
4073: # $cdom - Domain of the course (from the institutions
4074: # point of view?)..
4075: # $client - Socket open on the client.
4076: #
4077: # Returns:
4078: # 1 - Processing should continue.
4079: #
4080: sub validate_course_owner_handler {
4081: my ($cmd, $tail, $client) = @_;
4082: my $userinput = "$cmd:$tail";
4083: my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
4084:
4085: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
4086: &Reply($client, "$outcome\n", $userinput);
4087:
4088:
4089:
4090: return 1;
4091: }
4092: ®ister_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
4093:
4094: #
4095: # Validate a course section in the official schedule of classes
4096: # from the institutions point of view (part of autoenrollment).
4097: #
4098: # Formal Parameters:
4099: # $cmd - The command request that got us dispatched.
4100: # $tail - The tail of the command. In this case,
4101: # this is a colon separated set of words that will be split
4102: # into:
4103: # $inst_course_id - The course/section id from the
4104: # institutions point of view.
4105: # $cdom - The domain from the institutions
4106: # point of view.
4107: # $client - Socket open on the client.
4108: # Returns:
4109: # 1 - Indicating processing should continue.
4110: #
4111: sub validate_course_section_handler {
4112: my ($cmd, $tail, $client) = @_;
4113: my $userinput = "$cmd:$tail";
4114: my ($inst_course_id, $cdom) = split(/:/, $tail);
4115:
4116: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
4117: &Reply($client, "$outcome\n", $userinput);
4118:
4119:
4120: return 1;
4121: }
4122: ®ister_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
4123:
4124: #
4125: # Create a password for a new auto-enrollment user.
4126: # I think/guess, this password allows access to the institutions
4127: # AIS class list server/services. Stuart can correct this comment
4128: # when he finds out how wrong I am.
4129: #
4130: # Formal Parameters:
4131: # $cmd - The command request that got us dispatched.
4132: # $tail - The tail of the command. In this case this is a colon separated
4133: # set of words that will be split into:
4134: # $authparam - An authentication parameter (username??).
4135: # $cdom - The domain of the course from the institution's
4136: # point of view.
4137: # $client - The socket open on the client.
4138: # Returns:
4139: # 1 - continue processing.
4140: #
4141: sub create_auto_enroll_password_handler {
4142: my ($cmd, $tail, $client) = @_;
4143: my $userinput = "$cmd:$tail";
4144:
4145: my ($authparam, $cdom) = split(/:/, $userinput);
4146:
4147: my ($create_passwd,$authchk);
4148: ($authparam,
4149: $create_passwd,
4150: $authchk) = &localenroll::create_password($authparam,$cdom);
4151:
4152: &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
4153: $userinput);
4154:
4155:
4156: return 1;
4157: }
4158: ®ister_handler("autocreatepassword", \&create_auto_enroll_password_handler,
4159: 0, 1, 0);
4160:
4161: # Retrieve and remove temporary files created by/during autoenrollment.
4162: #
4163: # Formal Parameters:
4164: # $cmd - The command that got us dispatched.
4165: # $tail - The tail of the command. In our case this is a colon
4166: # separated list that will be split into:
4167: # $filename - The name of the file to remove.
4168: # The filename is given as a path relative to
4169: # the LonCAPA temp file directory.
4170: # $client - Socket open on the client.
4171: #
4172: # Returns:
4173: # 1 - Continue processing.
4174: sub retrieve_auto_file_handler {
4175: my ($cmd, $tail, $client) = @_;
4176: my $userinput = "cmd:$tail";
4177:
4178: my ($filename) = split(/:/, $tail);
4179:
4180: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
4181: if ( (-e $source) && ($filename ne '') ) {
4182: my $reply = '';
4183: if (open(my $fh,$source)) {
4184: while (<$fh>) {
4185: chomp($_);
4186: $_ =~ s/^\s+//g;
4187: $_ =~ s/\s+$//g;
4188: $reply .= $_;
4189: }
4190: close($fh);
4191: &Reply($client, &escape($reply)."\n", $userinput);
4192:
4193: # Does this have to be uncommented??!? (RF).
4194: #
4195: # unlink($source);
4196: } else {
4197: &Failure($client, "error\n", $userinput);
4198: }
4199: } else {
4200: &Failure($client, "error\n", $userinput);
4201: }
4202:
4203:
4204: return 1;
4205: }
4206: ®ister_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
4207:
4208: #
4209: # Read and retrieve institutional code format (for support form).
4210: # Formal Parameters:
4211: # $cmd - Command that dispatched us.
4212: # $tail - Tail of the command. In this case it conatins
4213: # the course domain and the coursename.
4214: # $client - Socket open on the client.
4215: # Returns:
4216: # 1 - Continue processing.
4217: #
4218: sub get_institutional_code_format_handler {
4219: my ($cmd, $tail, $client) = @_;
4220: my $userinput = "$cmd:$tail";
4221:
4222: my $reply;
4223: my($cdom,$course) = split(/:/,$tail);
4224: my @pairs = split/\&/,$course;
4225: my %instcodes = ();
4226: my %codes = ();
4227: my @codetitles = ();
4228: my %cat_titles = ();
4229: my %cat_order = ();
4230: foreach (@pairs) {
4231: my ($key,$value) = split/=/,$_;
4232: $instcodes{&unescape($key)} = &unescape($value);
4233: }
4234: my $formatreply = &localenroll::instcode_format($cdom,
4235: \%instcodes,
4236: \%codes,
4237: \@codetitles,
4238: \%cat_titles,
4239: \%cat_order);
4240: if ($formatreply eq 'ok') {
4241: my $codes_str = &hash2str(%codes);
4242: my $codetitles_str = &array2str(@codetitles);
4243: my $cat_titles_str = &hash2str(%cat_titles);
4244: my $cat_order_str = &hash2str(%cat_order);
4245: &Reply($client,
4246: $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
4247: .$cat_order_str."\n",
4248: $userinput);
4249: } else {
4250: # this else branch added by RF since if not ok, lonc will
4251: # hang waiting on reply until timeout.
4252: #
4253: &Reply($client, "format_error\n", $userinput);
4254: }
4255:
4256: return 1;
4257: }
4258: ®ister_handler("autoinstcodeformat",
4259: \&get_institutional_code_format_handler,0,1,0);
4260:
4261: #
4262: # Gets a student's photo to exist (in the correct image type) in the user's
4263: # directory.
4264: # Formal Parameters:
4265: # $cmd - The command request that got us dispatched.
4266: # $tail - A colon separated set of words that will be split into:
4267: # $domain - student's domain
4268: # $uname - student username
4269: # $type - image type desired
4270: # $client - The socket open on the client.
4271: # Returns:
4272: # 1 - continue processing.
4273: sub student_photo_handler {
4274: my ($cmd, $tail, $client) = @_;
4275: my ($domain,$uname,$type) = split(/:/, $tail);
4276:
4277: my $path=&propath($domain,$uname).
4278: '/userfiles/internal/studentphoto.'.$type;
4279: if (-e $path) {
4280: &Reply($client,"ok\n","$cmd:$tail");
4281: return 1;
4282: }
4283: &mkpath($path);
4284: my $file=&localstudentphoto::fetch($domain,$uname);
4285: if (!$file) {
4286: &Failure($client,"unavailable\n","$cmd:$tail");
4287: return 1;
4288: }
4289: if (!-e $path) { &convert_photo($file,$path); }
4290: if (-e $path) {
4291: &Reply($client,"ok\n","$cmd:$tail");
4292: return 1;
4293: }
4294: &Failure($client,"unable_to_convert\n","$cmd:$tail");
4295: return 1;
4296: }
4297: ®ister_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
4298:
4299: # mkpath makes all directories for a file, expects an absolute path with a
4300: # file or a trailing / if just a dir is passed
4301: # returns 1 on success 0 on failure
4302: sub mkpath {
4303: my ($file)=@_;
4304: my @parts=split(/\//,$file,-1);
4305: my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
4306: for (my $i=3;$i<= ($#parts-1);$i++) {
4307: $now.='/'.$parts[$i];
4308: if (!-e $now) {
4309: if (!mkdir($now,0770)) { return 0; }
4310: }
4311: }
4312: return 1;
4313: }
4314:
4315: #---------------------------------------------------------------
4316: #
4317: # Getting, decoding and dispatching requests:
4318: #
4319: #
4320: # Get a Request:
4321: # Gets a Request message from the client. The transaction
4322: # is defined as a 'line' of text. We remove the new line
4323: # from the text line.
4324: #
4325: sub get_request {
4326: my $input = <$client>;
4327: chomp($input);
4328:
4329: &Debug("get_request: Request = $input\n");
4330:
4331: &status('Processing '.$clientname.':'.$input);
4332:
4333: return $input;
4334: }
4335: #---------------------------------------------------------------
4336: #
4337: # Process a request. This sub should shrink as each action
4338: # gets farmed out into a separat sub that is registered
4339: # with the dispatch hash.
4340: #
4341: # Parameters:
4342: # user_input - The request received from the client (lonc).
4343: # Returns:
4344: # true to keep processing, false if caller should exit.
4345: #
4346: sub process_request {
4347: my ($userinput) = @_; # Easier for now to break style than to
4348: # fix all the userinput -> user_input.
4349: my $wasenc = 0; # True if request was encrypted.
4350: # ------------------------------------------------------------ See if encrypted
4351: if ($userinput =~ /^enc/) {
4352: $userinput = decipher($userinput);
4353: $wasenc=1;
4354: if(!$userinput) { # Cipher not defined.
4355: &Failure($client, "error: Encrypted data without negotated key\n");
4356: return 0;
4357: }
4358: }
4359: Debug("process_request: $userinput\n");
4360:
4361: #
4362: # The 'correct way' to add a command to lond is now to
4363: # write a sub to execute it and Add it to the command dispatch
4364: # hash via a call to register_handler.. The comments to that
4365: # sub should give you enough to go on to show how to do this
4366: # along with the examples that are building up as this code
4367: # is getting refactored. Until all branches of the
4368: # if/elseif monster below have been factored out into
4369: # separate procesor subs, if the dispatch hash is missing
4370: # the command keyword, we will fall through to the remainder
4371: # of the if/else chain below in order to keep this thing in
4372: # working order throughout the transmogrification.
4373:
4374: my ($command, $tail) = split(/:/, $userinput, 2);
4375: chomp($command);
4376: chomp($tail);
4377: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
4378: $command =~ s/(\r)//; # And this too for parameterless commands.
4379: if(!$tail) {
4380: $tail =""; # defined but blank.
4381: }
4382:
4383: &Debug("Command received: $command, encoded = $wasenc");
4384:
4385: if(defined $Dispatcher{$command}) {
4386:
4387: my $dispatch_info = $Dispatcher{$command};
4388: my $handler = $$dispatch_info[0];
4389: my $need_encode = $$dispatch_info[1];
4390: my $client_types = $$dispatch_info[2];
4391: Debug("Matched dispatch hash: mustencode: $need_encode "
4392: ."ClientType $client_types");
4393:
4394: # Validate the request:
4395:
4396: my $ok = 1;
4397: my $requesterprivs = 0;
4398: if(&isClient()) {
4399: $requesterprivs |= $CLIENT_OK;
4400: }
4401: if(&isManager()) {
4402: $requesterprivs |= $MANAGER_OK;
4403: }
4404: if($need_encode && (!$wasenc)) {
4405: Debug("Must encode but wasn't: $need_encode $wasenc");
4406: $ok = 0;
4407: }
4408: if(($client_types & $requesterprivs) == 0) {
4409: Debug("Client not privileged to do this operation");
4410: $ok = 0;
4411: }
4412:
4413: if($ok) {
4414: Debug("Dispatching to handler $command $tail");
4415: my $keep_going = &$handler($command, $tail, $client);
4416: return $keep_going;
4417: } else {
4418: Debug("Refusing to dispatch because client did not match requirements");
4419: Failure($client, "refused\n", $userinput);
4420: return 1;
4421: }
4422:
4423: }
4424:
4425: print $client "unknown_cmd\n";
4426: # -------------------------------------------------------------------- complete
4427: Debug("process_request - returning 1");
4428: return 1;
4429: }
4430: #
4431: # Decipher encoded traffic
4432: # Parameters:
4433: # input - Encoded data.
4434: # Returns:
4435: # Decoded data or undef if encryption key was not yet negotiated.
4436: # Implicit input:
4437: # cipher - This global holds the negotiated encryption key.
4438: #
4439: sub decipher {
4440: my ($input) = @_;
4441: my $output = '';
4442:
4443:
4444: if($cipher) {
4445: my($enc, $enclength, $encinput) = split(/:/, $input);
4446: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
4447: $output .=
4448: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
4449: }
4450: return substr($output, 0, $enclength);
4451: } else {
4452: return undef;
4453: }
4454: }
4455:
4456: #
4457: # Register a command processor. This function is invoked to register a sub
4458: # to process a request. Once registered, the ProcessRequest sub can automatically
4459: # dispatch requests to an appropriate sub, and do the top level validity checking
4460: # as well:
4461: # - Is the keyword recognized.
4462: # - Is the proper client type attempting the request.
4463: # - Is the request encrypted if it has to be.
4464: # Parameters:
4465: # $request_name - Name of the request being registered.
4466: # This is the command request that will match
4467: # against the hash keywords to lookup the information
4468: # associated with the dispatch information.
4469: # $procedure - Reference to a sub to call to process the request.
4470: # All subs get called as follows:
4471: # Procedure($cmd, $tail, $replyfd, $key)
4472: # $cmd - the actual keyword that invoked us.
4473: # $tail - the tail of the request that invoked us.
4474: # $replyfd- File descriptor connected to the client
4475: # $must_encode - True if the request must be encoded to be good.
4476: # $client_ok - True if it's ok for a client to request this.
4477: # $manager_ok - True if it's ok for a manager to request this.
4478: # Side effects:
4479: # - On success, the Dispatcher hash has an entry added for the key $RequestName
4480: # - On failure, the program will die as it's a bad internal bug to try to
4481: # register a duplicate command handler.
4482: #
4483: sub register_handler {
4484: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
4485:
4486: # Don't allow duplication#
4487:
4488: if (defined $Dispatcher{$request_name}) {
4489: die "Attempting to define a duplicate request handler for $request_name\n";
4490: }
4491: # Build the client type mask:
4492:
4493: my $client_type_mask = 0;
4494: if($client_ok) {
4495: $client_type_mask |= $CLIENT_OK;
4496: }
4497: if($manager_ok) {
4498: $client_type_mask |= $MANAGER_OK;
4499: }
4500:
4501: # Enter the hash:
4502:
4503: my @entry = ($procedure, $must_encode, $client_type_mask);
4504:
4505: $Dispatcher{$request_name} = \@entry;
4506:
4507: }
4508:
4509:
4510: #------------------------------------------------------------------
4511:
4512:
4513:
4514:
4515: #
4516: # Convert an error return code from lcpasswd to a string value.
4517: #
4518: sub lcpasswdstrerror {
4519: my $ErrorCode = shift;
4520: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
4521: return "lcpasswd Unrecognized error return value ".$ErrorCode;
4522: } else {
4523: return $passwderrors[$ErrorCode];
4524: }
4525: }
4526:
4527: #
4528: # Convert an error return code from lcuseradd to a string value:
4529: #
4530: sub lcuseraddstrerror {
4531: my $ErrorCode = shift;
4532: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
4533: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
4534: } else {
4535: return $adderrors[$ErrorCode];
4536: }
4537: }
4538:
4539: # grabs exception and records it to log before exiting
4540: sub catchexception {
4541: my ($error)=@_;
4542: $SIG{'QUIT'}='DEFAULT';
4543: $SIG{__DIE__}='DEFAULT';
4544: &status("Catching exception");
4545: &logthis("<font color='red'>CRITICAL: "
4546: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
4547: ."a crash with this error msg->[$error]</font>");
4548: &logthis('Famous last words: '.$status.' - '.$lastlog);
4549: if ($client) { print $client "error: $error\n"; }
4550: $server->close();
4551: die($error);
4552: }
4553: sub timeout {
4554: &status("Handling Timeout");
4555: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
4556: &catchexception('Timeout');
4557: }
4558: # -------------------------------- Set signal handlers to record abnormal exits
4559:
4560:
4561: $SIG{'QUIT'}=\&catchexception;
4562: $SIG{__DIE__}=\&catchexception;
4563:
4564: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
4565: &status("Read loncapa.conf and loncapa_apache.conf");
4566: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
4567: %perlvar=%{$perlvarref};
4568: undef $perlvarref;
4569:
4570: # ----------------------------- Make sure this process is running from user=www
4571: my $wwwid=getpwnam('www');
4572: if ($wwwid!=$<) {
4573: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
4574: my $subj="LON: $currenthostid User ID mismatch";
4575: system("echo 'User ID mismatch. lond must be run as user www.' |\
4576: mailto $emailto -s '$subj' > /dev/null");
4577: exit 1;
4578: }
4579:
4580: # --------------------------------------------- Check if other instance running
4581:
4582: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
4583:
4584: if (-e $pidfile) {
4585: my $lfh=IO::File->new("$pidfile");
4586: my $pide=<$lfh>;
4587: chomp($pide);
4588: if (kill 0 => $pide) { die "already running"; }
4589: }
4590:
4591: # ------------------------------------------------------------- Read hosts file
4592:
4593:
4594:
4595: # establish SERVER socket, bind and listen.
4596: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
4597: Type => SOCK_STREAM,
4598: Proto => 'tcp',
4599: Reuse => 1,
4600: Listen => 10 )
4601: or die "making socket: $@\n";
4602:
4603: # --------------------------------------------------------- Do global variables
4604:
4605: # global variables
4606:
4607: my %children = (); # keys are current child process IDs
4608:
4609: sub REAPER { # takes care of dead children
4610: $SIG{CHLD} = \&REAPER;
4611: &status("Handling child death");
4612: my $pid;
4613: do {
4614: $pid = waitpid(-1,&WNOHANG());
4615: if (defined($children{$pid})) {
4616: &logthis("Child $pid died");
4617: delete($children{$pid});
4618: } elsif ($pid > 0) {
4619: &logthis("Unknown Child $pid died");
4620: }
4621: } while ( $pid > 0 );
4622: foreach my $child (keys(%children)) {
4623: $pid = waitpid($child,&WNOHANG());
4624: if ($pid > 0) {
4625: &logthis("Child $child - $pid looks like we missed it's death");
4626: delete($children{$pid});
4627: }
4628: }
4629: &status("Finished Handling child death");
4630: }
4631:
4632: sub HUNTSMAN { # signal handler for SIGINT
4633: &status("Killing children (INT)");
4634: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
4635: kill 'INT' => keys %children;
4636: &logthis("Free socket: ".shutdown($server,2)); # free up socket
4637: my $execdir=$perlvar{'lonDaemons'};
4638: unlink("$execdir/logs/lond.pid");
4639: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
4640: &status("Done killing children");
4641: exit; # clean up with dignity
4642: }
4643:
4644: sub HUPSMAN { # signal handler for SIGHUP
4645: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
4646: &status("Killing children for restart (HUP)");
4647: kill 'INT' => keys %children;
4648: &logthis("Free socket: ".shutdown($server,2)); # free up socket
4649: &logthis("<font color='red'>CRITICAL: Restarting</font>");
4650: my $execdir=$perlvar{'lonDaemons'};
4651: unlink("$execdir/logs/lond.pid");
4652: &status("Restarting self (HUP)");
4653: exec("$execdir/lond"); # here we go again
4654: }
4655:
4656: #
4657: # Kill off hashes that describe the host table prior to re-reading it.
4658: # Hashes affected are:
4659: # %hostid, %hostdom %hostip %hostdns.
4660: #
4661: sub KillHostHashes {
4662: foreach my $key (keys %hostid) {
4663: delete $hostid{$key};
4664: }
4665: foreach my $key (keys %hostdom) {
4666: delete $hostdom{$key};
4667: }
4668: foreach my $key (keys %hostip) {
4669: delete $hostip{$key};
4670: }
4671: foreach my $key (keys %hostdns) {
4672: delete $hostdns{$key};
4673: }
4674: }
4675: #
4676: # Read in the host table from file and distribute it into the various hashes:
4677: #
4678: # - %hostid - Indexed by IP, the loncapa hostname.
4679: # - %hostdom - Indexed by loncapa hostname, the domain.
4680: # - %hostip - Indexed by hostid, the Ip address of the host.
4681: sub ReadHostTable {
4682:
4683: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
4684: my $myloncapaname = $perlvar{'lonHostID'};
4685: Debug("My loncapa name is : $myloncapaname");
4686: my %name_to_ip;
4687: while (my $configline=<CONFIG>) {
4688: if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
4689: my ($id,$domain,$role,$name)=split(/:/,$configline);
4690: $name=~s/\s//g;
4691: my $ip;
4692: if (!exists($name_to_ip{$name})) {
4693: $ip = gethostbyname($name);
4694: if (!$ip || length($ip) ne 4) {
4695: &logthis("Skipping host $id name $name no IP found\n");
4696: next;
4697: }
4698: $ip=inet_ntoa($ip);
4699: $name_to_ip{$name} = $ip;
4700: } else {
4701: $ip = $name_to_ip{$name};
4702: }
4703: $hostid{$ip}=$id; # LonCAPA name of host by IP.
4704: $hostdom{$id}=$domain; # LonCAPA domain name of host.
4705: $hostname{$id}=$name; # LonCAPA name -> DNS name
4706: $hostip{$id}=$ip; # IP address of host.
4707: $hostdns{$name} = $id; # LonCAPA name of host by DNS.
4708:
4709: if ($id eq $perlvar{'lonHostID'}) {
4710: Debug("Found me in the host table: $name");
4711: $thisserver=$name;
4712: }
4713: }
4714: }
4715: close(CONFIG);
4716: }
4717: #
4718: # Reload the Apache daemon's state.
4719: # This is done by invoking /home/httpd/perl/apachereload
4720: # a setuid perl script that can be root for us to do this job.
4721: #
4722: sub ReloadApache {
4723: my $execdir = $perlvar{'lonDaemons'};
4724: my $script = $execdir."/apachereload";
4725: system($script);
4726: }
4727:
4728: #
4729: # Called in response to a USR2 signal.
4730: # - Reread hosts.tab
4731: # - All children connected to hosts that were removed from hosts.tab
4732: # are killed via SIGINT
4733: # - All children connected to previously existing hosts are sent SIGUSR1
4734: # - Our internal hosts hash is updated to reflect the new contents of
4735: # hosts.tab causing connections from hosts added to hosts.tab to
4736: # now be honored.
4737: #
4738: sub UpdateHosts {
4739: &status("Reload hosts.tab");
4740: logthis('<font color="blue"> Updating connections </font>');
4741: #
4742: # The %children hash has the set of IP's we currently have children
4743: # on. These need to be matched against records in the hosts.tab
4744: # Any ip's no longer in the table get killed off they correspond to
4745: # either dropped or changed hosts. Note that the re-read of the table
4746: # will take care of new and changed hosts as connections come into being.
4747:
4748:
4749: KillHostHashes;
4750: ReadHostTable;
4751:
4752: foreach my $child (keys %children) {
4753: my $childip = $children{$child};
4754: if(!$hostid{$childip}) {
4755: logthis('<font color="blue"> UpdateHosts killing child '
4756: ." $child for ip $childip </font>");
4757: kill('INT', $child);
4758: } else {
4759: logthis('<font color="green"> keeping child for ip '
4760: ." $childip (pid=$child) </font>");
4761: }
4762: }
4763: ReloadApache;
4764: &status("Finished reloading hosts.tab");
4765: }
4766:
4767:
4768: sub checkchildren {
4769: &status("Checking on the children (sending signals)");
4770: &initnewstatus();
4771: &logstatus();
4772: &logthis('Going to check on the children');
4773: my $docdir=$perlvar{'lonDocRoot'};
4774: foreach (sort keys %children) {
4775: #sleep 1;
4776: unless (kill 'USR1' => $_) {
4777: &logthis ('Child '.$_.' is dead');
4778: &logstatus($$.' is dead');
4779: delete($children{$_});
4780: }
4781: }
4782: sleep 5;
4783: $SIG{ALRM} = sub { Debug("timeout");
4784: die "timeout"; };
4785: $SIG{__DIE__} = 'DEFAULT';
4786: &status("Checking on the children (waiting for reports)");
4787: foreach (sort keys %children) {
4788: unless (-e "$docdir/lon-status/londchld/$_.txt") {
4789: eval {
4790: alarm(300);
4791: &logthis('Child '.$_.' did not respond');
4792: kill 9 => $_;
4793: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
4794: #$subj="LON: $currenthostid killed lond process $_";
4795: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
4796: #$execdir=$perlvar{'lonDaemons'};
4797: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
4798: delete($children{$_});
4799: alarm(0);
4800: }
4801: }
4802: }
4803: $SIG{ALRM} = 'DEFAULT';
4804: $SIG{__DIE__} = \&catchexception;
4805: &status("Finished checking children");
4806: &logthis('Finished Checking children');
4807: }
4808:
4809: # --------------------------------------------------------------------- Logging
4810:
4811: sub logthis {
4812: my $message=shift;
4813: my $execdir=$perlvar{'lonDaemons'};
4814: my $fh=IO::File->new(">>$execdir/logs/lond.log");
4815: my $now=time;
4816: my $local=localtime($now);
4817: $lastlog=$local.': '.$message;
4818: print $fh "$local ($$): $message\n";
4819: }
4820:
4821: # ------------------------- Conditional log if $DEBUG true.
4822: sub Debug {
4823: my $message = shift;
4824: if($DEBUG) {
4825: &logthis($message);
4826: }
4827: }
4828:
4829: #
4830: # Sub to do replies to client.. this gives a hook for some
4831: # debug tracing too:
4832: # Parameters:
4833: # fd - File open on client.
4834: # reply - Text to send to client.
4835: # request - Original request from client.
4836: #
4837: sub Reply {
4838: my ($fd, $reply, $request) = @_;
4839: print $fd $reply;
4840: Debug("Request was $request Reply was $reply");
4841:
4842: $Transactions++;
4843: }
4844:
4845:
4846: #
4847: # Sub to report a failure.
4848: # This function:
4849: # - Increments the failure statistic counters.
4850: # - Invokes Reply to send the error message to the client.
4851: # Parameters:
4852: # fd - File descriptor open on the client
4853: # reply - Reply text to emit.
4854: # request - The original request message (used by Reply
4855: # to debug if that's enabled.
4856: # Implicit outputs:
4857: # $Failures- The number of failures is incremented.
4858: # Reply (invoked here) sends a message to the
4859: # client:
4860: #
4861: sub Failure {
4862: my $fd = shift;
4863: my $reply = shift;
4864: my $request = shift;
4865:
4866: $Failures++;
4867: Reply($fd, $reply, $request); # That's simple eh?
4868: }
4869: # ------------------------------------------------------------------ Log status
4870:
4871: sub logstatus {
4872: &status("Doing logging");
4873: my $docdir=$perlvar{'lonDocRoot'};
4874: {
4875: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
4876: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
4877: $fh->close();
4878: }
4879: &status("Finished $$.txt");
4880: {
4881: open(LOG,">>$docdir/lon-status/londstatus.txt");
4882: flock(LOG,LOCK_EX);
4883: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
4884: .$status."\t".$lastlog."\t $keymode\n";
4885: flock(LOG,LOCK_UN);
4886: close(LOG);
4887: }
4888: &status("Finished logging");
4889: }
4890:
4891: sub initnewstatus {
4892: my $docdir=$perlvar{'lonDocRoot'};
4893: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
4894: my $now=time;
4895: my $local=localtime($now);
4896: print $fh "LOND status $local - parent $$\n\n";
4897: opendir(DIR,"$docdir/lon-status/londchld");
4898: while (my $filename=readdir(DIR)) {
4899: unlink("$docdir/lon-status/londchld/$filename");
4900: }
4901: closedir(DIR);
4902: }
4903:
4904: # -------------------------------------------------------------- Status setting
4905:
4906: sub status {
4907: my $what=shift;
4908: my $now=time;
4909: my $local=localtime($now);
4910: $status=$local.': '.$what;
4911: $0='lond: '.$what.' '.$local;
4912: }
4913:
4914: # -------------------------------------------------------- Escape Special Chars
4915:
4916: sub escape {
4917: my $str=shift;
4918: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
4919: return $str;
4920: }
4921:
4922: # ----------------------------------------------------- Un-Escape Special Chars
4923:
4924: sub unescape {
4925: my $str=shift;
4926: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
4927: return $str;
4928: }
4929:
4930: # ----------------------------------------------------------- Send USR1 to lonc
4931:
4932: sub reconlonc {
4933: my $peerfile=shift;
4934: &logthis("Trying to reconnect for $peerfile");
4935: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
4936: if (my $fh=IO::File->new("$loncfile")) {
4937: my $loncpid=<$fh>;
4938: chomp($loncpid);
4939: if (kill 0 => $loncpid) {
4940: &logthis("lonc at pid $loncpid responding, sending USR1");
4941: kill USR1 => $loncpid;
4942: } else {
4943: &logthis(
4944: "<font color='red'>CRITICAL: "
4945: ."lonc at pid $loncpid not responding, giving up</font>");
4946: }
4947: } else {
4948: &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
4949: }
4950: }
4951:
4952: # -------------------------------------------------- Non-critical communication
4953:
4954: sub subreply {
4955: my ($cmd,$server)=@_;
4956: my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
4957: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
4958: Type => SOCK_STREAM,
4959: Timeout => 10)
4960: or return "con_lost";
4961: print $sclient "sethost:$server:$cmd\n";
4962: my $answer=<$sclient>;
4963: chomp($answer);
4964: if (!$answer) { $answer="con_lost"; }
4965: return $answer;
4966: }
4967:
4968: sub reply {
4969: my ($cmd,$server)=@_;
4970: my $answer;
4971: if ($server ne $currenthostid) {
4972: $answer=subreply($cmd,$server);
4973: if ($answer eq 'con_lost') {
4974: $answer=subreply("ping",$server);
4975: if ($answer ne $server) {
4976: &logthis("sub reply: answer != server answer is $answer, server is $server");
4977: &reconlonc("$perlvar{'lonSockDir'}/".$hostname{$server});
4978: }
4979: $answer=subreply($cmd,$server);
4980: }
4981: } else {
4982: $answer='self_reply';
4983: }
4984: return $answer;
4985: }
4986:
4987: # -------------------------------------------------------------- Talk to lonsql
4988:
4989: sub sql_reply {
4990: my ($cmd)=@_;
4991: my $answer=&sub_sql_reply($cmd);
4992: if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
4993: return $answer;
4994: }
4995:
4996: sub sub_sql_reply {
4997: my ($cmd)=@_;
4998: my $unixsock="mysqlsock";
4999: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
5000: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
5001: Type => SOCK_STREAM,
5002: Timeout => 10)
5003: or return "con_lost";
5004: print $sclient "$cmd\n";
5005: my $answer=<$sclient>;
5006: chomp($answer);
5007: if (!$answer) { $answer="con_lost"; }
5008: return $answer;
5009: }
5010:
5011: # -------------------------------------------- Return path to profile directory
5012:
5013: sub propath {
5014: my ($udom,$uname)=@_;
5015: $udom=~s/\W//g;
5016: $uname=~s/\W//g;
5017: my $subdir=$uname.'__';
5018: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5019: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
5020: return $proname;
5021: }
5022:
5023: # --------------------------------------- Is this the home server of an author?
5024:
5025: sub ishome {
5026: my $author=shift;
5027: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
5028: my ($udom,$uname)=split(/\//,$author);
5029: my $proname=propath($udom,$uname);
5030: if (-e $proname) {
5031: return 'owner';
5032: } else {
5033: return 'not_owner';
5034: }
5035: }
5036:
5037: # ======================================================= Continue main program
5038: # ---------------------------------------------------- Fork once and dissociate
5039:
5040: my $fpid=fork;
5041: exit if $fpid;
5042: die "Couldn't fork: $!" unless defined ($fpid);
5043:
5044: POSIX::setsid() or die "Can't start new session: $!";
5045:
5046: # ------------------------------------------------------- Write our PID on disk
5047:
5048: my $execdir=$perlvar{'lonDaemons'};
5049: open (PIDSAVE,">$execdir/logs/lond.pid");
5050: print PIDSAVE "$$\n";
5051: close(PIDSAVE);
5052: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
5053: &status('Starting');
5054:
5055:
5056:
5057: # ----------------------------------------------------- Install signal handlers
5058:
5059:
5060: $SIG{CHLD} = \&REAPER;
5061: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
5062: $SIG{HUP} = \&HUPSMAN;
5063: $SIG{USR1} = \&checkchildren;
5064: $SIG{USR2} = \&UpdateHosts;
5065:
5066: # Read the host hashes:
5067:
5068: ReadHostTable;
5069:
5070: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
5071:
5072: # --------------------------------------------------------------
5073: # Accept connections. When a connection comes in, it is validated
5074: # and if good, a child process is created to process transactions
5075: # along the connection.
5076:
5077: while (1) {
5078: &status('Starting accept');
5079: $client = $server->accept() or next;
5080: &status('Accepted '.$client.' off to spawn');
5081: make_new_child($client);
5082: &status('Finished spawning');
5083: }
5084:
5085: sub make_new_child {
5086: my $pid;
5087: # my $cipher; # Now global
5088: my $sigset;
5089:
5090: $client = shift;
5091: &status('Starting new child '.$client);
5092: &logthis('<font color="green"> Attempting to start child ('.$client.
5093: ")</font>");
5094: # block signal for fork
5095: $sigset = POSIX::SigSet->new(SIGINT);
5096: sigprocmask(SIG_BLOCK, $sigset)
5097: or die "Can't block SIGINT for fork: $!\n";
5098:
5099: die "fork: $!" unless defined ($pid = fork);
5100:
5101: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
5102: # connection liveness.
5103:
5104: #
5105: # Figure out who we're talking to so we can record the peer in
5106: # the pid hash.
5107: #
5108: my $caller = getpeername($client);
5109: my ($port,$iaddr);
5110: if (defined($caller) && length($caller) > 0) {
5111: ($port,$iaddr)=unpack_sockaddr_in($caller);
5112: } else {
5113: &logthis("Unable to determine who caller was, getpeername returned nothing");
5114: }
5115: if (defined($iaddr)) {
5116: $clientip = inet_ntoa($iaddr);
5117: Debug("Connected with $clientip");
5118: } else {
5119: &logthis("Unable to determine clientip");
5120: $clientip='Unavailable';
5121: }
5122:
5123: if ($pid) {
5124: # Parent records the child's birth and returns.
5125: sigprocmask(SIG_UNBLOCK, $sigset)
5126: or die "Can't unblock SIGINT for fork: $!\n";
5127: $children{$pid} = $clientip;
5128: &status('Started child '.$pid);
5129: return;
5130: } else {
5131: # Child can *not* return from this subroutine.
5132: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
5133: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
5134: #don't get intercepted
5135: $SIG{USR1}= \&logstatus;
5136: $SIG{ALRM}= \&timeout;
5137: $lastlog='Forked ';
5138: $status='Forked';
5139:
5140: # unblock signals
5141: sigprocmask(SIG_UNBLOCK, $sigset)
5142: or die "Can't unblock SIGINT for fork: $!\n";
5143:
5144: # my $tmpsnum=0; # Now global
5145: #---------------------------------------------------- kerberos 5 initialization
5146: &Authen::Krb5::init_context();
5147: unless (($dist eq 'fedora4') || ($dist eq 'suse9.3')) {
5148: &Authen::Krb5::init_ets();
5149: }
5150:
5151: &status('Accepted connection');
5152: # =============================================================================
5153: # do something with the connection
5154: # -----------------------------------------------------------------------------
5155: # see if we know client and 'check' for spoof IP by ineffective challenge
5156:
5157: ReadManagerTable; # May also be a manager!!
5158:
5159: my $outsideip=$clientip;
5160: if ($clientip eq '127.0.0.1') {
5161: $outsideip=$hostip{$perlvar{'lonHostID'}};
5162: }
5163:
5164: my $clientrec=($hostid{$outsideip} ne undef);
5165: my $ismanager=($managers{$outsideip} ne undef);
5166: $clientname = "[unknonwn]";
5167: if($clientrec) { # Establish client type.
5168: $ConnectionType = "client";
5169: $clientname = $hostid{$outsideip};
5170: if($ismanager) {
5171: $ConnectionType = "both";
5172: }
5173: } else {
5174: $ConnectionType = "manager";
5175: $clientname = $managers{$outsideip};
5176: }
5177: my $clientok;
5178:
5179: if ($clientrec || $ismanager) {
5180: &status("Waiting for init from $clientip $clientname");
5181: &logthis('<font color="yellow">INFO: Connection, '.
5182: $clientip.
5183: " ($clientname) connection type = $ConnectionType </font>" );
5184: &status("Connecting $clientip ($clientname))");
5185: my $remotereq=<$client>;
5186: chomp($remotereq);
5187: Debug("Got init: $remotereq");
5188: my $inikeyword = split(/:/, $remotereq);
5189: if ($remotereq =~ /^init/) {
5190: &sethost("sethost:$perlvar{'lonHostID'}");
5191: #
5192: # If the remote is attempting a local init... give that a try:
5193: #
5194: my ($i, $inittype) = split(/:/, $remotereq);
5195:
5196: # If the connection type is ssl, but I didn't get my
5197: # certificate files yet, then I'll drop back to
5198: # insecure (if allowed).
5199:
5200: if($inittype eq "ssl") {
5201: my ($ca, $cert) = lonssl::CertificateFile;
5202: my $kfile = lonssl::KeyFile;
5203: if((!$ca) ||
5204: (!$cert) ||
5205: (!$kfile)) {
5206: $inittype = ""; # This forces insecure attempt.
5207: &logthis("<font color=\"blue\"> Certificates not "
5208: ."installed -- trying insecure auth</font>");
5209: } else { # SSL certificates are in place so
5210: } # Leave the inittype alone.
5211: }
5212:
5213: if($inittype eq "local") {
5214: my $key = LocalConnection($client, $remotereq);
5215: if($key) {
5216: Debug("Got local key $key");
5217: $clientok = 1;
5218: my $cipherkey = pack("H32", $key);
5219: $cipher = new IDEA($cipherkey);
5220: print $client "ok:local\n";
5221: &logthis('<font color="green"'
5222: . "Successful local authentication </font>");
5223: $keymode = "local"
5224: } else {
5225: Debug("Failed to get local key");
5226: $clientok = 0;
5227: shutdown($client, 3);
5228: close $client;
5229: }
5230: } elsif ($inittype eq "ssl") {
5231: my $key = SSLConnection($client);
5232: if ($key) {
5233: $clientok = 1;
5234: my $cipherkey = pack("H32", $key);
5235: $cipher = new IDEA($cipherkey);
5236: &logthis('<font color="green">'
5237: ."Successfull ssl authentication with $clientname </font>");
5238: $keymode = "ssl";
5239:
5240: } else {
5241: $clientok = 0;
5242: close $client;
5243: }
5244:
5245: } else {
5246: my $ok = InsecureConnection($client);
5247: if($ok) {
5248: $clientok = 1;
5249: &logthis('<font color="green">'
5250: ."Successful insecure authentication with $clientname </font>");
5251: print $client "ok\n";
5252: $keymode = "insecure";
5253: } else {
5254: &logthis('<font color="yellow">'
5255: ."Attempted insecure connection disallowed </font>");
5256: close $client;
5257: $clientok = 0;
5258:
5259: }
5260: }
5261: } else {
5262: &logthis(
5263: "<font color='blue'>WARNING: "
5264: ."$clientip failed to initialize: >$remotereq< </font>");
5265: &status('No init '.$clientip);
5266: }
5267:
5268: } else {
5269: &logthis(
5270: "<font color='blue'>WARNING: Unknown client $clientip</font>");
5271: &status('Hung up on '.$clientip);
5272: }
5273:
5274: if ($clientok) {
5275: # ---------------- New known client connecting, could mean machine online again
5276:
5277: foreach my $id (keys(%hostip)) {
5278: if ($hostip{$id} ne $clientip ||
5279: $hostip{$currenthostid} eq $clientip) {
5280: # no need to try to do recon's to myself
5281: next;
5282: }
5283: &reconlonc("$perlvar{'lonSockDir'}/".$hostname{$id});
5284: }
5285: &logthis("<font color='green'>Established connection: $clientname</font>");
5286: &status('Will listen to '.$clientname);
5287: # ------------------------------------------------------------ Process requests
5288: my $keep_going = 1;
5289: my $user_input;
5290: while(($user_input = get_request) && $keep_going) {
5291: alarm(120);
5292: Debug("Main: Got $user_input\n");
5293: $keep_going = &process_request($user_input);
5294: alarm(0);
5295: &status('Listening to '.$clientname." ($keymode)");
5296: }
5297:
5298: # --------------------------------------------- client unknown or fishy, refuse
5299: } else {
5300: print $client "refused\n";
5301: $client->close();
5302: &logthis("<font color='blue'>WARNING: "
5303: ."Rejected client $clientip, closing connection</font>");
5304: }
5305: }
5306:
5307: # =============================================================================
5308:
5309: &logthis("<font color='red'>CRITICAL: "
5310: ."Disconnect from $clientip ($clientname)</font>");
5311:
5312:
5313: # this exit is VERY important, otherwise the child will become
5314: # a producer of more and more children, forking yourself into
5315: # process death.
5316: exit;
5317:
5318: }
5319: #
5320: # Determine if a user is an author for the indicated domain.
5321: #
5322: # Parameters:
5323: # domain - domain to check in .
5324: # user - Name of user to check.
5325: #
5326: # Return:
5327: # 1 - User is an author for domain.
5328: # 0 - User is not an author for domain.
5329: sub is_author {
5330: my ($domain, $user) = @_;
5331:
5332: &Debug("is_author: $user @ $domain");
5333:
5334: my $hashref = &tie_user_hash($domain, $user, "roles",
5335: &GDBM_READER());
5336:
5337: # Author role should show up as a key /domain/_au
5338:
5339: my $key = "/$domain/_au";
5340: my $value = $hashref->{$key};
5341:
5342: if(defined($value)) {
5343: &Debug("$user @ $domain is an author");
5344: }
5345:
5346: return defined($value);
5347: }
5348: #
5349: # Checks to see if the input roleput request was to set
5350: # an author role. If so, invokes the lchtmldir script to set
5351: # up a correct public_html
5352: # Parameters:
5353: # request - The request sent to the rolesput subchunk.
5354: # We're looking for /domain/_au
5355: # domain - The domain in which the user is having roles doctored.
5356: # user - Name of the user for which the role is being put.
5357: # authtype - The authentication type associated with the user.
5358: #
5359: sub manage_permissions {
5360: my ($request, $domain, $user, $authtype) = @_;
5361:
5362: &Debug("manage_permissions: $request $domain $user $authtype");
5363:
5364: # See if the request is of the form /$domain/_au
5365: if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
5366: my $execdir = $perlvar{'lonDaemons'};
5367: my $userhome= "/home/$user" ;
5368: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
5369: &Debug("Setting homedir permissions for $userhome");
5370: system("$execdir/lchtmldir $userhome $user $authtype");
5371: }
5372: }
5373:
5374:
5375: #
5376: # Return the full path of a user password file, whether it exists or not.
5377: # Parameters:
5378: # domain - Domain in which the password file lives.
5379: # user - name of the user.
5380: # Returns:
5381: # Full passwd path:
5382: #
5383: sub password_path {
5384: my ($domain, $user) = @_;
5385: return &propath($domain, $user).'/passwd';
5386: }
5387:
5388: # Password Filename
5389: # Returns the path to a passwd file given domain and user... only if
5390: # it exists.
5391: # Parameters:
5392: # domain - Domain in which to search.
5393: # user - username.
5394: # Returns:
5395: # - If the password file exists returns its path.
5396: # - If the password file does not exist, returns undefined.
5397: #
5398: sub password_filename {
5399: my ($domain, $user) = @_;
5400:
5401: Debug ("PasswordFilename called: dom = $domain user = $user");
5402:
5403: my $path = &password_path($domain, $user);
5404: Debug("PasswordFilename got path: $path");
5405: if(-e $path) {
5406: return $path;
5407: } else {
5408: return undef;
5409: }
5410: }
5411:
5412: #
5413: # Rewrite the contents of the user's passwd file.
5414: # Parameters:
5415: # domain - domain of the user.
5416: # name - User's name.
5417: # contents - New contents of the file.
5418: # Returns:
5419: # 0 - Failed.
5420: # 1 - Success.
5421: #
5422: sub rewrite_password_file {
5423: my ($domain, $user, $contents) = @_;
5424:
5425: my $file = &password_filename($domain, $user);
5426: if (defined $file) {
5427: my $pf = IO::File->new(">$file");
5428: if($pf) {
5429: print $pf "$contents\n";
5430: return 1;
5431: } else {
5432: return 0;
5433: }
5434: } else {
5435: return 0;
5436: }
5437:
5438: }
5439:
5440: #
5441: # get_auth_type - Determines the authorization type of a user in a domain.
5442:
5443: # Returns the authorization type or nouser if there is no such user.
5444: #
5445: sub get_auth_type
5446: {
5447:
5448: my ($domain, $user) = @_;
5449:
5450: Debug("get_auth_type( $domain, $user ) \n");
5451: my $proname = &propath($domain, $user);
5452: my $passwdfile = "$proname/passwd";
5453: if( -e $passwdfile ) {
5454: my $pf = IO::File->new($passwdfile);
5455: my $realpassword = <$pf>;
5456: chomp($realpassword);
5457: Debug("Password info = $realpassword\n");
5458: my ($authtype, $contentpwd) = split(/:/, $realpassword);
5459: Debug("Authtype = $authtype, content = $contentpwd\n");
5460: return "$authtype:$contentpwd";
5461: } else {
5462: Debug("Returning nouser");
5463: return "nouser";
5464: }
5465: }
5466:
5467: #
5468: # Validate a user given their domain, name and password. This utility
5469: # function is used by both AuthenticateHandler and ChangePasswordHandler
5470: # to validate the login credentials of a user.
5471: # Parameters:
5472: # $domain - The domain being logged into (this is required due to
5473: # the capability for multihomed systems.
5474: # $user - The name of the user being validated.
5475: # $password - The user's propoposed password.
5476: #
5477: # Returns:
5478: # 1 - The domain,user,pasword triplet corresponds to a valid
5479: # user.
5480: # 0 - The domain,user,password triplet is not a valid user.
5481: #
5482: sub validate_user {
5483: my ($domain, $user, $password) = @_;
5484:
5485:
5486: # Why negative ~pi you may well ask? Well this function is about
5487: # authentication, and therefore very important to get right.
5488: # I've initialized the flag that determines whether or not I've
5489: # validated correctly to a value it's not supposed to get.
5490: # At the end of this function. I'll ensure that it's not still that
5491: # value so we don't just wind up returning some accidental value
5492: # as a result of executing an unforseen code path that
5493: # did not set $validated. At the end of valid execution paths,
5494: # validated shoule be 1 for success or 0 for failuer.
5495:
5496: my $validated = -3.14159;
5497:
5498: # How we authenticate is determined by the type of authentication
5499: # the user has been assigned. If the authentication type is
5500: # "nouser", the user does not exist so we will return 0.
5501:
5502: my $contents = &get_auth_type($domain, $user);
5503: my ($howpwd, $contentpwd) = split(/:/, $contents);
5504:
5505: my $null = pack("C",0); # Used by kerberos auth types.
5506:
5507: if ($howpwd ne 'nouser') {
5508:
5509: if($howpwd eq "internal") { # Encrypted is in local password file.
5510: $validated = (crypt($password, $contentpwd) eq $contentpwd);
5511: }
5512: elsif ($howpwd eq "unix") { # User is a normal unix user.
5513: $contentpwd = (getpwnam($user))[1];
5514: if($contentpwd) {
5515: if($contentpwd eq 'x') { # Shadow password file...
5516: my $pwauth_path = "/usr/local/sbin/pwauth";
5517: open PWAUTH, "|$pwauth_path" or
5518: die "Cannot invoke authentication";
5519: print PWAUTH "$user\n$password\n";
5520: close PWAUTH;
5521: $validated = ! $?;
5522:
5523: } else { # Passwords in /etc/passwd.
5524: $validated = (crypt($password,
5525: $contentpwd) eq $contentpwd);
5526: }
5527: } else {
5528: $validated = 0;
5529: }
5530: }
5531: elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
5532: if(! ($password =~ /$null/) ) {
5533: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
5534: "",
5535: $contentpwd,,
5536: 'krbtgt',
5537: $contentpwd,
5538: 1,
5539: $password);
5540: if(!$k4error) {
5541: $validated = 1;
5542: } else {
5543: $validated = 0;
5544: &logthis('krb4: '.$user.', '.$contentpwd.', '.
5545: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
5546: }
5547: } else {
5548: $validated = 0; # Password has a match with null.
5549: }
5550: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
5551: if(!($password =~ /$null/)) { # Null password not allowed.
5552: my $krbclient = &Authen::Krb5::parse_name($user.'@'
5553: .$contentpwd);
5554: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
5555: my $krbserver = &Authen::Krb5::parse_name($krbservice);
5556: my $credentials= &Authen::Krb5::cc_default();
5557: $credentials->initialize($krbclient);
5558: my $krbreturn = &Authen::Krb5::get_in_tkt_with_password($krbclient,
5559: $krbserver,
5560: $password,
5561: $credentials);
5562: $validated = ($krbreturn == 1);
5563: } else {
5564: $validated = 0;
5565: }
5566: } elsif ($howpwd eq "localauth") {
5567: # Authenticate via installation specific authentcation method:
5568: $validated = &localauth::localauth($user,
5569: $password,
5570: $contentpwd);
5571: } else { # Unrecognized auth is also bad.
5572: $validated = 0;
5573: }
5574: } else {
5575: $validated = 0;
5576: }
5577: #
5578: # $validated has the correct stat of the authentication:
5579: #
5580:
5581: unless ($validated != -3.14159) {
5582: # I >really really< want to know if this happens.
5583: # since it indicates that user authentication is badly
5584: # broken in some code path.
5585: #
5586: die "ValidateUser - failed to set the value of validated $domain, $user $password";
5587: }
5588: return $validated;
5589: }
5590:
5591:
5592: sub addline {
5593: my ($fname,$hostid,$ip,$newline)=@_;
5594: my $contents;
5595: my $found=0;
5596: my $expr='^'.$hostid.':'.$ip.':';
5597: $expr =~ s/\./\\\./g;
5598: my $sh;
5599: if ($sh=IO::File->new("$fname.subscription")) {
5600: while (my $subline=<$sh>) {
5601: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
5602: }
5603: $sh->close();
5604: }
5605: $sh=IO::File->new(">$fname.subscription");
5606: if ($contents) { print $sh $contents; }
5607: if ($newline) { print $sh $newline; }
5608: $sh->close();
5609: return $found;
5610: }
5611:
5612: sub get_chat {
5613: my ($cdom,$cname,$udom,$uname)=@_;
5614: my %hash;
5615: my $proname=&propath($cdom,$cname);
5616: my @entries=();
5617: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
5618: &GDBM_READER(),0640)) {
5619: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
5620: untie %hash;
5621: }
5622: my @participants=();
5623: my $cutoff=time-60;
5624: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
5625: &GDBM_WRCREAT(),0640)) {
5626: $hash{$uname.':'.$udom}=time;
5627: foreach (sort keys %hash) {
5628: if ($hash{$_}>$cutoff) {
5629: $participants[$#participants+1]='active_participant:'.$_;
5630: }
5631: }
5632: untie %hash;
5633: }
5634: return (@participants,@entries);
5635: }
5636:
5637: sub chat_add {
5638: my ($cdom,$cname,$newchat)=@_;
5639: my %hash;
5640: my $proname=&propath($cdom,$cname);
5641: my @entries=();
5642: my $time=time;
5643: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
5644: &GDBM_WRCREAT(),0640)) {
5645: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
5646: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
5647: my ($thentime,$idnum)=split(/\_/,$lastid);
5648: my $newid=$time.'_000000';
5649: if ($thentime==$time) {
5650: $idnum=~s/^0+//;
5651: $idnum++;
5652: $idnum=substr('000000'.$idnum,-6,6);
5653: $newid=$time.'_'.$idnum;
5654: }
5655: $hash{$newid}=$newchat;
5656: my $expired=$time-3600;
5657: foreach (keys %hash) {
5658: my ($thistime)=($_=~/(\d+)\_/);
5659: if ($thistime<$expired) {
5660: delete $hash{$_};
5661: }
5662: }
5663: untie %hash;
5664: }
5665: {
5666: my $hfh;
5667: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
5668: print $hfh "$time:".&unescape($newchat)."\n";
5669: }
5670: }
5671: }
5672:
5673: sub unsub {
5674: my ($fname,$clientip)=@_;
5675: my $result;
5676: my $unsubs = 0; # Number of successful unsubscribes:
5677:
5678:
5679: # An old way subscriptions were handled was to have a
5680: # subscription marker file:
5681:
5682: Debug("Attempting unlink of $fname.$clientname");
5683: if (unlink("$fname.$clientname")) {
5684: $unsubs++; # Successful unsub via marker file.
5685: }
5686:
5687: # The more modern way to do it is to have a subscription list
5688: # file:
5689:
5690: if (-e "$fname.subscription") {
5691: my $found=&addline($fname,$clientname,$clientip,'');
5692: if ($found) {
5693: $unsubs++;
5694: }
5695: }
5696:
5697: # If either or both of these mechanisms succeeded in unsubscribing a
5698: # resource we can return ok:
5699:
5700: if($unsubs) {
5701: $result = "ok\n";
5702: } else {
5703: $result = "not_subscribed\n";
5704: }
5705:
5706: return $result;
5707: }
5708:
5709: sub currentversion {
5710: my $fname=shift;
5711: my $version=-1;
5712: my $ulsdir='';
5713: if ($fname=~/^(.+)\/[^\/]+$/) {
5714: $ulsdir=$1;
5715: }
5716: my ($fnamere1,$fnamere2);
5717: # remove version if already specified
5718: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
5719: # get the bits that go before and after the version number
5720: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
5721: $fnamere1=$1;
5722: $fnamere2='.'.$2;
5723: }
5724: if (-e $fname) { $version=1; }
5725: if (-e $ulsdir) {
5726: if(-d $ulsdir) {
5727: if (opendir(LSDIR,$ulsdir)) {
5728: my $ulsfn;
5729: while ($ulsfn=readdir(LSDIR)) {
5730: # see if this is a regular file (ignore links produced earlier)
5731: my $thisfile=$ulsdir.'/'.$ulsfn;
5732: unless (-l $thisfile) {
5733: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
5734: if ($1>$version) { $version=$1; }
5735: }
5736: }
5737: }
5738: closedir(LSDIR);
5739: $version++;
5740: }
5741: }
5742: }
5743: return $version;
5744: }
5745:
5746: sub thisversion {
5747: my $fname=shift;
5748: my $version=-1;
5749: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
5750: $version=$1;
5751: }
5752: return $version;
5753: }
5754:
5755: sub subscribe {
5756: my ($userinput,$clientip)=@_;
5757: my $result;
5758: my ($cmd,$fname)=split(/:/,$userinput,2);
5759: my $ownership=&ishome($fname);
5760: if ($ownership eq 'owner') {
5761: # explitly asking for the current version?
5762: unless (-e $fname) {
5763: my $currentversion=¤tversion($fname);
5764: if (&thisversion($fname)==$currentversion) {
5765: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
5766: my $root=$1;
5767: my $extension=$2;
5768: symlink($root.'.'.$extension,
5769: $root.'.'.$currentversion.'.'.$extension);
5770: unless ($extension=~/\.meta$/) {
5771: symlink($root.'.'.$extension.'.meta',
5772: $root.'.'.$currentversion.'.'.$extension.'.meta');
5773: }
5774: }
5775: }
5776: }
5777: if (-e $fname) {
5778: if (-d $fname) {
5779: $result="directory\n";
5780: } else {
5781: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
5782: my $now=time;
5783: my $found=&addline($fname,$clientname,$clientip,
5784: "$clientname:$clientip:$now\n");
5785: if ($found) { $result="$fname\n"; }
5786: # if they were subscribed to only meta data, delete that
5787: # subscription, when you subscribe to a file you also get
5788: # the metadata
5789: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
5790: $fname=~s/\/home\/httpd\/html\/res/raw/;
5791: $fname="http://$thisserver/".$fname;
5792: $result="$fname\n";
5793: }
5794: } else {
5795: $result="not_found\n";
5796: }
5797: } else {
5798: $result="rejected\n";
5799: }
5800: return $result;
5801: }
5802: # Change the passwd of a unix user. The caller must have
5803: # first verified that the user is a loncapa user.
5804: #
5805: # Parameters:
5806: # user - Unix user name to change.
5807: # pass - New password for the user.
5808: # Returns:
5809: # ok - if success
5810: # other - Some meaningfule error message string.
5811: # NOTE:
5812: # invokes a setuid script to change the passwd.
5813: sub change_unix_password {
5814: my ($user, $pass) = @_;
5815:
5816: &Debug("change_unix_password");
5817: my $execdir=$perlvar{'lonDaemons'};
5818: &Debug("Opening lcpasswd pipeline");
5819: my $pf = IO::File->new("|$execdir/lcpasswd > "
5820: ."$perlvar{'lonDaemons'}"
5821: ."/logs/lcpasswd.log");
5822: print $pf "$user\n$pass\n$pass\n";
5823: close $pf;
5824: my $err = $?;
5825: return ($err < @passwderrors) ? $passwderrors[$err] :
5826: "pwchange_falure - unknown error";
5827:
5828:
5829: }
5830:
5831:
5832: sub make_passwd_file {
5833: my ($uname, $umode,$npass,$passfilename)=@_;
5834: my $result="ok\n";
5835: if ($umode eq 'krb4' or $umode eq 'krb5') {
5836: {
5837: my $pf = IO::File->new(">$passfilename");
5838: if ($pf) {
5839: print $pf "$umode:$npass\n";
5840: } else {
5841: $result = "pass_file_failed_error";
5842: }
5843: }
5844: } elsif ($umode eq 'internal') {
5845: my $salt=time;
5846: $salt=substr($salt,6,2);
5847: my $ncpass=crypt($npass,$salt);
5848: {
5849: &Debug("Creating internal auth");
5850: my $pf = IO::File->new(">$passfilename");
5851: if($pf) {
5852: print $pf "internal:$ncpass\n";
5853: } else {
5854: $result = "pass_file_failed_error";
5855: }
5856: }
5857: } elsif ($umode eq 'localauth') {
5858: {
5859: my $pf = IO::File->new(">$passfilename");
5860: if($pf) {
5861: print $pf "localauth:$npass\n";
5862: } else {
5863: $result = "pass_file_failed_error";
5864: }
5865: }
5866: } elsif ($umode eq 'unix') {
5867: {
5868: #
5869: # Don't allow the creation of privileged accounts!!! that would
5870: # be real bad!!!
5871: #
5872: my $uid = getpwnam($uname);
5873: if((defined $uid) && ($uid == 0)) {
5874: &logthis(">>>Attempted to create privilged account blocked");
5875: return "no_priv_account_error\n";
5876: }
5877:
5878: my $execpath ="$perlvar{'lonDaemons'}/"."lcuseradd";
5879:
5880: my $lc_error_file = $execdir."/tmp/lcuseradd".$$.".status";
5881: {
5882: &Debug("Executing external: ".$execpath);
5883: &Debug("user = ".$uname.", Password =". $npass);
5884: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
5885: print $se "$uname\n";
5886: print $se "$npass\n";
5887: print $se "$npass\n";
5888: print $se "$lc_error_file\n"; # Status -> unique file.
5889: }
5890: if (-r $lc_error_file) {
5891: &Debug("Opening error file: $lc_error_file");
5892: my $error = IO::File->new("< $lc_error_file");
5893: my $useraddok = <$error>;
5894: $error->close;
5895: unlink($lc_error_file);
5896:
5897: chomp $useraddok;
5898:
5899: if($useraddok > 0) {
5900: my $error_text = &lcuseraddstrerror($useraddok);
5901: &logthis("Failed lcuseradd: $error_text");
5902: $result = "lcuseradd_failed:$error_text\n";
5903: } else {
5904: my $pf = IO::File->new(">$passfilename");
5905: if($pf) {
5906: print $pf "unix:\n";
5907: } else {
5908: $result = "pass_file_failed_error";
5909: }
5910: }
5911: } else {
5912: &Debug("Could not locate lcuseradd error: $lc_error_file");
5913: $result="bug_lcuseradd_no_output_file";
5914: }
5915: }
5916: } elsif ($umode eq 'none') {
5917: {
5918: my $pf = IO::File->new("> $passfilename");
5919: if($pf) {
5920: print $pf "none:\n";
5921: } else {
5922: $result = "pass_file_failed_error";
5923: }
5924: }
5925: } else {
5926: $result="auth_mode_error\n";
5927: }
5928: return $result;
5929: }
5930:
5931: sub convert_photo {
5932: my ($start,$dest)=@_;
5933: system("convert $start $dest");
5934: }
5935:
5936: sub sethost {
5937: my ($remotereq) = @_;
5938: my (undef,$hostid)=split(/:/,$remotereq);
5939: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
5940: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
5941: $currenthostid =$hostid;
5942: $currentdomainid=$hostdom{$hostid};
5943: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
5944: } else {
5945: &logthis("Requested host id $hostid not an alias of ".
5946: $perlvar{'lonHostID'}." refusing connection");
5947: return 'unable_to_set';
5948: }
5949: return 'ok';
5950: }
5951:
5952: sub version {
5953: my ($userinput)=@_;
5954: $remoteVERSION=(split(/:/,$userinput))[1];
5955: return "version:$VERSION";
5956: }
5957:
5958: #There is a copy of this in lonnet.pm
5959: sub userload {
5960: my $numusers=0;
5961: {
5962: opendir(LONIDS,$perlvar{'lonIDsDir'});
5963: my $filename;
5964: my $curtime=time;
5965: while ($filename=readdir(LONIDS)) {
5966: if ($filename eq '.' || $filename eq '..') {next;}
5967: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
5968: if ($curtime-$mtime < 1800) { $numusers++; }
5969: }
5970: closedir(LONIDS);
5971: }
5972: my $userloadpercent=0;
5973: my $maxuserload=$perlvar{'lonUserLoadLim'};
5974: if ($maxuserload) {
5975: $userloadpercent=100*$numusers/$maxuserload;
5976: }
5977: $userloadpercent=sprintf("%.2f",$userloadpercent);
5978: return $userloadpercent;
5979: }
5980:
5981: # Routines for serializing arrays and hashes (copies from lonnet)
5982:
5983: sub array2str {
5984: my (@array) = @_;
5985: my $result=&arrayref2str(\@array);
5986: $result=~s/^__ARRAY_REF__//;
5987: $result=~s/__END_ARRAY_REF__$//;
5988: return $result;
5989: }
5990:
5991: sub arrayref2str {
5992: my ($arrayref) = @_;
5993: my $result='__ARRAY_REF__';
5994: foreach my $elem (@$arrayref) {
5995: if(ref($elem) eq 'ARRAY') {
5996: $result.=&arrayref2str($elem).'&';
5997: } elsif(ref($elem) eq 'HASH') {
5998: $result.=&hashref2str($elem).'&';
5999: } elsif(ref($elem)) {
6000: #print("Got a ref of ".(ref($elem))." skipping.");
6001: } else {
6002: $result.=&escape($elem).'&';
6003: }
6004: }
6005: $result=~s/\&$//;
6006: $result .= '__END_ARRAY_REF__';
6007: return $result;
6008: }
6009:
6010: sub hash2str {
6011: my (%hash) = @_;
6012: my $result=&hashref2str(\%hash);
6013: $result=~s/^__HASH_REF__//;
6014: $result=~s/__END_HASH_REF__$//;
6015: return $result;
6016: }
6017:
6018: sub hashref2str {
6019: my ($hashref)=@_;
6020: my $result='__HASH_REF__';
6021: foreach (sort(keys(%$hashref))) {
6022: if (ref($_) eq 'ARRAY') {
6023: $result.=&arrayref2str($_).'=';
6024: } elsif (ref($_) eq 'HASH') {
6025: $result.=&hashref2str($_).'=';
6026: } elsif (ref($_)) {
6027: $result.='=';
6028: #print("Got a ref of ".(ref($_))." skipping.");
6029: } else {
6030: if ($_) {$result.=&escape($_).'=';} else { last; }
6031: }
6032:
6033: if(ref($hashref->{$_}) eq 'ARRAY') {
6034: $result.=&arrayref2str($hashref->{$_}).'&';
6035: } elsif(ref($hashref->{$_}) eq 'HASH') {
6036: $result.=&hashref2str($hashref->{$_}).'&';
6037: } elsif(ref($hashref->{$_})) {
6038: $result.='&';
6039: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
6040: } else {
6041: $result.=&escape($hashref->{$_}).'&';
6042: }
6043: }
6044: $result=~s/\&$//;
6045: $result .= '__END_HASH_REF__';
6046: return $result;
6047: }
6048:
6049: # ----------------------------------- POD (plain old documentation, CPAN style)
6050:
6051: =head1 NAME
6052:
6053: lond - "LON Daemon" Server (port "LOND" 5663)
6054:
6055: =head1 SYNOPSIS
6056:
6057: Usage: B<lond>
6058:
6059: Should only be run as user=www. This is a command-line script which
6060: is invoked by B<loncron>. There is no expectation that a typical user
6061: will manually start B<lond> from the command-line. (In other words,
6062: DO NOT START B<lond> YOURSELF.)
6063:
6064: =head1 DESCRIPTION
6065:
6066: There are two characteristics associated with the running of B<lond>,
6067: PROCESS MANAGEMENT (starting, stopping, handling child processes)
6068: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
6069: subscriptions, etc). These are described in two large
6070: sections below.
6071:
6072: B<PROCESS MANAGEMENT>
6073:
6074: Preforker - server who forks first. Runs as a daemon. HUPs.
6075: Uses IDEA encryption
6076:
6077: B<lond> forks off children processes that correspond to the other servers
6078: in the network. Management of these processes can be done at the
6079: parent process level or the child process level.
6080:
6081: B<logs/lond.log> is the location of log messages.
6082:
6083: The process management is now explained in terms of linux shell commands,
6084: subroutines internal to this code, and signal assignments:
6085:
6086: =over 4
6087:
6088: =item *
6089:
6090: PID is stored in B<logs/lond.pid>
6091:
6092: This is the process id number of the parent B<lond> process.
6093:
6094: =item *
6095:
6096: SIGTERM and SIGINT
6097:
6098: Parent signal assignment:
6099: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
6100:
6101: Child signal assignment:
6102: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
6103: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
6104: to restart a new child.)
6105:
6106: Command-line invocations:
6107: B<kill> B<-s> SIGTERM I<PID>
6108: B<kill> B<-s> SIGINT I<PID>
6109:
6110: Subroutine B<HUNTSMAN>:
6111: This is only invoked for the B<lond> parent I<PID>.
6112: This kills all the children, and then the parent.
6113: The B<lonc.pid> file is cleared.
6114:
6115: =item *
6116:
6117: SIGHUP
6118:
6119: Current bug:
6120: This signal can only be processed the first time
6121: on the parent process. Subsequent SIGHUP signals
6122: have no effect.
6123:
6124: Parent signal assignment:
6125: $SIG{HUP} = \&HUPSMAN;
6126:
6127: Child signal assignment:
6128: none (nothing happens)
6129:
6130: Command-line invocations:
6131: B<kill> B<-s> SIGHUP I<PID>
6132:
6133: Subroutine B<HUPSMAN>:
6134: This is only invoked for the B<lond> parent I<PID>,
6135: This kills all the children, and then the parent.
6136: The B<lond.pid> file is cleared.
6137:
6138: =item *
6139:
6140: SIGUSR1
6141:
6142: Parent signal assignment:
6143: $SIG{USR1} = \&USRMAN;
6144:
6145: Child signal assignment:
6146: $SIG{USR1}= \&logstatus;
6147:
6148: Command-line invocations:
6149: B<kill> B<-s> SIGUSR1 I<PID>
6150:
6151: Subroutine B<USRMAN>:
6152: When invoked for the B<lond> parent I<PID>,
6153: SIGUSR1 is sent to all the children, and the status of
6154: each connection is logged.
6155:
6156: =item *
6157:
6158: SIGUSR2
6159:
6160: Parent Signal assignment:
6161: $SIG{USR2} = \&UpdateHosts
6162:
6163: Child signal assignment:
6164: NONE
6165:
6166:
6167: =item *
6168:
6169: SIGCHLD
6170:
6171: Parent signal assignment:
6172: $SIG{CHLD} = \&REAPER;
6173:
6174: Child signal assignment:
6175: none
6176:
6177: Command-line invocations:
6178: B<kill> B<-s> SIGCHLD I<PID>
6179:
6180: Subroutine B<REAPER>:
6181: This is only invoked for the B<lond> parent I<PID>.
6182: Information pertaining to the child is removed.
6183: The socket port is cleaned up.
6184:
6185: =back
6186:
6187: B<SERVER-SIDE ACTIVITIES>
6188:
6189: Server-side information can be accepted in an encrypted or non-encrypted
6190: method.
6191:
6192: =over 4
6193:
6194: =item ping
6195:
6196: Query a client in the hosts.tab table; "Are you there?"
6197:
6198: =item pong
6199:
6200: Respond to a ping query.
6201:
6202: =item ekey
6203:
6204: Read in encrypted key, make cipher. Respond with a buildkey.
6205:
6206: =item load
6207:
6208: Respond with CPU load based on a computation upon /proc/loadavg.
6209:
6210: =item currentauth
6211:
6212: Reply with current authentication information (only over an
6213: encrypted channel).
6214:
6215: =item auth
6216:
6217: Only over an encrypted channel, reply as to whether a user's
6218: authentication information can be validated.
6219:
6220: =item passwd
6221:
6222: Allow for a password to be set.
6223:
6224: =item makeuser
6225:
6226: Make a user.
6227:
6228: =item passwd
6229:
6230: Allow for authentication mechanism and password to be changed.
6231:
6232: =item home
6233:
6234: Respond to a question "are you the home for a given user?"
6235:
6236: =item update
6237:
6238: Update contents of a subscribed resource.
6239:
6240: =item unsubscribe
6241:
6242: The server is unsubscribing from a resource.
6243:
6244: =item subscribe
6245:
6246: The server is subscribing to a resource.
6247:
6248: =item log
6249:
6250: Place in B<logs/lond.log>
6251:
6252: =item put
6253:
6254: stores hash in namespace
6255:
6256: =item rolesputy
6257:
6258: put a role into a user's environment
6259:
6260: =item get
6261:
6262: returns hash with keys from array
6263: reference filled in from namespace
6264:
6265: =item eget
6266:
6267: returns hash with keys from array
6268: reference filled in from namesp (encrypts the return communication)
6269:
6270: =item rolesget
6271:
6272: get a role from a user's environment
6273:
6274: =item del
6275:
6276: deletes keys out of array from namespace
6277:
6278: =item keys
6279:
6280: returns namespace keys
6281:
6282: =item dump
6283:
6284: dumps the complete (or key matching regexp) namespace into a hash
6285:
6286: =item store
6287:
6288: stores hash permanently
6289: for this url; hashref needs to be given and should be a \%hashname; the
6290: remaining args aren't required and if they aren't passed or are '' they will
6291: be derived from the ENV
6292:
6293: =item restore
6294:
6295: returns a hash for a given url
6296:
6297: =item querysend
6298:
6299: Tells client about the lonsql process that has been launched in response
6300: to a sent query.
6301:
6302: =item queryreply
6303:
6304: Accept information from lonsql and make appropriate storage in temporary
6305: file space.
6306:
6307: =item idput
6308:
6309: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
6310: for each student, defined perhaps by the institutional Registrar.)
6311:
6312: =item idget
6313:
6314: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
6315: for each student, defined perhaps by the institutional Registrar.)
6316:
6317: =item tmpput
6318:
6319: Accept and store information in temporary space.
6320:
6321: =item tmpget
6322:
6323: Send along temporarily stored information.
6324:
6325: =item ls
6326:
6327: List part of a user's directory.
6328:
6329: =item pushtable
6330:
6331: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
6332: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
6333: must be restored manually in case of a problem with the new table file.
6334: pushtable requires that the request be encrypted and validated via
6335: ValidateManager. The form of the command is:
6336: enc:pushtable tablename <tablecontents> \n
6337: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
6338: cleartext newline.
6339:
6340: =item Hanging up (exit or init)
6341:
6342: What to do when a client tells the server that they (the client)
6343: are leaving the network.
6344:
6345: =item unknown command
6346:
6347: If B<lond> is sent an unknown command (not in the list above),
6348: it replys to the client "unknown_cmd".
6349:
6350:
6351: =item UNKNOWN CLIENT
6352:
6353: If the anti-spoofing algorithm cannot verify the client,
6354: the client is rejected (with a "refused" message sent
6355: to the client, and the connection is closed.
6356:
6357: =back
6358:
6359: =head1 PREREQUISITES
6360:
6361: IO::Socket
6362: IO::File
6363: Apache::File
6364: Symbol
6365: POSIX
6366: Crypt::IDEA
6367: LWP::UserAgent()
6368: GDBM_File
6369: Authen::Krb4
6370: Authen::Krb5
6371:
6372: =head1 COREQUISITES
6373:
6374: =head1 OSNAMES
6375:
6376: linux
6377:
6378: =head1 SCRIPT CATEGORIES
6379:
6380: Server/Process
6381:
6382: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>