1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
4: #
5: # $Id: lond,v 1.446.2.2 2011/09/02 13:10:38 raeburn 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;
35: use LONCAPA::Configuration;
36:
37: use IO::Socket;
38: use IO::File;
39: #use Apache::File;
40: use POSIX;
41: use Crypt::IDEA;
42: use LWP::UserAgent();
43: use Digest::MD5 qw(md5_hex);
44: use GDBM_File;
45: use Authen::Krb5;
46: use localauth;
47: use localenroll;
48: use localstudentphoto;
49: use File::Copy;
50: use File::Find;
51: use LONCAPA::lonlocal;
52: use LONCAPA::lonssl;
53: use Fcntl qw(:flock);
54: use Apache::lonnet;
55:
56: my $DEBUG = 0; # Non zero to enable debug log entries.
57:
58: my $status='';
59: my $lastlog='';
60:
61: my $VERSION='$Revision: 1.446.2.2 $'; #' stupid emacs
62: my $remoteVERSION;
63: my $currenthostid="default";
64: my $currentdomainid;
65:
66: my $client;
67: my $clientip; # IP address of client.
68: my $clientname; # LonCAPA name of client.
69: my $clientversion; # LonCAPA version running on client
70:
71: my $server;
72:
73: my $keymode;
74:
75: my $cipher; # Cipher key negotiated with client
76: my $tmpsnum = 0; # Id of tmpputs.
77:
78: #
79: # Connection type is:
80: # client - All client actions are allowed
81: # manager - only management functions allowed.
82: # both - Both management and client actions are allowed
83: #
84:
85: my $ConnectionType;
86:
87: my %managers; # Ip -> manager names
88:
89: my %perlvar; # Will have the apache conf defined perl vars.
90:
91: #
92: # The hash below is used for command dispatching, and is therefore keyed on the request keyword.
93: # Each element of the hash contains a reference to an array that contains:
94: # A reference to a sub that executes the request corresponding to the keyword.
95: # A flag that is true if the request must be encoded to be acceptable.
96: # A mask with bits as follows:
97: # CLIENT_OK - Set when the function is allowed by ordinary clients
98: # MANAGER_OK - Set when the function is allowed to manager clients.
99: #
100: my $CLIENT_OK = 1;
101: my $MANAGER_OK = 2;
102: my %Dispatcher;
103:
104:
105: #
106: # The array below are password error strings."
107: #
108: my $lastpwderror = 13; # Largest error number from lcpasswd.
109: my @passwderrors = ("ok",
110: "pwchange_failure - lcpasswd must be run as user 'www'",
111: "pwchange_failure - lcpasswd got incorrect number of arguments",
112: "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
113: "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
114: "pwchange_failure - lcpasswd User does not exist.",
115: "pwchange_failure - lcpasswd Incorrect current passwd",
116: "pwchange_failure - lcpasswd Unable to su to root.",
117: "pwchange_failure - lcpasswd Cannot set new passwd.",
118: "pwchange_failure - lcpasswd Username has invalid characters",
119: "pwchange_failure - lcpasswd Invalid characters in password",
120: "pwchange_failure - lcpasswd User already exists",
121: "pwchange_failure - lcpasswd Something went wrong with user addition.",
122: "pwchange_failure - lcpasswd Password mismatch",
123: "pwchange_failure - lcpasswd Error filename is invalid");
124:
125:
126: # The array below are lcuseradd error strings.:
127:
128: my $lastadderror = 13;
129: my @adderrors = ("ok",
130: "User ID mismatch, lcuseradd must run as user www",
131: "lcuseradd Incorrect number of command line parameters must be 3",
132: "lcuseradd Incorrect number of stdinput lines, must be 3",
133: "lcuseradd Too many other simultaneous pwd changes in progress",
134: "lcuseradd User does not exist",
135: "lcuseradd Unable to make www member of users's group",
136: "lcuseradd Unable to su to root",
137: "lcuseradd Unable to set password",
138: "lcuseradd Username has invalid characters",
139: "lcuseradd Password has an invalid character",
140: "lcuseradd User already exists",
141: "lcuseradd Could not add user.",
142: "lcuseradd Password mismatch");
143:
144:
145: # This array are the errors from lcinstallfile:
146:
147: my @installerrors = ("ok",
148: "Initial user id of client not that of www",
149: "Usage error, not enough command line arguments",
150: "Source file name does not exist",
151: "Destination file name does not exist",
152: "Some file operation failed",
153: "Invalid table filename."
154: );
155:
156: #
157: # Statistics that are maintained and dislayed in the status line.
158: #
159: my $Transactions = 0; # Number of attempted transactions.
160: my $Failures = 0; # Number of transcations failed.
161:
162: # ResetStatistics:
163: # Resets the statistics counters:
164: #
165: sub ResetStatistics {
166: $Transactions = 0;
167: $Failures = 0;
168: }
169:
170: #------------------------------------------------------------------------
171: #
172: # LocalConnection
173: # Completes the formation of a locally authenticated connection.
174: # This function will ensure that the 'remote' client is really the
175: # local host. If not, the connection is closed, and the function fails.
176: # If so, initcmd is parsed for the name of a file containing the
177: # IDEA session key. The fie is opened, read, deleted and the session
178: # key returned to the caller.
179: #
180: # Parameters:
181: # $Socket - Socket open on client.
182: # $initcmd - The full text of the init command.
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");
191: if($clientip ne "127.0.0.1") {
192: &logthis('<font color="red"> LocalConnection rejecting non local: '
193: ."$clientip ne 127.0.0.1 </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: &Debug("Reading manager table");
412: # Clean out the old table first..
413:
414: foreach my $key (keys %managers) {
415: delete $managers{$key};
416: }
417:
418: my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
419: if (!open (MANAGERS, $tablename)) {
420: logthis('<font color="red">No manager table. Nobody can manage!!</font>');
421: return;
422: }
423: while(my $host = <MANAGERS>) {
424: chomp($host);
425: if ($host =~ "^#") { # Comment line.
426: next;
427: }
428: if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
429: # The entry is of the form:
430: # cluname:hostname
431: # cluname - A 'cluster hostname' is needed in order to negotiate
432: # the host key.
433: # hostname- The dns name of the host.
434: #
435: my($cluname, $dnsname) = split(/:/, $host);
436:
437: my $ip = gethostbyname($dnsname);
438: if(defined($ip)) { # bad names don't deserve entry.
439: my $hostip = inet_ntoa($ip);
440: $managers{$hostip} = $cluname;
441: logthis('<font color="green"> registering manager '.
442: "$dnsname as $cluname with $hostip </font>\n");
443: }
444: } else {
445: logthis('<font color="green"> existing host'." $host</font>\n");
446: $managers{&Apache::lonnet::get_host_ip($host)} = $host; # Use info from cluster tab if clumemeber
447: }
448: }
449: }
450:
451: #
452: # ValidManager: Determines if a given certificate represents a valid manager.
453: # in this primitive implementation, the 'certificate' is
454: # just the connecting loncapa client name. This is checked
455: # against a valid client list in the configuration.
456: #
457: #
458: sub ValidManager {
459: my $certificate = shift;
460:
461: return isManager;
462: }
463: #
464: # CopyFile: Called as part of the process of installing a
465: # new configuration file. This function copies an existing
466: # file to a backup file.
467: # Parameters:
468: # oldfile - Name of the file to backup.
469: # newfile - Name of the backup file.
470: # Return:
471: # 0 - Failure (errno has failure reason).
472: # 1 - Success.
473: #
474: sub CopyFile {
475:
476: my ($oldfile, $newfile) = @_;
477:
478: if (! copy($oldfile,$newfile)) {
479: return 0;
480: }
481: chmod(0660, $newfile);
482: return 1;
483: }
484: #
485: # Host files are passed out with externally visible host IPs.
486: # If, for example, we are behind a fire-wall or NAT host, our
487: # internally visible IP may be different than the externally
488: # visible IP. Therefore, we always adjust the contents of the
489: # host file so that the entry for ME is the IP that we believe
490: # we have. At present, this is defined as the entry that
491: # DNS has for us. If by some chance we are not able to get a
492: # DNS translation for us, then we assume that the host.tab file
493: # is correct.
494: # BUGBUGBUG - in the future, we really should see if we can
495: # easily query the interface(s) instead.
496: # Parameter(s):
497: # contents - The contents of the host.tab to check.
498: # Returns:
499: # newcontents - The adjusted contents.
500: #
501: #
502: sub AdjustHostContents {
503: my $contents = shift;
504: my $adjusted;
505: my $me = $perlvar{'lonHostID'};
506:
507: foreach my $line (split(/\n/,$contents)) {
508: if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
509: chomp($line);
510: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
511: if ($id eq $me) {
512: my $ip = gethostbyname($name);
513: my $ipnew = inet_ntoa($ip);
514: $ip = $ipnew;
515: # Reconstruct the host line and append to adjusted:
516:
517: my $newline = "$id:$domain:$role:$name:$ip";
518: if($maxcon ne "") { # Not all hosts have loncnew tuning params
519: $newline .= ":$maxcon:$idleto:$mincon";
520: }
521: $adjusted .= $newline."\n";
522:
523: } else { # Not me, pass unmodified.
524: $adjusted .= $line."\n";
525: }
526: } else { # Blank or comment never re-written.
527: $adjusted .= $line."\n"; # Pass blanks and comments as is.
528: }
529: }
530: return $adjusted;
531: }
532: #
533: # InstallFile: Called to install an administrative file:
534: # - The file is created int a temp directory called <name>.tmp
535: # - lcinstall file is called to install the file.
536: # since the web app has no direct write access to the table directory
537: #
538: # Parameters:
539: # Name of the file
540: # File Contents.
541: # Return:
542: # nonzero - success.
543: # 0 - failure and $! has an errno.
544: # Assumptions:
545: # File installtion is a relatively infrequent
546: #
547: sub InstallFile {
548:
549: my ($Filename, $Contents) = @_;
550: # my $TempFile = $Filename.".tmp";
551: my $exedir = $perlvar{'lonDaemons'};
552: my $tmpdir = $exedir.'/tmp/';
553: my $TempFile = $tmpdir."TempTableFile.tmp";
554:
555: # Open the file for write:
556:
557: my $fh = IO::File->new("> $TempFile"); # Write to temp.
558: if(!(defined $fh)) {
559: &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
560: return 0;
561: }
562: # write the contents of the file:
563:
564: print $fh ($Contents);
565: $fh->close; # In case we ever have a filesystem w. locking
566:
567: chmod(0664, $TempFile); # Everyone can write it.
568:
569: # Use lcinstall file to put the file in the table directory...
570:
571: &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
572: my $pf = IO::File->new("| $exedir/lcinstallfile $TempFile $Filename > $exedir/logs/lcinstallfile.log");
573: close $pf;
574: my $err = $?;
575: &Debug("Status is $err");
576: if ($err != 0) {
577: my $msg = $err;
578: if ($err < @installerrors) {
579: $msg = $installerrors[$err];
580: }
581: &logthis("Install failed for table file $Filename : $msg");
582: return 0;
583: }
584:
585: # Remove the temp file:
586:
587: unlink($TempFile);
588:
589: return 1;
590: }
591:
592:
593: #
594: # ConfigFileFromSelector: converts a configuration file selector
595: # into a configuration file pathname.
596: # It's probably no longer necessary to preserve
597: # special handling of hosts or domain as those
598: # files have been superceded by dns_hosts, dns_domain.
599: # The default action is just to prepend the directory
600: # and append .tab
601: #
602: #
603: # Parameters:
604: # selector - Configuration file selector.
605: # Returns:
606: # Full path to the file or undef if the selector is invalid.
607: #
608: sub ConfigFileFromSelector {
609: my $selector = shift;
610: my $tablefile;
611:
612: my $tabledir = $perlvar{'lonTabDir'}.'/';
613: if ($selector eq "hosts") {
614: $tablefile = $tabledir."hosts.tab";
615: } elsif ($selector eq "domain") {
616: $tablefile = $tabledir."domain.tab";
617: } else {
618: $tablefile = $tabledir.$selector.'.tab';
619: }
620: return $tablefile;
621:
622: }
623: #
624: # PushFile: Called to do an administrative push of a file.
625: # - Ensure the file being pushed is one we support.
626: # - Backup the old file to <filename.saved>
627: # - Separate the contents of the new file out from the
628: # rest of the request.
629: # - Write the new file.
630: # Parameter:
631: # Request - The entire user request. This consists of a : separated
632: # string pushfile:tablename:contents.
633: # NOTE: The contents may have :'s in it as well making things a bit
634: # more interesting... but not much.
635: # Returns:
636: # String to send to client ("ok" or "refused" if bad file).
637: #
638: sub PushFile {
639: my $request = shift;
640: my ($command, $filename, $contents) = split(":", $request, 3);
641: &Debug("PushFile");
642:
643: # At this point in time, pushes for only the following tables are
644: # supported:
645: # hosts.tab ($filename eq host).
646: # domain.tab ($filename eq domain).
647: # Construct the destination filename or reject the request.
648: #
649: # lonManage is supposed to ensure this, however this session could be
650: # part of some elaborate spoof that managed somehow to authenticate.
651: #
652:
653:
654: my $tablefile = ConfigFileFromSelector($filename);
655: if(! (defined $tablefile)) {
656: return "refused";
657: }
658:
659: # If the file being pushed is the host file, we adjust the entry for ourself so that the
660: # IP will be our current IP as looked up in dns. Note this is only 99% good as it's possible
661: # to conceive of conditions where we don't have a DNS entry locally. This is possible in a
662: # network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
663: # that possibilty.
664:
665: if($filename eq "host") {
666: $contents = AdjustHostContents($contents);
667: }
668:
669: # Install the new file:
670:
671: &logthis("Installing new $tablefile contents:\n$contents");
672: if(!InstallFile($tablefile, $contents)) {
673: &logthis('<font color="red"> Pushfile: unable to install '
674: .$tablefile." $! </font>");
675: return "error:$!";
676: } else {
677: &logthis('<font color="green"> Installed new '.$tablefile
678: ."</font>");
679:
680: }
681:
682:
683: # Indicate success:
684:
685: return "ok";
686:
687: }
688:
689: #
690: # Called to re-init either lonc or lond.
691: #
692: # Parameters:
693: # request - The full request by the client. This is of the form
694: # reinit:<process>
695: # where <process> is allowed to be either of
696: # lonc or lond
697: #
698: # Returns:
699: # The string to be sent back to the client either:
700: # ok - Everything worked just fine.
701: # error:why - There was a failure and why describes the reason.
702: #
703: #
704: sub ReinitProcess {
705: my $request = shift;
706:
707:
708: # separate the request (reinit) from the process identifier and
709: # validate it producing the name of the .pid file for the process.
710: #
711: #
712: my ($junk, $process) = split(":", $request);
713: my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
714: if($process eq 'lonc') {
715: $processpidfile = $processpidfile."lonc.pid";
716: if (!open(PIDFILE, "< $processpidfile")) {
717: return "error:Open failed for $processpidfile";
718: }
719: my $loncpid = <PIDFILE>;
720: close(PIDFILE);
721: logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
722: ."</font>");
723: kill("USR2", $loncpid);
724: } elsif ($process eq 'lond') {
725: logthis('<font color="red"> Reinitializing self (lond) </font>');
726: &UpdateHosts; # Lond is us!!
727: } else {
728: &logthis('<font color="yellow" Invalid reinit request for '.$process
729: ."</font>");
730: return "error:Invalid process identifier $process";
731: }
732: return 'ok';
733: }
734: # Validate a line in a configuration file edit script:
735: # Validation includes:
736: # - Ensuring the command is valid.
737: # - Ensuring the command has sufficient parameters
738: # Parameters:
739: # scriptline - A line to validate (\n has been stripped for what it's worth).
740: #
741: # Return:
742: # 0 - Invalid scriptline.
743: # 1 - Valid scriptline
744: # NOTE:
745: # Only the command syntax is checked, not the executability of the
746: # command.
747: #
748: sub isValidEditCommand {
749: my $scriptline = shift;
750:
751: # Line elements are pipe separated:
752:
753: my ($command, $key, $newline) = split(/\|/, $scriptline);
754: &logthis('<font color="green"> isValideditCommand checking: '.
755: "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
756:
757: if ($command eq "delete") {
758: #
759: # key with no newline.
760: #
761: if( ($key eq "") || ($newline ne "")) {
762: return 0; # Must have key but no newline.
763: } else {
764: return 1; # Valid syntax.
765: }
766: } elsif ($command eq "replace") {
767: #
768: # key and newline:
769: #
770: if (($key eq "") || ($newline eq "")) {
771: return 0;
772: } else {
773: return 1;
774: }
775: } elsif ($command eq "append") {
776: if (($key ne "") && ($newline eq "")) {
777: return 1;
778: } else {
779: return 0;
780: }
781: } else {
782: return 0; # Invalid command.
783: }
784: return 0; # Should not get here!!!
785: }
786: #
787: # ApplyEdit - Applies an edit command to a line in a configuration
788: # file. It is the caller's responsiblity to validate the
789: # edit line.
790: # Parameters:
791: # $directive - A single edit directive to apply.
792: # Edit directives are of the form:
793: # append|newline - Appends a new line to the file.
794: # replace|key|newline - Replaces the line with key value 'key'
795: # delete|key - Deletes the line with key value 'key'.
796: # $editor - A config file editor object that contains the
797: # file being edited.
798: #
799: sub ApplyEdit {
800:
801: my ($directive, $editor) = @_;
802:
803: # Break the directive down into its command and its parameters
804: # (at most two at this point. The meaning of the parameters, if in fact
805: # they exist depends on the command).
806:
807: my ($command, $p1, $p2) = split(/\|/, $directive);
808:
809: if($command eq "append") {
810: $editor->Append($p1); # p1 - key p2 null.
811: } elsif ($command eq "replace") {
812: $editor->ReplaceLine($p1, $p2); # p1 - key p2 = newline.
813: } elsif ($command eq "delete") {
814: $editor->DeleteLine($p1); # p1 - key p2 null.
815: } else { # Should not get here!!!
816: die "Invalid command given to ApplyEdit $command"
817: }
818: }
819: #
820: # AdjustOurHost:
821: # Adjusts a host file stored in a configuration file editor object
822: # for the true IP address of this host. This is necessary for hosts
823: # that live behind a firewall.
824: # Those hosts have a publicly distributed IP of the firewall, but
825: # internally must use their actual IP. We assume that a given
826: # host only has a single IP interface for now.
827: # Formal Parameters:
828: # editor - The configuration file editor to adjust. This
829: # editor is assumed to contain a hosts.tab file.
830: # Strategy:
831: # - Figure out our hostname.
832: # - Lookup the entry for this host.
833: # - Modify the line to contain our IP
834: # - Do a replace for this host.
835: sub AdjustOurHost {
836: my $editor = shift;
837:
838: # figure out who I am.
839:
840: my $myHostName = $perlvar{'lonHostID'}; # LonCAPA hostname.
841:
842: # Get my host file entry.
843:
844: my $ConfigLine = $editor->Find($myHostName);
845: if(! (defined $ConfigLine)) {
846: die "AdjustOurHost - no entry for me in hosts file $myHostName";
847: }
848: # figure out my IP:
849: # Use the config line to get my hostname.
850: # Use gethostbyname to translate that into an IP address.
851: #
852: my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
853: #
854: # Reassemble the config line from the elements in the list.
855: # Note that if the loncnew items were not present before, they will
856: # be now even if they would be empty
857: #
858: my $newConfigLine = $id;
859: foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
860: $newConfigLine .= ":".$item;
861: }
862: # Replace the line:
863:
864: $editor->ReplaceLine($id, $newConfigLine);
865:
866: }
867: #
868: # ReplaceConfigFile:
869: # Replaces a configuration file with the contents of a
870: # configuration file editor object.
871: # This is done by:
872: # - Copying the target file to <filename>.old
873: # - Writing the new file to <filename>.tmp
874: # - Moving <filename.tmp> -> <filename>
875: # This laborious process ensures that the system is never without
876: # a configuration file that's at least valid (even if the contents
877: # may be dated).
878: # Parameters:
879: # filename - Name of the file to modify... this is a full path.
880: # editor - Editor containing the file.
881: #
882: sub ReplaceConfigFile {
883:
884: my ($filename, $editor) = @_;
885:
886: CopyFile ($filename, $filename.".old");
887:
888: my $contents = $editor->Get(); # Get the contents of the file.
889:
890: InstallFile($filename, $contents);
891: }
892: #
893: #
894: # Called to edit a configuration table file
895: # Parameters:
896: # request - The entire command/request sent by lonc or lonManage
897: # Return:
898: # The reply to send to the client.
899: #
900: sub EditFile {
901: my $request = shift;
902:
903: # Split the command into it's pieces: edit:filetype:script
904:
905: my ($cmd, $filetype, $script) = split(/:/, $request,3); # : in script
906:
907: # Check the pre-coditions for success:
908:
909: if($cmd != "edit") { # Something is amiss afoot alack.
910: return "error:edit request detected, but request != 'edit'\n";
911: }
912: if( ($filetype ne "hosts") &&
913: ($filetype ne "domain")) {
914: return "error:edit requested with invalid file specifier: $filetype \n";
915: }
916:
917: # Split the edit script and check it's validity.
918:
919: my @scriptlines = split(/\n/, $script); # one line per element.
920: my $linecount = scalar(@scriptlines);
921: for(my $i = 0; $i < $linecount; $i++) {
922: chomp($scriptlines[$i]);
923: if(!isValidEditCommand($scriptlines[$i])) {
924: return "error:edit with bad script line: '$scriptlines[$i]' \n";
925: }
926: }
927:
928: # Execute the edit operation.
929: # - Create a config file editor for the appropriate file and
930: # - execute each command in the script:
931: #
932: my $configfile = ConfigFileFromSelector($filetype);
933: if (!(defined $configfile)) {
934: return "refused\n";
935: }
936: my $editor = ConfigFileEdit->new($configfile);
937:
938: for (my $i = 0; $i < $linecount; $i++) {
939: ApplyEdit($scriptlines[$i], $editor);
940: }
941: # If the file is the host file, ensure that our host is
942: # adjusted to have our ip:
943: #
944: if($filetype eq "host") {
945: AdjustOurHost($editor);
946: }
947: # Finally replace the current file with our file.
948: #
949: ReplaceConfigFile($configfile, $editor);
950:
951: return "ok\n";
952: }
953:
954: # read_profile
955: #
956: # Returns a set of specific entries from a user's profile file.
957: # this is a utility function that is used by both get_profile_entry and
958: # get_profile_entry_encrypted.
959: #
960: # Parameters:
961: # udom - Domain in which the user exists.
962: # uname - User's account name (loncapa account)
963: # namespace - The profile namespace to open.
964: # what - A set of & separated queries.
965: # Returns:
966: # If all ok: - The string that needs to be shipped back to the user.
967: # If failure - A string that starts with error: followed by the failure
968: # reason.. note that this probabyl gets shipped back to the
969: # user as well.
970: #
971: sub read_profile {
972: my ($udom, $uname, $namespace, $what) = @_;
973:
974: my $hashref = &tie_user_hash($udom, $uname, $namespace,
975: &GDBM_READER());
976: if ($hashref) {
977: my @queries=split(/\&/,$what);
978: if ($namespace eq 'roles') {
979: @queries = map { &unescape($_); } @queries;
980: }
981: my $qresult='';
982:
983: for (my $i=0;$i<=$#queries;$i++) {
984: $qresult.="$hashref->{$queries[$i]}&"; # Presumably failure gives empty string.
985: }
986: $qresult=~s/\&$//; # Remove trailing & from last lookup.
987: if (&untie_user_hash($hashref)) {
988: return $qresult;
989: } else {
990: return "error: ".($!+0)." untie (GDBM) Failed";
991: }
992: } else {
993: if ($!+0 == 2) {
994: return "error:No such file or GDBM reported bad block error";
995: } else {
996: return "error: ".($!+0)." tie (GDBM) Failed";
997: }
998: }
999:
1000: }
1001: #--------------------- Request Handlers --------------------------------------------
1002: #
1003: # By convention each request handler registers itself prior to the sub
1004: # declaration:
1005: #
1006:
1007: #++
1008: #
1009: # Handles ping requests.
1010: # Parameters:
1011: # $cmd - the actual keyword that invoked us.
1012: # $tail - the tail of the request that invoked us.
1013: # $replyfd- File descriptor connected to the client
1014: # Implicit Inputs:
1015: # $currenthostid - Global variable that carries the name of the host we are
1016: # known as.
1017: # Returns:
1018: # 1 - Ok to continue processing.
1019: # 0 - Program should exit.
1020: # Side effects:
1021: # Reply information is sent to the client.
1022: sub ping_handler {
1023: my ($cmd, $tail, $client) = @_;
1024: Debug("$cmd $tail $client .. $currenthostid:");
1025:
1026: Reply( $client,\$currenthostid,"$cmd:$tail");
1027:
1028: return 1;
1029: }
1030: ®ister_handler("ping", \&ping_handler, 0, 1, 1); # Ping unencoded, client or manager.
1031:
1032: #++
1033: #
1034: # Handles pong requests. Pong replies with our current host id, and
1035: # the results of a ping sent to us via our lonc.
1036: #
1037: # Parameters:
1038: # $cmd - the actual keyword that invoked us.
1039: # $tail - the tail of the request that invoked us.
1040: # $replyfd- File descriptor connected to the client
1041: # Implicit Inputs:
1042: # $currenthostid - Global variable that carries the name of the host we are
1043: # connected to.
1044: # Returns:
1045: # 1 - Ok to continue processing.
1046: # 0 - Program should exit.
1047: # Side effects:
1048: # Reply information is sent to the client.
1049: sub pong_handler {
1050: my ($cmd, $tail, $replyfd) = @_;
1051:
1052: my $reply=&Apache::lonnet::reply("ping",$clientname);
1053: &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail");
1054: return 1;
1055: }
1056: ®ister_handler("pong", \&pong_handler, 0, 1, 1); # Pong unencoded, client or manager
1057:
1058: #++
1059: # Called to establish an encrypted session key with the remote client.
1060: # Note that with secure lond, in most cases this function is never
1061: # invoked. Instead, the secure session key is established either
1062: # via a local file that's locked down tight and only lives for a short
1063: # time, or via an ssl tunnel...and is generated from a bunch-o-random
1064: # bits from /dev/urandom, rather than the predictable pattern used by
1065: # by this sub. This sub is only used in the old-style insecure
1066: # key negotiation.
1067: # Parameters:
1068: # $cmd - the actual keyword that invoked us.
1069: # $tail - the tail of the request that invoked us.
1070: # $replyfd- File descriptor connected to the client
1071: # Implicit Inputs:
1072: # $currenthostid - Global variable that carries the name of the host
1073: # known as.
1074: # $clientname - Global variable that carries the name of the hsot we're connected to.
1075: # Returns:
1076: # 1 - Ok to continue processing.
1077: # 0 - Program should exit.
1078: # Implicit Outputs:
1079: # Reply information is sent to the client.
1080: # $cipher is set with a reference to a new IDEA encryption object.
1081: #
1082: sub establish_key_handler {
1083: my ($cmd, $tail, $replyfd) = @_;
1084:
1085: my $buildkey=time.$$.int(rand 100000);
1086: $buildkey=~tr/1-6/A-F/;
1087: $buildkey=int(rand 100000).$buildkey.int(rand 100000);
1088: my $key=$currenthostid.$clientname;
1089: $key=~tr/a-z/A-Z/;
1090: $key=~tr/G-P/0-9/;
1091: $key=~tr/Q-Z/0-9/;
1092: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
1093: $key=substr($key,0,32);
1094: my $cipherkey=pack("H32",$key);
1095: $cipher=new IDEA $cipherkey;
1096: &Reply($replyfd, \$buildkey, "$cmd:$tail");
1097:
1098: return 1;
1099:
1100: }
1101: ®ister_handler("ekey", \&establish_key_handler, 0, 1,1);
1102:
1103: # Handler for the load command. Returns the current system load average
1104: # to the requestor.
1105: #
1106: # Parameters:
1107: # $cmd - the actual keyword that invoked us.
1108: # $tail - the tail of the request that invoked us.
1109: # $replyfd- File descriptor connected to the client
1110: # Implicit Inputs:
1111: # $currenthostid - Global variable that carries the name of the host
1112: # known as.
1113: # $clientname - Global variable that carries the name of the hsot we're connected to.
1114: # Returns:
1115: # 1 - Ok to continue processing.
1116: # 0 - Program should exit.
1117: # Side effects:
1118: # Reply information is sent to the client.
1119: sub load_handler {
1120: my ($cmd, $tail, $replyfd) = @_;
1121:
1122: # Get the load average from /proc/loadavg and calculate it as a percentage of
1123: # the allowed load limit as set by the perl global variable lonLoadLim
1124:
1125: my $loadavg;
1126: my $loadfile=IO::File->new('/proc/loadavg');
1127:
1128: $loadavg=<$loadfile>;
1129: $loadavg =~ s/\s.*//g; # Extract the first field only.
1130:
1131: my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
1132:
1133: &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1134:
1135: return 1;
1136: }
1137: ®ister_handler("load", \&load_handler, 0, 1, 0);
1138:
1139: #
1140: # Process the userload request. This sub returns to the client the current
1141: # user load average. It can be invoked either by clients or managers.
1142: #
1143: # Parameters:
1144: # $cmd - the actual keyword that invoked us.
1145: # $tail - the tail of the request that invoked us.
1146: # $replyfd- File descriptor connected to the client
1147: # Implicit Inputs:
1148: # $currenthostid - Global variable that carries the name of the host
1149: # known as.
1150: # $clientname - Global variable that carries the name of the hsot we're connected to.
1151: # Returns:
1152: # 1 - Ok to continue processing.
1153: # 0 - Program should exit
1154: # Implicit inputs:
1155: # whatever the userload() function requires.
1156: # Implicit outputs:
1157: # the reply is written to the client.
1158: #
1159: sub user_load_handler {
1160: my ($cmd, $tail, $replyfd) = @_;
1161:
1162: my $userloadpercent=&Apache::lonnet::userload();
1163: &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1164:
1165: return 1;
1166: }
1167: ®ister_handler("userload", \&user_load_handler, 0, 1, 0);
1168:
1169: # Process a request for the authorization type of a user:
1170: # (userauth).
1171: #
1172: # Parameters:
1173: # $cmd - the actual keyword that invoked us.
1174: # $tail - the tail of the request that invoked us.
1175: # $replyfd- File descriptor connected to the client
1176: # Returns:
1177: # 1 - Ok to continue processing.
1178: # 0 - Program should exit
1179: # Implicit outputs:
1180: # The user authorization type is written to the client.
1181: #
1182: sub user_authorization_type {
1183: my ($cmd, $tail, $replyfd) = @_;
1184:
1185: my $userinput = "$cmd:$tail";
1186:
1187: # Pull the domain and username out of the command tail.
1188: # and call get_auth_type to determine the authentication type.
1189:
1190: my ($udom,$uname)=split(/:/,$tail);
1191: my $result = &get_auth_type($udom, $uname);
1192: if($result eq "nouser") {
1193: &Failure( $replyfd, "unknown_user\n", $userinput);
1194: } else {
1195: #
1196: # We only want to pass the second field from get_auth_type
1197: # for ^krb.. otherwise we'll be handing out the encrypted
1198: # password for internals e.g.
1199: #
1200: my ($type,$otherinfo) = split(/:/,$result);
1201: if($type =~ /^krb/) {
1202: $type = $result;
1203: } else {
1204: $type .= ':';
1205: }
1206: &Reply( $replyfd, \$type, $userinput);
1207: }
1208:
1209: return 1;
1210: }
1211: ®ister_handler("currentauth", \&user_authorization_type, 1, 1, 0);
1212:
1213: # Process a request by a manager to push a hosts or domain table
1214: # to us. We pick apart the command and pass it on to the subs
1215: # that already exist to do this.
1216: #
1217: # Parameters:
1218: # $cmd - the actual keyword that invoked us.
1219: # $tail - the tail of the request that invoked us.
1220: # $client - File descriptor connected to the client
1221: # Returns:
1222: # 1 - Ok to continue processing.
1223: # 0 - Program should exit
1224: # Implicit Output:
1225: # a reply is written to the client.
1226: sub push_file_handler {
1227: my ($cmd, $tail, $client) = @_;
1228: &Debug("In push file handler");
1229: my $userinput = "$cmd:$tail";
1230:
1231: # At this time we only know that the IP of our partner is a valid manager
1232: # the code below is a hook to do further authentication (e.g. to resolve
1233: # spoofing).
1234:
1235: my $cert = &GetCertificate($userinput);
1236: if(&ValidManager($cert)) {
1237: &Debug("Valid manager: $client");
1238:
1239: # Now presumably we have the bona fides of both the peer host and the
1240: # process making the request.
1241:
1242: my $reply = &PushFile($userinput);
1243: &Reply($client, \$reply, $userinput);
1244:
1245: } else {
1246: &logthis("push_file_handler $client is not valid");
1247: &Failure( $client, "refused\n", $userinput);
1248: }
1249: return 1;
1250: }
1251: ®ister_handler("pushfile", \&push_file_handler, 1, 0, 1);
1252:
1253: # The du_handler routine should be considered obsolete and is retained
1254: # for communication with legacy servers. Please see the du2_handler.
1255: #
1256: # du - list the disk usage of a directory recursively.
1257: #
1258: # note: stolen code from the ls file handler
1259: # under construction by Rick Banghart
1260: # .
1261: # Parameters:
1262: # $cmd - The command that dispatched us (du).
1263: # $ududir - The directory path to list... I'm not sure what this
1264: # is relative as things like ls:. return e.g.
1265: # no_such_dir.
1266: # $client - Socket open on the client.
1267: # Returns:
1268: # 1 - indicating that the daemon should not disconnect.
1269: # Side Effects:
1270: # The reply is written to $client.
1271: #
1272: sub du_handler {
1273: my ($cmd, $ududir, $client) = @_;
1274: ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1275: my $userinput = "$cmd:$ududir";
1276:
1277: if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
1278: &Failure($client,"refused\n","$cmd:$ududir");
1279: return 1;
1280: }
1281: # Since $ududir could have some nasties in it,
1282: # we will require that ududir is a valid
1283: # directory. Just in case someone tries to
1284: # slip us a line like .;(cd /home/httpd rm -rf*)
1285: # etc.
1286: #
1287: if (-d $ududir) {
1288: my $total_size=0;
1289: my $code=sub {
1290: if ($_=~/\.\d+\./) { return;}
1291: if ($_=~/\.meta$/) { return;}
1292: if (-d $_) { return;}
1293: $total_size+=(stat($_))[7];
1294: };
1295: chdir($ududir);
1296: find($code,$ududir);
1297: $total_size=int($total_size/1024);
1298: &Reply($client,\$total_size,"$cmd:$ududir");
1299: } else {
1300: &Failure($client, "bad_directory:$ududir\n","$cmd:$ududir");
1301: }
1302: return 1;
1303: }
1304: ®ister_handler("du", \&du_handler, 0, 1, 0);
1305:
1306: # Please also see the du_handler, which is obsoleted by du2.
1307: # du2_handler differs from du_handler in that required path to directory
1308: # provided by &propath() is prepended in the handler instead of on the
1309: # client side.
1310: #
1311: # du2 - list the disk usage of a directory recursively.
1312: #
1313: # Parameters:
1314: # $cmd - The command that dispatched us (du).
1315: # $tail - The tail of the request that invoked us.
1316: # $tail is a : separated list of the following:
1317: # - $ududir - directory path to list (before prepending)
1318: # - $getpropath = 1 if &propath() should prepend
1319: # - $uname - username to use for &propath or user dir
1320: # - $udom - domain to use for &propath or user dir
1321: # All are escaped.
1322: # $client - Socket open on the client.
1323: # Returns:
1324: # 1 - indicating that the daemon should not disconnect.
1325: # Side Effects:
1326: # The reply is written to $client.
1327: #
1328:
1329: sub du2_handler {
1330: my ($cmd, $tail, $client) = @_;
1331: my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
1332: my $userinput = "$cmd:$tail";
1333: if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
1334: &Failure($client,"refused\n","$cmd:$tail");
1335: return 1;
1336: }
1337: if ($getpropath) {
1338: if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
1339: $ududir = &propath($udom,$uname).'/'.$ududir;
1340: } else {
1341: &Failure($client,"refused\n","$cmd:$tail");
1342: return 1;
1343: }
1344: }
1345: # Since $ududir could have some nasties in it,
1346: # we will require that ududir is a valid
1347: # directory. Just in case someone tries to
1348: # slip us a line like .;(cd /home/httpd rm -rf*)
1349: # etc.
1350: #
1351: if (-d $ududir) {
1352: my $total_size=0;
1353: my $code=sub {
1354: if ($_=~/\.\d+\./) { return;}
1355: if ($_=~/\.meta$/) { return;}
1356: if (-d $_) { return;}
1357: $total_size+=(stat($_))[7];
1358: };
1359: chdir($ududir);
1360: find($code,$ududir);
1361: $total_size=int($total_size/1024);
1362: &Reply($client,\$total_size,"$cmd:$ududir");
1363: } else {
1364: &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
1365: }
1366: return 1;
1367: }
1368: ®ister_handler("du2", \&du2_handler, 0, 1, 0);
1369:
1370: #
1371: # The ls_handler routine should be considered obsolete and is retained
1372: # for communication with legacy servers. Please see the ls3_handler.
1373: #
1374: # ls - list the contents of a directory. For each file in the
1375: # selected directory the filename followed by the full output of
1376: # the stat function is returned. The returned info for each
1377: # file are separated by ':'. The stat fields are separated by &'s.
1378: # Parameters:
1379: # $cmd - The command that dispatched us (ls).
1380: # $ulsdir - The directory path to list... I'm not sure what this
1381: # is relative as things like ls:. return e.g.
1382: # no_such_dir.
1383: # $client - Socket open on the client.
1384: # Returns:
1385: # 1 - indicating that the daemon should not disconnect.
1386: # Side Effects:
1387: # The reply is written to $client.
1388: #
1389: sub ls_handler {
1390: # obsoleted by ls2_handler
1391: my ($cmd, $ulsdir, $client) = @_;
1392:
1393: my $userinput = "$cmd:$ulsdir";
1394:
1395: my $obs;
1396: my $rights;
1397: my $ulsout='';
1398: my $ulsfn;
1399: if (-e $ulsdir) {
1400: if(-d $ulsdir) {
1401: if (opendir(LSDIR,$ulsdir)) {
1402: while ($ulsfn=readdir(LSDIR)) {
1403: undef($obs);
1404: undef($rights);
1405: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1406: #We do some obsolete checking here
1407: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1408: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1409: my @obsolete=<FILE>;
1410: foreach my $obsolete (@obsolete) {
1411: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1412: if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
1413: }
1414: }
1415: $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
1416: if($obs eq '1') { $ulsout.="&1"; }
1417: else { $ulsout.="&0"; }
1418: if($rights eq '1') { $ulsout.="&1:"; }
1419: else { $ulsout.="&0:"; }
1420: }
1421: closedir(LSDIR);
1422: }
1423: } else {
1424: my @ulsstats=stat($ulsdir);
1425: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1426: }
1427: } else {
1428: $ulsout='no_such_dir';
1429: }
1430: if ($ulsout eq '') { $ulsout='empty'; }
1431: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1432:
1433: return 1;
1434:
1435: }
1436: ®ister_handler("ls", \&ls_handler, 0, 1, 0);
1437:
1438: # The ls2_handler routine should be considered obsolete and is retained
1439: # for communication with legacy servers. Please see the ls3_handler.
1440: # Please also see the ls_handler, which was itself obsoleted by ls2.
1441: # ls2_handler differs from ls_handler in that it escapes its return
1442: # values before concatenating them together with ':'s.
1443: #
1444: # ls2 - list the contents of a directory. For each file in the
1445: # selected directory the filename followed by the full output of
1446: # the stat function is returned. The returned info for each
1447: # file are separated by ':'. The stat fields are separated by &'s.
1448: # Parameters:
1449: # $cmd - The command that dispatched us (ls).
1450: # $ulsdir - The directory path to list... I'm not sure what this
1451: # is relative as things like ls:. return e.g.
1452: # no_such_dir.
1453: # $client - Socket open on the client.
1454: # Returns:
1455: # 1 - indicating that the daemon should not disconnect.
1456: # Side Effects:
1457: # The reply is written to $client.
1458: #
1459: sub ls2_handler {
1460: my ($cmd, $ulsdir, $client) = @_;
1461:
1462: my $userinput = "$cmd:$ulsdir";
1463:
1464: my $obs;
1465: my $rights;
1466: my $ulsout='';
1467: my $ulsfn;
1468: if (-e $ulsdir) {
1469: if(-d $ulsdir) {
1470: if (opendir(LSDIR,$ulsdir)) {
1471: while ($ulsfn=readdir(LSDIR)) {
1472: undef($obs);
1473: undef($rights);
1474: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1475: #We do some obsolete checking here
1476: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1477: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1478: my @obsolete=<FILE>;
1479: foreach my $obsolete (@obsolete) {
1480: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1481: if($obsolete =~ m|(<copyright>)(default)|) {
1482: $rights = 1;
1483: }
1484: }
1485: }
1486: my $tmp = $ulsfn.'&'.join('&',@ulsstats);
1487: if ($obs eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1488: if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1489: $ulsout.= &escape($tmp).':';
1490: }
1491: closedir(LSDIR);
1492: }
1493: } else {
1494: my @ulsstats=stat($ulsdir);
1495: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1496: }
1497: } else {
1498: $ulsout='no_such_dir';
1499: }
1500: if ($ulsout eq '') { $ulsout='empty'; }
1501: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1502: return 1;
1503: }
1504: ®ister_handler("ls2", \&ls2_handler, 0, 1, 0);
1505: #
1506: # ls3 - list the contents of a directory. For each file in the
1507: # selected directory the filename followed by the full output of
1508: # the stat function is returned. The returned info for each
1509: # file are separated by ':'. The stat fields are separated by &'s.
1510: # Parameters:
1511: # $cmd - The command that dispatched us (ls).
1512: # $tail - The tail of the request that invoked us.
1513: # $tail is a : separated list of the following:
1514: # - $ulsdir - directory path to list (before prepending)
1515: # - $getpropath = 1 if &propath() should prepend
1516: # - $getuserdir = 1 if path to user dir in lonUsers should
1517: # prepend
1518: # - $alternate_root - path to prepend
1519: # - $uname - username to use for &propath or user dir
1520: # - $udom - domain to use for &propath or user dir
1521: # All of these except $getpropath and &getuserdir are escaped.
1522: # no_such_dir.
1523: # $client - Socket open on the client.
1524: # Returns:
1525: # 1 - indicating that the daemon should not disconnect.
1526: # Side Effects:
1527: # The reply is written to $client.
1528: #
1529:
1530: sub ls3_handler {
1531: my ($cmd, $tail, $client) = @_;
1532: my $userinput = "$cmd:$tail";
1533: my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
1534: split(/:/,$tail);
1535: if (defined($ulsdir)) {
1536: $ulsdir = &unescape($ulsdir);
1537: }
1538: if (defined($alternate_root)) {
1539: $alternate_root = &unescape($alternate_root);
1540: }
1541: if (defined($uname)) {
1542: $uname = &unescape($uname);
1543: }
1544: if (defined($udom)) {
1545: $udom = &unescape($udom);
1546: }
1547:
1548: my $dir_root = $perlvar{'lonDocRoot'};
1549: if ($getpropath) {
1550: if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
1551: $dir_root = &propath($udom,$uname);
1552: $dir_root =~ s/\/$//;
1553: } else {
1554: &Failure($client,"refused\n","$cmd:$tail");
1555: return 1;
1556: }
1557: } elsif ($getuserdir) {
1558: if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
1559: my $subdir=$uname.'__';
1560: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
1561: $dir_root = $Apache::lonnet::perlvar{'lonUsersDir'}
1562: ."/$udom/$subdir/$uname";
1563: } else {
1564: &Failure($client,"refused\n","$cmd:$tail");
1565: return 1;
1566: }
1567: } elsif ($alternate_root ne '') {
1568: $dir_root = $alternate_root;
1569: }
1570: if (($dir_root ne '') && ($dir_root ne '/')) {
1571: if ($ulsdir =~ /^\//) {
1572: $ulsdir = $dir_root.$ulsdir;
1573: } else {
1574: $ulsdir = $dir_root.'/'.$ulsdir;
1575: }
1576: }
1577: my $obs;
1578: my $rights;
1579: my $ulsout='';
1580: my $ulsfn;
1581: if (-e $ulsdir) {
1582: if(-d $ulsdir) {
1583: if (opendir(LSDIR,$ulsdir)) {
1584: while ($ulsfn=readdir(LSDIR)) {
1585: undef($obs);
1586: undef($rights);
1587: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1588: #We do some obsolete checking here
1589: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1590: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1591: my @obsolete=<FILE>;
1592: foreach my $obsolete (@obsolete) {
1593: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1594: if($obsolete =~ m|(<copyright>)(default)|) {
1595: $rights = 1;
1596: }
1597: }
1598: }
1599: my $tmp = $ulsfn.'&'.join('&',@ulsstats);
1600: if ($obs eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1601: if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1602: $ulsout.= &escape($tmp).':';
1603: }
1604: closedir(LSDIR);
1605: }
1606: } else {
1607: my @ulsstats=stat($ulsdir);
1608: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1609: }
1610: } else {
1611: $ulsout='no_such_dir';
1612: }
1613: if ($ulsout eq '') { $ulsout='empty'; }
1614: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1615: return 1;
1616: }
1617: ®ister_handler("ls3", \&ls3_handler, 0, 1, 0);
1618:
1619: sub server_timezone_handler {
1620: my ($cmd,$tail,$client) = @_;
1621: my $userinput = "$cmd:$tail";
1622: my $timezone;
1623: my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
1624: my $tzfile = '/etc/timezone'; # Debian/Ubuntu
1625: if (-e $clockfile) {
1626: if (open(my $fh,"<$clockfile")) {
1627: while (<$fh>) {
1628: next if (/^[\#\s]/);
1629: if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
1630: $timezone = $1;
1631: last;
1632: }
1633: }
1634: close($fh);
1635: }
1636: } elsif (-e $tzfile) {
1637: if (open(my $fh,"<$tzfile")) {
1638: $timezone = <$fh>;
1639: close($fh);
1640: chomp($timezone);
1641: if ($timezone =~ m{^Etc/(\w+)$}) {
1642: $timezone = $1;
1643: }
1644: }
1645: }
1646: &Reply($client,\$timezone,$userinput); # This supports debug logging.
1647: return 1;
1648: }
1649: ®ister_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
1650:
1651: sub server_loncaparev_handler {
1652: my ($cmd,$tail,$client) = @_;
1653: my $userinput = "$cmd:$tail";
1654: &Reply($client,\$perlvar{'lonVersion'},$userinput);
1655: return 1;
1656: }
1657: ®ister_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
1658:
1659: # Process a reinit request. Reinit requests that either
1660: # lonc or lond be reinitialized so that an updated
1661: # host.tab or domain.tab can be processed.
1662: #
1663: # Parameters:
1664: # $cmd - the actual keyword that invoked us.
1665: # $tail - the tail of the request that invoked us.
1666: # $client - File descriptor connected to the client
1667: # Returns:
1668: # 1 - Ok to continue processing.
1669: # 0 - Program should exit
1670: # Implicit output:
1671: # a reply is sent to the client.
1672: #
1673: sub reinit_process_handler {
1674: my ($cmd, $tail, $client) = @_;
1675:
1676: my $userinput = "$cmd:$tail";
1677:
1678: my $cert = &GetCertificate($userinput);
1679: if(&ValidManager($cert)) {
1680: chomp($userinput);
1681: my $reply = &ReinitProcess($userinput);
1682: &Reply( $client, \$reply, $userinput);
1683: } else {
1684: &Failure( $client, "refused\n", $userinput);
1685: }
1686: return 1;
1687: }
1688: ®ister_handler("reinit", \&reinit_process_handler, 1, 0, 1);
1689:
1690: # Process the editing script for a table edit operation.
1691: # the editing operation must be encrypted and requested by
1692: # a manager host.
1693: #
1694: # Parameters:
1695: # $cmd - the actual keyword that invoked us.
1696: # $tail - the tail of the request that invoked us.
1697: # $client - File descriptor connected to the client
1698: # Returns:
1699: # 1 - Ok to continue processing.
1700: # 0 - Program should exit
1701: # Implicit output:
1702: # a reply is sent to the client.
1703: #
1704: sub edit_table_handler {
1705: my ($command, $tail, $client) = @_;
1706:
1707: my $userinput = "$command:$tail";
1708:
1709: my $cert = &GetCertificate($userinput);
1710: if(&ValidManager($cert)) {
1711: my($filetype, $script) = split(/:/, $tail);
1712: if (($filetype eq "hosts") ||
1713: ($filetype eq "domain")) {
1714: if($script ne "") {
1715: &Reply($client, # BUGBUG - EditFile
1716: &EditFile($userinput), # could fail.
1717: $userinput);
1718: } else {
1719: &Failure($client,"refused\n",$userinput);
1720: }
1721: } else {
1722: &Failure($client,"refused\n",$userinput);
1723: }
1724: } else {
1725: &Failure($client,"refused\n",$userinput);
1726: }
1727: return 1;
1728: }
1729: ®ister_handler("edit", \&edit_table_handler, 1, 0, 1);
1730:
1731: #
1732: # Authenticate a user against the LonCAPA authentication
1733: # database. Note that there are several authentication
1734: # possibilities:
1735: # - unix - The user can be authenticated against the unix
1736: # password file.
1737: # - internal - The user can be authenticated against a purely
1738: # internal per user password file.
1739: # - kerberos - The user can be authenticated against either a kerb4 or kerb5
1740: # ticket granting authority.
1741: # - user - The person tailoring LonCAPA can supply a user authentication
1742: # mechanism that is per system.
1743: #
1744: # Parameters:
1745: # $cmd - The command that got us here.
1746: # $tail - Tail of the command (remaining parameters).
1747: # $client - File descriptor connected to client.
1748: # Returns
1749: # 0 - Requested to exit, caller should shut down.
1750: # 1 - Continue processing.
1751: # Implicit inputs:
1752: # The authentication systems describe above have their own forms of implicit
1753: # input into the authentication process that are described above.
1754: #
1755: sub authenticate_handler {
1756: my ($cmd, $tail, $client) = @_;
1757:
1758:
1759: # Regenerate the full input line
1760:
1761: my $userinput = $cmd.":".$tail;
1762:
1763: # udom - User's domain.
1764: # uname - Username.
1765: # upass - User's password.
1766: # checkdefauth - Pass to validate_user() to try authentication
1767: # with default auth type(s) if no user account.
1768:
1769: my ($udom, $uname, $upass, $checkdefauth)=split(/:/,$tail);
1770: &Debug(" Authenticate domain = $udom, user = $uname, password = $upass, checkdefauth = $checkdefauth");
1771: chomp($upass);
1772: $upass=&unescape($upass);
1773:
1774: my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1775: if($pwdcorrect) {
1776: &Reply( $client, "authorized\n", $userinput);
1777: #
1778: # Bad credentials: Failed to authorize
1779: #
1780: } else {
1781: &Failure( $client, "non_authorized\n", $userinput);
1782: }
1783:
1784: return 1;
1785: }
1786: ®ister_handler("auth", \&authenticate_handler, 1, 1, 0);
1787:
1788: #
1789: # Change a user's password. Note that this function is complicated by
1790: # the fact that a user may be authenticated in more than one way:
1791: # At present, we are not able to change the password for all types of
1792: # authentication methods. Only for:
1793: # unix - unix password or shadow passoword style authentication.
1794: # local - Locally written authentication mechanism.
1795: # For now, kerb4 and kerb5 password changes are not supported and result
1796: # in an error.
1797: # FUTURE WORK:
1798: # Support kerberos passwd changes?
1799: # Parameters:
1800: # $cmd - The command that got us here.
1801: # $tail - Tail of the command (remaining parameters).
1802: # $client - File descriptor connected to client.
1803: # Returns
1804: # 0 - Requested to exit, caller should shut down.
1805: # 1 - Continue processing.
1806: # Implicit inputs:
1807: # The authentication systems describe above have their own forms of implicit
1808: # input into the authentication process that are described above.
1809: sub change_password_handler {
1810: my ($cmd, $tail, $client) = @_;
1811:
1812: my $userinput = $cmd.":".$tail; # Reconstruct client's string.
1813:
1814: #
1815: # udom - user's domain.
1816: # uname - Username.
1817: # upass - Current password.
1818: # npass - New password.
1819: # context - Context in which this was called
1820: # (preferences or reset_by_email).
1821: # lonhost - HostID of server where request originated
1822:
1823: my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1824:
1825: $upass=&unescape($upass);
1826: $npass=&unescape($npass);
1827: &Debug("Trying to change password for $uname");
1828:
1829: # First require that the user can be authenticated with their
1830: # old password unless context was 'reset_by_email':
1831:
1832: my ($validated,$failure);
1833: if ($context eq 'reset_by_email') {
1834: if ($lonhost eq '') {
1835: $failure = 'invalid_client';
1836: } else {
1837: $validated = 1;
1838: }
1839: } else {
1840: $validated = &validate_user($udom, $uname, $upass);
1841: }
1842: if($validated) {
1843: my $realpasswd = &get_auth_type($udom, $uname); # Defined since authd.
1844:
1845: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1846: if ($howpwd eq 'internal') {
1847: &Debug("internal auth");
1848: my $salt=time;
1849: $salt=substr($salt,6,2);
1850: my $ncpass=crypt($npass,$salt);
1851: if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1852: my $msg="Result of password change for $uname: pwchange_success";
1853: if ($lonhost) {
1854: $msg .= " - request originated from: $lonhost";
1855: }
1856: &logthis($msg);
1857: &Reply($client, "ok\n", $userinput);
1858: } else {
1859: &logthis("Unable to open $uname passwd "
1860: ."to change password");
1861: &Failure( $client, "non_authorized\n",$userinput);
1862: }
1863: } elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1864: my $result = &change_unix_password($uname, $npass);
1865: &logthis("Result of password change for $uname: ".
1866: $result);
1867: &Reply($client, \$result, $userinput);
1868: } else {
1869: # this just means that the current password mode is not
1870: # one we know how to change (e.g the kerberos auth modes or
1871: # locally written auth handler).
1872: #
1873: &Failure( $client, "auth_mode_error\n", $userinput);
1874: }
1875:
1876: } else {
1877: if ($failure eq '') {
1878: $failure = 'non_authorized';
1879: }
1880: &Failure( $client, "$failure\n", $userinput);
1881: }
1882:
1883: return 1;
1884: }
1885: ®ister_handler("passwd", \&change_password_handler, 1, 1, 0);
1886:
1887: #
1888: # Create a new user. User in this case means a lon-capa user.
1889: # The user must either already exist in some authentication realm
1890: # like kerberos or the /etc/passwd. If not, a user completely local to
1891: # this loncapa system is created.
1892: #
1893: # Parameters:
1894: # $cmd - The command that got us here.
1895: # $tail - Tail of the command (remaining parameters).
1896: # $client - File descriptor connected to client.
1897: # Returns
1898: # 0 - Requested to exit, caller should shut down.
1899: # 1 - Continue processing.
1900: # Implicit inputs:
1901: # The authentication systems describe above have their own forms of implicit
1902: # input into the authentication process that are described above.
1903: sub add_user_handler {
1904:
1905: my ($cmd, $tail, $client) = @_;
1906:
1907:
1908: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
1909: my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
1910:
1911: &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
1912:
1913:
1914: if($udom eq $currentdomainid) { # Reject new users for other domains...
1915:
1916: my $oldumask=umask(0077);
1917: chomp($npass);
1918: $npass=&unescape($npass);
1919: my $passfilename = &password_path($udom, $uname);
1920: &Debug("Password file created will be:".$passfilename);
1921: if (-e $passfilename) {
1922: &Failure( $client, "already_exists\n", $userinput);
1923: } else {
1924: my $fperror='';
1925: if (!&mkpath($passfilename)) {
1926: $fperror="error: ".($!+0)." mkdir failed while attempting "
1927: ."makeuser";
1928: }
1929: unless ($fperror) {
1930: my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
1931: &Reply($client,\$result, $userinput); #BUGBUG - could be fail
1932: } else {
1933: &Failure($client, \$fperror, $userinput);
1934: }
1935: }
1936: umask($oldumask);
1937: } else {
1938: &Failure($client, "not_right_domain\n",
1939: $userinput); # Even if we are multihomed.
1940:
1941: }
1942: return 1;
1943:
1944: }
1945: ®ister_handler("makeuser", \&add_user_handler, 1, 1, 0);
1946:
1947: #
1948: # Change the authentication method of a user. Note that this may
1949: # also implicitly change the user's password if, for example, the user is
1950: # joining an existing authentication realm. Known authentication realms at
1951: # this time are:
1952: # internal - Purely internal password file (only loncapa knows this user)
1953: # local - Institutionally written authentication module.
1954: # unix - Unix user (/etc/passwd with or without /etc/shadow).
1955: # kerb4 - kerberos version 4
1956: # kerb5 - kerberos version 5
1957: #
1958: # Parameters:
1959: # $cmd - The command that got us here.
1960: # $tail - Tail of the command (remaining parameters).
1961: # $client - File descriptor connected to client.
1962: # Returns
1963: # 0 - Requested to exit, caller should shut down.
1964: # 1 - Continue processing.
1965: # Implicit inputs:
1966: # The authentication systems describe above have their own forms of implicit
1967: # input into the authentication process that are described above.
1968: # NOTE:
1969: # This is also used to change the authentication credential values (e.g. passwd).
1970: #
1971: #
1972: sub change_authentication_handler {
1973:
1974: my ($cmd, $tail, $client) = @_;
1975:
1976: my $userinput = "$cmd:$tail"; # Reconstruct user input.
1977:
1978: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
1979: &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
1980: if ($udom ne $currentdomainid) {
1981: &Failure( $client, "not_right_domain\n", $client);
1982: } else {
1983:
1984: chomp($npass);
1985:
1986: $npass=&unescape($npass);
1987: my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1988: my $passfilename = &password_path($udom, $uname);
1989: if ($passfilename) { # Not allowed to create a new user!!
1990: # If just changing the unix passwd. need to arrange to run
1991: # passwd since otherwise make_passwd_file will run
1992: # lcuseradd which fails if an account already exists
1993: # (to prevent an unscrupulous LONCAPA admin from stealing
1994: # an existing account by overwriting it as a LonCAPA account).
1995:
1996: if(($oldauth =~/^unix/) && ($umode eq "unix")) {
1997: my $result = &change_unix_password($uname, $npass);
1998: &logthis("Result of password change for $uname: ".$result);
1999: if ($result eq "ok") {
2000: &Reply($client, \$result);
2001: } else {
2002: &Failure($client, \$result);
2003: }
2004: } else {
2005: my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
2006: #
2007: # If the current auth mode is internal, and the old auth mode was
2008: # unix, or krb*, and the user is an author for this domain,
2009: # re-run manage_permissions for that role in order to be able
2010: # to take ownership of the construction space back to www:www
2011: #
2012:
2013:
2014: if( (($oldauth =~ /^unix/) && ($umode eq "internal")) ||
2015: (($oldauth =~ /^internal/) && ($umode eq "unix")) ) {
2016: if(&is_author($udom, $uname)) {
2017: &Debug(" Need to manage author permissions...");
2018: &manage_permissions("/$udom/_au", $udom, $uname, "$umode:");
2019: }
2020: }
2021: &Reply($client, \$result, $userinput);
2022: }
2023:
2024:
2025: } else {
2026: &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
2027: }
2028: }
2029: return 1;
2030: }
2031: ®ister_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
2032:
2033: #
2034: # Determines if this is the home server for a user. The home server
2035: # for a user will have his/her lon-capa passwd file. Therefore all we need
2036: # to do is determine if this file exists.
2037: #
2038: # Parameters:
2039: # $cmd - The command that got us here.
2040: # $tail - Tail of the command (remaining parameters).
2041: # $client - File descriptor connected to client.
2042: # Returns
2043: # 0 - Requested to exit, caller should shut down.
2044: # 1 - Continue processing.
2045: # Implicit inputs:
2046: # The authentication systems describe above have their own forms of implicit
2047: # input into the authentication process that are described above.
2048: #
2049: sub is_home_handler {
2050: my ($cmd, $tail, $client) = @_;
2051:
2052: my $userinput = "$cmd:$tail";
2053:
2054: my ($udom,$uname)=split(/:/,$tail);
2055: chomp($uname);
2056: my $passfile = &password_filename($udom, $uname);
2057: if($passfile) {
2058: &Reply( $client, "found\n", $userinput);
2059: } else {
2060: &Failure($client, "not_found\n", $userinput);
2061: }
2062: return 1;
2063: }
2064: ®ister_handler("home", \&is_home_handler, 0,1,0);
2065:
2066: #
2067: # Process an update request for a resource.
2068: # A resource has been modified that we hold a subscription to.
2069: # If the resource is not local, then we must update, or at least invalidate our
2070: # cached copy of the resource.
2071: # Parameters:
2072: # $cmd - The command that got us here.
2073: # $tail - Tail of the command (remaining parameters).
2074: # $client - File descriptor connected to client.
2075: # Returns
2076: # 0 - Requested to exit, caller should shut down.
2077: # 1 - Continue processing.
2078: # Implicit inputs:
2079: # The authentication systems describe above have their own forms of implicit
2080: # input into the authentication process that are described above.
2081: #
2082: sub update_resource_handler {
2083:
2084: my ($cmd, $tail, $client) = @_;
2085:
2086: my $userinput = "$cmd:$tail";
2087:
2088: my $fname= $tail; # This allows interactive testing
2089:
2090:
2091: my $ownership=ishome($fname);
2092: if ($ownership eq 'not_owner') {
2093: if (-e $fname) {
2094: # Delete preview file, if exists
2095: unlink("$fname.tmp");
2096: # Get usage stats
2097: my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
2098: $atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
2099: my $now=time;
2100: my $since=$now-$atime;
2101: # If the file has not been used within lonExpire seconds,
2102: # unsubscribe from it and delete local copy
2103: if ($since>$perlvar{'lonExpire'}) {
2104: my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
2105: &devalidate_meta_cache($fname);
2106: unlink("$fname");
2107: unlink("$fname.meta");
2108: } else {
2109: # Yes, this is in active use. Get a fresh copy. Since it might be in
2110: # very active use and huge (like a movie), copy it to "in.transfer" filename first.
2111: my $transname="$fname.in.transfer";
2112: my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
2113: my $response;
2114: alarm(120);
2115: {
2116: my $ua=new LWP::UserAgent;
2117: my $request=new HTTP::Request('GET',"$remoteurl");
2118: $response=$ua->request($request,$transname);
2119: }
2120: alarm(0);
2121: if ($response->is_error()) {
2122: unlink($transname);
2123: my $message=$response->status_line;
2124: &logthis("LWP GET: $message for $fname ($remoteurl)");
2125: } else {
2126: if ($remoteurl!~/\.meta$/) {
2127: alarm(120);
2128: {
2129: my $ua=new LWP::UserAgent;
2130: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2131: my $mresponse=$ua->request($mrequest,$fname.'.meta');
2132: if ($mresponse->is_error()) {
2133: unlink($fname.'.meta');
2134: }
2135: }
2136: alarm(0);
2137: }
2138: # we successfully transfered, copy file over to real name
2139: rename($transname,$fname);
2140: &devalidate_meta_cache($fname);
2141: }
2142: }
2143: &Reply( $client, "ok\n", $userinput);
2144: } else {
2145: &Failure($client, "not_found\n", $userinput);
2146: }
2147: } else {
2148: &Failure($client, "rejected\n", $userinput);
2149: }
2150: return 1;
2151: }
2152: ®ister_handler("update", \&update_resource_handler, 0 ,1, 0);
2153:
2154: sub devalidate_meta_cache {
2155: my ($url) = @_;
2156: use Cache::Memcached;
2157: my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
2158: $url = &Apache::lonnet::declutter($url);
2159: $url =~ s-\.meta$--;
2160: my $id = &escape('meta:'.$url);
2161: $memcache->delete($id);
2162: }
2163:
2164: #
2165: # Fetch a user file from a remote server to the user's home directory
2166: # userfiles subdir.
2167: # Parameters:
2168: # $cmd - The command that got us here.
2169: # $tail - Tail of the command (remaining parameters).
2170: # $client - File descriptor connected to client.
2171: # Returns
2172: # 0 - Requested to exit, caller should shut down.
2173: # 1 - Continue processing.
2174: #
2175: sub fetch_user_file_handler {
2176:
2177: my ($cmd, $tail, $client) = @_;
2178:
2179: my $userinput = "$cmd:$tail";
2180: my $fname = $tail;
2181: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2182: my $udir=&propath($udom,$uname).'/userfiles';
2183: unless (-e $udir) {
2184: mkdir($udir,0770);
2185: }
2186: Debug("fetch user file for $fname");
2187: if (-e $udir) {
2188: $ufile=~s/^[\.\~]+//;
2189:
2190: # IF necessary, create the path right down to the file.
2191: # Note that any regular files in the way of this path are
2192: # wiped out to deal with some earlier folly of mine.
2193:
2194: if (!&mkpath($udir.'/'.$ufile)) {
2195: &Failure($client, "unable_to_create\n", $userinput);
2196: }
2197:
2198: my $destname=$udir.'/'.$ufile;
2199: my $transname=$udir.'/'.$ufile.'.in.transit';
2200: my $clientprotocol=$Apache::lonnet::protocol{$clientname};
2201: $clientprotocol = 'http' if ($clientprotocol ne 'https');
2202: my $remoteurl=$clientprotocol.'://'.$clientip.'/userfiles/'.$fname;
2203: my $response;
2204: Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
2205: alarm(120);
2206: {
2207: my $ua=new LWP::UserAgent;
2208: my $request=new HTTP::Request('GET',"$remoteurl");
2209: $response=$ua->request($request,$transname);
2210: }
2211: alarm(0);
2212: if ($response->is_error()) {
2213: unlink($transname);
2214: my $message=$response->status_line;
2215: &logthis("LWP GET: $message for $fname ($remoteurl)");
2216: &Failure($client, "failed\n", $userinput);
2217: } else {
2218: Debug("Renaming $transname to $destname");
2219: if (!rename($transname,$destname)) {
2220: &logthis("Unable to move $transname to $destname");
2221: unlink($transname);
2222: &Failure($client, "failed\n", $userinput);
2223: } else {
2224: &Reply($client, "ok\n", $userinput);
2225: }
2226: }
2227: } else {
2228: &Failure($client, "not_home\n", $userinput);
2229: }
2230: return 1;
2231: }
2232: ®ister_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
2233:
2234: #
2235: # Remove a file from a user's home directory userfiles subdirectory.
2236: # Parameters:
2237: # cmd - the Lond request keyword that got us here.
2238: # tail - the part of the command past the keyword.
2239: # client- File descriptor connected with the client.
2240: #
2241: # Returns:
2242: # 1 - Continue processing.
2243: sub remove_user_file_handler {
2244: my ($cmd, $tail, $client) = @_;
2245:
2246: my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2247:
2248: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2249: if ($ufile =~m|/\.\./|) {
2250: # any files paths with /../ in them refuse
2251: # to deal with
2252: &Failure($client, "refused\n", "$cmd:$tail");
2253: } else {
2254: my $udir = &propath($udom,$uname);
2255: if (-e $udir) {
2256: my $file=$udir.'/userfiles/'.$ufile;
2257: if (-e $file) {
2258: #
2259: # If the file is a regular file unlink is fine...
2260: # However it's possible the client wants a dir.
2261: # removed, in which case rmdir is more approprate:
2262: #
2263: if (-f $file){
2264: unlink($file);
2265: } elsif(-d $file) {
2266: rmdir($file);
2267: }
2268: if (-e $file) {
2269: # File is still there after we deleted it ?!?
2270:
2271: &Failure($client, "failed\n", "$cmd:$tail");
2272: } else {
2273: &Reply($client, "ok\n", "$cmd:$tail");
2274: }
2275: } else {
2276: &Failure($client, "not_found\n", "$cmd:$tail");
2277: }
2278: } else {
2279: &Failure($client, "not_home\n", "$cmd:$tail");
2280: }
2281: }
2282: return 1;
2283: }
2284: ®ister_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
2285:
2286: #
2287: # make a directory in a user's home directory userfiles subdirectory.
2288: # Parameters:
2289: # cmd - the Lond request keyword that got us here.
2290: # tail - the part of the command past the keyword.
2291: # client- File descriptor connected with the client.
2292: #
2293: # Returns:
2294: # 1 - Continue processing.
2295: sub mkdir_user_file_handler {
2296: my ($cmd, $tail, $client) = @_;
2297:
2298: my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2299: $dir=&unescape($dir);
2300: my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
2301: if ($ufile =~m|/\.\./|) {
2302: # any files paths with /../ in them refuse
2303: # to deal with
2304: &Failure($client, "refused\n", "$cmd:$tail");
2305: } else {
2306: my $udir = &propath($udom,$uname);
2307: if (-e $udir) {
2308: my $newdir=$udir.'/userfiles/'.$ufile.'/';
2309: if (!&mkpath($newdir)) {
2310: &Failure($client, "failed\n", "$cmd:$tail");
2311: }
2312: &Reply($client, "ok\n", "$cmd:$tail");
2313: } else {
2314: &Failure($client, "not_home\n", "$cmd:$tail");
2315: }
2316: }
2317: return 1;
2318: }
2319: ®ister_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
2320:
2321: #
2322: # rename a file in a user's home directory userfiles subdirectory.
2323: # Parameters:
2324: # cmd - the Lond request keyword that got us here.
2325: # tail - the part of the command past the keyword.
2326: # client- File descriptor connected with the client.
2327: #
2328: # Returns:
2329: # 1 - Continue processing.
2330: sub rename_user_file_handler {
2331: my ($cmd, $tail, $client) = @_;
2332:
2333: my ($udom,$uname,$old,$new) = split(/:/, $tail);
2334: $old=&unescape($old);
2335: $new=&unescape($new);
2336: if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
2337: # any files paths with /../ in them refuse to deal with
2338: &Failure($client, "refused\n", "$cmd:$tail");
2339: } else {
2340: my $udir = &propath($udom,$uname);
2341: if (-e $udir) {
2342: my $oldfile=$udir.'/userfiles/'.$old;
2343: my $newfile=$udir.'/userfiles/'.$new;
2344: if (-e $newfile) {
2345: &Failure($client, "exists\n", "$cmd:$tail");
2346: } elsif (! -e $oldfile) {
2347: &Failure($client, "not_found\n", "$cmd:$tail");
2348: } else {
2349: if (!rename($oldfile,$newfile)) {
2350: &Failure($client, "failed\n", "$cmd:$tail");
2351: } else {
2352: &Reply($client, "ok\n", "$cmd:$tail");
2353: }
2354: }
2355: } else {
2356: &Failure($client, "not_home\n", "$cmd:$tail");
2357: }
2358: }
2359: return 1;
2360: }
2361: ®ister_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
2362:
2363: #
2364: # Checks if the specified user has an active session on the server
2365: # return ok if so, not_found if not
2366: #
2367: # Parameters:
2368: # cmd - The request keyword that dispatched to tus.
2369: # tail - The tail of the request (colon separated parameters).
2370: # client - Filehandle open on the client.
2371: # Return:
2372: # 1.
2373: sub user_has_session_handler {
2374: my ($cmd, $tail, $client) = @_;
2375:
2376: my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
2377:
2378: &logthis("Looking for $udom $uname");
2379: opendir(DIR,$perlvar{'lonIDsDir'});
2380: my $filename;
2381: while ($filename=readdir(DIR)) {
2382: last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
2383: }
2384: if ($filename) {
2385: &Reply($client, "ok\n", "$cmd:$tail");
2386: } else {
2387: &Failure($client, "not_found\n", "$cmd:$tail");
2388: }
2389: return 1;
2390:
2391: }
2392: ®ister_handler("userhassession", \&user_has_session_handler, 0,1,0);
2393:
2394: #
2395: # Authenticate access to a user file by checking that the token the user's
2396: # passed also exists in their session file
2397: #
2398: # Parameters:
2399: # cmd - The request keyword that dispatched to tus.
2400: # tail - The tail of the request (colon separated parameters).
2401: # client - Filehandle open on the client.
2402: # Return:
2403: # 1.
2404: sub token_auth_user_file_handler {
2405: my ($cmd, $tail, $client) = @_;
2406:
2407: my ($fname, $session) = split(/:/, $tail);
2408:
2409: chomp($session);
2410: my $reply="non_auth";
2411: my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
2412: if (open(ENVIN,"$file")) {
2413: flock(ENVIN,LOCK_SH);
2414: tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
2415: if (exists($disk_env{"userfile.$fname"})) {
2416: $reply="ok";
2417: } else {
2418: foreach my $envname (keys(%disk_env)) {
2419: if ($envname=~ m|^userfile\.\Q$fname\E|) {
2420: $reply="ok";
2421: last;
2422: }
2423: }
2424: }
2425: untie(%disk_env);
2426: close(ENVIN);
2427: &Reply($client, \$reply, "$cmd:$tail");
2428: } else {
2429: &Failure($client, "invalid_token\n", "$cmd:$tail");
2430: }
2431: return 1;
2432:
2433: }
2434: ®ister_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
2435:
2436: #
2437: # Unsubscribe from a resource.
2438: #
2439: # Parameters:
2440: # $cmd - The command that got us here.
2441: # $tail - Tail of the command (remaining parameters).
2442: # $client - File descriptor connected to client.
2443: # Returns
2444: # 0 - Requested to exit, caller should shut down.
2445: # 1 - Continue processing.
2446: #
2447: sub unsubscribe_handler {
2448: my ($cmd, $tail, $client) = @_;
2449:
2450: my $userinput= "$cmd:$tail";
2451:
2452: my ($fname) = split(/:/,$tail); # Split in case there's extrs.
2453:
2454: &Debug("Unsubscribing $fname");
2455: if (-e $fname) {
2456: &Debug("Exists");
2457: &Reply($client, &unsub($fname,$clientip), $userinput);
2458: } else {
2459: &Failure($client, "not_found\n", $userinput);
2460: }
2461: return 1;
2462: }
2463: ®ister_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
2464:
2465: # Subscribe to a resource
2466: #
2467: # Parameters:
2468: # $cmd - The command that got us here.
2469: # $tail - Tail of the command (remaining parameters).
2470: # $client - File descriptor connected to client.
2471: # Returns
2472: # 0 - Requested to exit, caller should shut down.
2473: # 1 - Continue processing.
2474: #
2475: sub subscribe_handler {
2476: my ($cmd, $tail, $client)= @_;
2477:
2478: my $userinput = "$cmd:$tail";
2479:
2480: &Reply( $client, &subscribe($userinput,$clientip), $userinput);
2481:
2482: return 1;
2483: }
2484: ®ister_handler("sub", \&subscribe_handler, 0, 1, 0);
2485:
2486: #
2487: # Determine the latest version of a resource (it looks for the highest
2488: # past version and then returns that +1)
2489: #
2490: # Parameters:
2491: # $cmd - The command that got us here.
2492: # $tail - Tail of the command (remaining parameters).
2493: # (Should consist of an absolute path to a file)
2494: # $client - File descriptor connected to client.
2495: # Returns
2496: # 0 - Requested to exit, caller should shut down.
2497: # 1 - Continue processing.
2498: #
2499: sub current_version_handler {
2500: my ($cmd, $tail, $client) = @_;
2501:
2502: my $userinput= "$cmd:$tail";
2503:
2504: my $fname = $tail;
2505: &Reply( $client, ¤tversion($fname)."\n", $userinput);
2506: return 1;
2507:
2508: }
2509: ®ister_handler("currentversion", \¤t_version_handler, 0, 1, 0);
2510:
2511: # Make an entry in a user's activity log.
2512: #
2513: # Parameters:
2514: # $cmd - The command that got us here.
2515: # $tail - Tail of the command (remaining parameters).
2516: # $client - File descriptor connected to client.
2517: # Returns
2518: # 0 - Requested to exit, caller should shut down.
2519: # 1 - Continue processing.
2520: #
2521: sub activity_log_handler {
2522: my ($cmd, $tail, $client) = @_;
2523:
2524:
2525: my $userinput= "$cmd:$tail";
2526:
2527: my ($udom,$uname,$what)=split(/:/,$tail);
2528: chomp($what);
2529: my $proname=&propath($udom,$uname);
2530: my $now=time;
2531: my $hfh;
2532: if ($hfh=IO::File->new(">>$proname/activity.log")) {
2533: print $hfh "$now:$clientname:$what\n";
2534: &Reply( $client, "ok\n", $userinput);
2535: } else {
2536: &Failure($client, "error: ".($!+0)." IO::File->new Failed "
2537: ."while attempting log\n",
2538: $userinput);
2539: }
2540:
2541: return 1;
2542: }
2543: ®ister_handler("log", \&activity_log_handler, 0, 1, 0);
2544:
2545: #
2546: # Put a namespace entry in a user profile hash.
2547: # My druthers would be for this to be an encrypted interaction too.
2548: # anything that might be an inadvertent covert channel about either
2549: # user authentication or user personal information....
2550: #
2551: # Parameters:
2552: # $cmd - The command that got us here.
2553: # $tail - Tail of the command (remaining parameters).
2554: # $client - File descriptor connected to client.
2555: # Returns
2556: # 0 - Requested to exit, caller should shut down.
2557: # 1 - Continue processing.
2558: #
2559: sub put_user_profile_entry {
2560: my ($cmd, $tail, $client) = @_;
2561:
2562: my $userinput = "$cmd:$tail";
2563:
2564: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
2565: if ($namespace ne 'roles') {
2566: chomp($what);
2567: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2568: &GDBM_WRCREAT(),"P",$what);
2569: if($hashref) {
2570: my @pairs=split(/\&/,$what);
2571: foreach my $pair (@pairs) {
2572: my ($key,$value)=split(/=/,$pair);
2573: $hashref->{$key}=$value;
2574: }
2575: if (&untie_user_hash($hashref)) {
2576: &Reply( $client, "ok\n", $userinput);
2577: } else {
2578: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2579: "while attempting put\n",
2580: $userinput);
2581: }
2582: } else {
2583: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2584: "while attempting put\n", $userinput);
2585: }
2586: } else {
2587: &Failure( $client, "refused\n", $userinput);
2588: }
2589:
2590: return 1;
2591: }
2592: ®ister_handler("put", \&put_user_profile_entry, 0, 1, 0);
2593:
2594: # Put a piece of new data in hash, returns error if entry already exists
2595: # Parameters:
2596: # $cmd - The command that got us here.
2597: # $tail - Tail of the command (remaining parameters).
2598: # $client - File descriptor connected to client.
2599: # Returns
2600: # 0 - Requested to exit, caller should shut down.
2601: # 1 - Continue processing.
2602: #
2603: sub newput_user_profile_entry {
2604: my ($cmd, $tail, $client) = @_;
2605:
2606: my $userinput = "$cmd:$tail";
2607:
2608: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
2609: if ($namespace eq 'roles') {
2610: &Failure( $client, "refused\n", $userinput);
2611: return 1;
2612: }
2613:
2614: chomp($what);
2615:
2616: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2617: &GDBM_WRCREAT(),"N",$what);
2618: if(!$hashref) {
2619: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2620: "while attempting put\n", $userinput);
2621: return 1;
2622: }
2623:
2624: my @pairs=split(/\&/,$what);
2625: foreach my $pair (@pairs) {
2626: my ($key,$value)=split(/=/,$pair);
2627: if (exists($hashref->{$key})) {
2628: &Failure($client, "key_exists: ".$key."\n",$userinput);
2629: return 1;
2630: }
2631: }
2632:
2633: foreach my $pair (@pairs) {
2634: my ($key,$value)=split(/=/,$pair);
2635: $hashref->{$key}=$value;
2636: }
2637:
2638: if (&untie_user_hash($hashref)) {
2639: &Reply( $client, "ok\n", $userinput);
2640: } else {
2641: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2642: "while attempting put\n",
2643: $userinput);
2644: }
2645: return 1;
2646: }
2647: ®ister_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
2648:
2649: #
2650: # Increment a profile entry in the user history file.
2651: # The history contains keyword value pairs. In this case,
2652: # The value itself is a pair of numbers. The first, the current value
2653: # the second an increment that this function applies to the current
2654: # value.
2655: #
2656: # Parameters:
2657: # $cmd - The command that got us here.
2658: # $tail - Tail of the command (remaining parameters).
2659: # $client - File descriptor connected to client.
2660: # Returns
2661: # 0 - Requested to exit, caller should shut down.
2662: # 1 - Continue processing.
2663: #
2664: sub increment_user_value_handler {
2665: my ($cmd, $tail, $client) = @_;
2666:
2667: my $userinput = "$cmd:$tail";
2668:
2669: my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
2670: if ($namespace ne 'roles') {
2671: chomp($what);
2672: my $hashref = &tie_user_hash($udom, $uname,
2673: $namespace, &GDBM_WRCREAT(),
2674: "P",$what);
2675: if ($hashref) {
2676: my @pairs=split(/\&/,$what);
2677: foreach my $pair (@pairs) {
2678: my ($key,$value)=split(/=/,$pair);
2679: $value = &unescape($value);
2680: # We could check that we have a number...
2681: if (! defined($value) || $value eq '') {
2682: $value = 1;
2683: }
2684: $hashref->{$key}+=$value;
2685: if ($namespace eq 'nohist_resourcetracker') {
2686: if ($hashref->{$key} < 0) {
2687: $hashref->{$key} = 0;
2688: }
2689: }
2690: }
2691: if (&untie_user_hash($hashref)) {
2692: &Reply( $client, "ok\n", $userinput);
2693: } else {
2694: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2695: "while attempting inc\n", $userinput);
2696: }
2697: } else {
2698: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2699: "while attempting inc\n", $userinput);
2700: }
2701: } else {
2702: &Failure($client, "refused\n", $userinput);
2703: }
2704:
2705: return 1;
2706: }
2707: ®ister_handler("inc", \&increment_user_value_handler, 0, 1, 0);
2708:
2709: #
2710: # Put a new role for a user. Roles are LonCAPA's packaging of permissions.
2711: # Each 'role' a user has implies a set of permissions. Adding a new role
2712: # for a person grants the permissions packaged with that role
2713: # to that user when the role is selected.
2714: #
2715: # Parameters:
2716: # $cmd - The command string (rolesput).
2717: # $tail - The remainder of the request line. For rolesput this
2718: # consists of a colon separated list that contains:
2719: # The domain and user that is granting the role (logged).
2720: # The domain and user that is getting the role.
2721: # The roles being granted as a set of & separated pairs.
2722: # each pair a key value pair.
2723: # $client - File descriptor connected to the client.
2724: # Returns:
2725: # 0 - If the daemon should exit
2726: # 1 - To continue processing.
2727: #
2728: #
2729: sub roles_put_handler {
2730: my ($cmd, $tail, $client) = @_;
2731:
2732: my $userinput = "$cmd:$tail";
2733:
2734: my ( $exedom, $exeuser, $udom, $uname, $what) = split(/:/,$tail);
2735:
2736:
2737: my $namespace='roles';
2738: chomp($what);
2739: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2740: &GDBM_WRCREAT(), "P",
2741: "$exedom:$exeuser:$what");
2742: #
2743: # Log the attempt to set a role. The {}'s here ensure that the file
2744: # handle is open for the minimal amount of time. Since the flush
2745: # is done on close this improves the chances the log will be an un-
2746: # corrupted ordered thing.
2747: if ($hashref) {
2748: my $pass_entry = &get_auth_type($udom, $uname);
2749: my ($auth_type,$pwd) = split(/:/, $pass_entry);
2750: $auth_type = $auth_type.":";
2751: my @pairs=split(/\&/,$what);
2752: foreach my $pair (@pairs) {
2753: my ($key,$value)=split(/=/,$pair);
2754: &manage_permissions($key, $udom, $uname,
2755: $auth_type);
2756: $hashref->{$key}=$value;
2757: }
2758: if (&untie_user_hash($hashref)) {
2759: &Reply($client, "ok\n", $userinput);
2760: } else {
2761: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2762: "while attempting rolesput\n", $userinput);
2763: }
2764: } else {
2765: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2766: "while attempting rolesput\n", $userinput);
2767: }
2768: return 1;
2769: }
2770: ®ister_handler("rolesput", \&roles_put_handler, 1,1,0); # Encoded client only.
2771:
2772: #
2773: # Deletes (removes) a role for a user. This is equivalent to removing
2774: # a permissions package associated with the role from the user's profile.
2775: #
2776: # Parameters:
2777: # $cmd - The command (rolesdel)
2778: # $tail - The remainder of the request line. This consists
2779: # of:
2780: # The domain and user requesting the change (logged)
2781: # The domain and user being changed.
2782: # The roles being revoked. These are shipped to us
2783: # as a bunch of & separated role name keywords.
2784: # $client - The file handle open on the client.
2785: # Returns:
2786: # 1 - Continue processing
2787: # 0 - Exit.
2788: #
2789: sub roles_delete_handler {
2790: my ($cmd, $tail, $client) = @_;
2791:
2792: my $userinput = "$cmd:$tail";
2793:
2794: my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
2795: &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
2796: "what = ".$what);
2797: my $namespace='roles';
2798: chomp($what);
2799: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2800: &GDBM_WRCREAT(), "D",
2801: "$exedom:$exeuser:$what");
2802:
2803: if ($hashref) {
2804: my @rolekeys=split(/\&/,$what);
2805:
2806: foreach my $key (@rolekeys) {
2807: delete $hashref->{$key};
2808: }
2809: if (&untie_user_hash($hashref)) {
2810: &Reply($client, "ok\n", $userinput);
2811: } else {
2812: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2813: "while attempting rolesdel\n", $userinput);
2814: }
2815: } else {
2816: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2817: "while attempting rolesdel\n", $userinput);
2818: }
2819:
2820: return 1;
2821: }
2822: ®ister_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
2823:
2824: # Unencrypted get from a user's profile database. See
2825: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
2826: # This function retrieves a keyed item from a specific named database in the
2827: # user's directory.
2828: #
2829: # Parameters:
2830: # $cmd - Command request keyword (get).
2831: # $tail - Tail of the command. This is a colon separated list
2832: # consisting of the domain and username that uniquely
2833: # identifies the profile,
2834: # The 'namespace' which selects the gdbm file to
2835: # do the lookup in,
2836: # & separated list of keys to lookup. Note that
2837: # the values are returned as an & separated list too.
2838: # $client - File descriptor open on the client.
2839: # Returns:
2840: # 1 - Continue processing.
2841: # 0 - Exit.
2842: #
2843: sub get_profile_entry {
2844: my ($cmd, $tail, $client) = @_;
2845:
2846: my $userinput= "$cmd:$tail";
2847:
2848: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2849: chomp($what);
2850:
2851:
2852: my $replystring = read_profile($udom, $uname, $namespace, $what);
2853: my ($first) = split(/:/,$replystring);
2854: if($first ne "error") {
2855: &Reply($client, \$replystring, $userinput);
2856: } else {
2857: &Failure($client, $replystring." while attempting get\n", $userinput);
2858: }
2859: return 1;
2860:
2861:
2862: }
2863: ®ister_handler("get", \&get_profile_entry, 0,1,0);
2864:
2865: #
2866: # Process the encrypted get request. Note that the request is sent
2867: # in clear, but the reply is encrypted. This is a small covert channel:
2868: # information about the sensitive keys is given to the snooper. Just not
2869: # information about the values of the sensitive key. Hmm if I wanted to
2870: # know these I'd snoop for the egets. Get the profile item names from them
2871: # and then issue a get for them since there's no enforcement of the
2872: # requirement of an encrypted get for particular profile items. If I
2873: # were re-doing this, I'd force the request to be encrypted as well as the
2874: # reply. I'd also just enforce encrypted transactions for all gets since
2875: # that would prevent any covert channel snooping.
2876: #
2877: # Parameters:
2878: # $cmd - Command keyword of request (eget).
2879: # $tail - Tail of the command. See GetProfileEntry
# for more information about this.
2880: # $client - File open on the client.
2881: # Returns:
2882: # 1 - Continue processing
2883: # 0 - server should exit.
2884: sub get_profile_entry_encrypted {
2885: my ($cmd, $tail, $client) = @_;
2886:
2887: my $userinput = "$cmd:$tail";
2888:
2889: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2890: chomp($what);
2891: my $qresult = read_profile($udom, $uname, $namespace, $what);
2892: my ($first) = split(/:/, $qresult);
2893: if($first ne "error") {
2894:
2895: if ($cipher) {
2896: my $cmdlength=length($qresult);
2897: $qresult.=" ";
2898: my $encqresult='';
2899: for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
2900: $encqresult.= unpack("H16",
2901: $cipher->encrypt(substr($qresult,
2902: $encidx,
2903: 8)));
2904: }
2905: &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
2906: } else {
2907: &Failure( $client, "error:no_key\n", $userinput);
2908: }
2909: } else {
2910: &Failure($client, "$qresult while attempting eget\n", $userinput);
2911:
2912: }
2913:
2914: return 1;
2915: }
2916: ®ister_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
2917:
2918: #
2919: # Deletes a key in a user profile database.
2920: #
2921: # Parameters:
2922: # $cmd - Command keyword (del).
2923: # $tail - Command tail. IN this case a colon
2924: # separated list containing:
2925: # The domain and user that identifies uniquely
2926: # the identity of the user.
2927: # The profile namespace (name of the profile
2928: # database file).
2929: # & separated list of keywords to delete.
2930: # $client - File open on client socket.
2931: # Returns:
2932: # 1 - Continue processing
2933: # 0 - Exit server.
2934: #
2935: #
2936: sub delete_profile_entry {
2937: my ($cmd, $tail, $client) = @_;
2938:
2939: my $userinput = "cmd:$tail";
2940:
2941: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2942: chomp($what);
2943: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2944: &GDBM_WRCREAT(),
2945: "D",$what);
2946: if ($hashref) {
2947: my @keys=split(/\&/,$what);
2948: foreach my $key (@keys) {
2949: delete($hashref->{$key});
2950: }
2951: if (&untie_user_hash($hashref)) {
2952: &Reply($client, "ok\n", $userinput);
2953: } else {
2954: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2955: "while attempting del\n", $userinput);
2956: }
2957: } else {
2958: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2959: "while attempting del\n", $userinput);
2960: }
2961: return 1;
2962: }
2963: ®ister_handler("del", \&delete_profile_entry, 0, 1, 0);
2964:
2965: #
2966: # List the set of keys that are defined in a profile database file.
2967: # A successful reply from this will contain an & separated list of
2968: # the keys.
2969: # Parameters:
2970: # $cmd - Command request (keys).
2971: # $tail - Remainder of the request, a colon separated
2972: # list containing domain/user that identifies the
2973: # user being queried, and the database namespace
2974: # (database filename essentially).
2975: # $client - File open on the client.
2976: # Returns:
2977: # 1 - Continue processing.
2978: # 0 - Exit the server.
2979: #
2980: sub get_profile_keys {
2981: my ($cmd, $tail, $client) = @_;
2982:
2983: my $userinput = "$cmd:$tail";
2984:
2985: my ($udom,$uname,$namespace)=split(/:/,$tail);
2986: my $qresult='';
2987: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2988: &GDBM_READER());
2989: if ($hashref) {
2990: foreach my $key (keys %$hashref) {
2991: $qresult.="$key&";
2992: }
2993: if (&untie_user_hash($hashref)) {
2994: $qresult=~s/\&$//;
2995: &Reply($client, \$qresult, $userinput);
2996: } else {
2997: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2998: "while attempting keys\n", $userinput);
2999: }
3000: } else {
3001: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3002: "while attempting keys\n", $userinput);
3003: }
3004:
3005: return 1;
3006: }
3007: ®ister_handler("keys", \&get_profile_keys, 0, 1, 0);
3008:
3009: #
3010: # Dump the contents of a user profile database.
3011: # Note that this constitutes a very large covert channel too since
3012: # the dump will return sensitive information that is not encrypted.
3013: # The naive security assumption is that the session negotiation ensures
3014: # our client is trusted and I don't believe that's assured at present.
3015: # Sure want badly to go to ssl or tls. Of course if my peer isn't really
3016: # a LonCAPA node they could have negotiated an encryption key too so >sigh<.
3017: #
3018: # Parameters:
3019: # $cmd - The command request keyword (currentdump).
3020: # $tail - Remainder of the request, consisting of a colon
3021: # separated list that has the domain/username and
3022: # the namespace to dump (database file).
3023: # $client - file open on the remote client.
3024: # Returns:
3025: # 1 - Continue processing.
3026: # 0 - Exit the server.
3027: #
3028: sub dump_profile_database {
3029: my ($cmd, $tail, $client) = @_;
3030:
3031: my $userinput = "$cmd:$tail";
3032:
3033: my ($udom,$uname,$namespace) = split(/:/,$tail);
3034: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3035: &GDBM_READER());
3036: if ($hashref) {
3037: # Structure of %data:
3038: # $data{$symb}->{$parameter}=$value;
3039: # $data{$symb}->{'v.'.$parameter}=$version;
3040: # since $parameter will be unescaped, we do not
3041: # have to worry about silly parameter names...
3042:
3043: my $qresult='';
3044: my %data = (); # A hash of anonymous hashes..
3045: while (my ($key,$value) = each(%$hashref)) {
3046: my ($v,$symb,$param) = split(/:/,$key);
3047: next if ($v eq 'version' || $symb eq 'keys');
3048: next if (exists($data{$symb}) &&
3049: exists($data{$symb}->{$param}) &&
3050: $data{$symb}->{'v.'.$param} > $v);
3051: $data{$symb}->{$param}=$value;
3052: $data{$symb}->{'v.'.$param}=$v;
3053: }
3054: if (&untie_user_hash($hashref)) {
3055: while (my ($symb,$param_hash) = each(%data)) {
3056: while(my ($param,$value) = each (%$param_hash)){
3057: next if ($param =~ /^v\./); # Ignore versions...
3058: #
3059: # Just dump the symb=value pairs separated by &
3060: #
3061: $qresult.=$symb.':'.$param.'='.$value.'&';
3062: }
3063: }
3064: chop($qresult);
3065: &Reply($client , \$qresult, $userinput);
3066: } else {
3067: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3068: "while attempting currentdump\n", $userinput);
3069: }
3070: } else {
3071: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3072: "while attempting currentdump\n", $userinput);
3073: }
3074:
3075: return 1;
3076: }
3077: ®ister_handler("currentdump", \&dump_profile_database, 0, 1, 0);
3078:
3079: #
3080: # Dump a profile database with an optional regular expression
3081: # to match against the keys. In this dump, no effort is made
3082: # to separate symb from version information. Presumably the
3083: # databases that are dumped by this command are of a different
3084: # structure. Need to look at this and improve the documentation of
3085: # both this and the currentdump handler.
3086: # Parameters:
3087: # $cmd - The command keyword.
3088: # $tail - All of the characters after the $cmd:
3089: # These are expected to be a colon
3090: # separated list containing:
3091: # domain/user - identifying the user.
3092: # namespace - identifying the database.
3093: # regexp - optional regular expression
3094: # that is matched against
3095: # database keywords to do
3096: # selective dumps.
3097: # $client - Channel open on the client.
3098: # Returns:
3099: # 1 - Continue processing.
3100: # Side effects:
3101: # response is written to $client.
3102: #
3103: sub dump_with_regexp {
3104: my ($cmd, $tail, $client) = @_;
3105:
3106:
3107: my $userinput = "$cmd:$tail";
3108:
3109: my ($udom,$uname,$namespace,$regexp,$range)=split(/:/,$tail);
3110: if (defined($regexp)) {
3111: $regexp=&unescape($regexp);
3112: } else {
3113: $regexp='.';
3114: }
3115: my ($start,$end);
3116: if (defined($range)) {
3117: if ($range =~/^(\d+)\-(\d+)$/) {
3118: ($start,$end) = ($1,$2);
3119: } elsif ($range =~/^(\d+)$/) {
3120: ($start,$end) = (0,$1);
3121: } else {
3122: undef($range);
3123: }
3124: }
3125: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3126: &GDBM_READER());
3127: if ($hashref) {
3128: my $qresult='';
3129: my $count=0;
3130: while (my ($key,$value) = each(%$hashref)) {
3131: if ($namespace eq 'roles') {
3132: if ($key =~ m{^/($LONCAPA::match_domain)/($LONCAPA::match_community)_(cc|co|in|ta|ep|ad|st|cr)}) {
3133: my $cdom = $1;
3134: my $cnum = $2;
3135: if ($clientversion =~ /^['"]?(\d+)\.(\d+)[.\d\-]+['"]?$/) {
3136: my $major = $1;
3137: my $minor = $2;
3138: next if (($major < 2) || (($major == 2) && ($minor < 9)));
3139: } else {
3140: my $homeserver = &Apache::lonnet::homeserver($cnum,$cdom);
3141: next unless ($currenthostid eq $homeserver);
3142: }
3143: }
3144: }
3145: if ($regexp eq '.') {
3146: $count++;
3147: if (defined($range) && $count >= $end) { last; }
3148: if (defined($range) && $count < $start) { next; }
3149: $qresult.=$key.'='.$value.'&';
3150: } else {
3151: my $unescapeKey = &unescape($key);
3152: if (eval('$unescapeKey=~/$regexp/')) {
3153: $count++;
3154: if (defined($range) && $count >= $end) { last; }
3155: if (defined($range) && $count < $start) { next; }
3156: $qresult.="$key=$value&";
3157: }
3158: }
3159: }
3160: if (&untie_user_hash($hashref)) {
3161: chop($qresult);
3162: &Reply($client, \$qresult, $userinput);
3163: } else {
3164: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3165: "while attempting dump\n", $userinput);
3166: }
3167: } else {
3168: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3169: "while attempting dump\n", $userinput);
3170: }
3171:
3172: return 1;
3173: }
3174: ®ister_handler("dump", \&dump_with_regexp, 0, 1, 0);
3175:
3176: # Store a set of key=value pairs associated with a versioned name.
3177: #
3178: # Parameters:
3179: # $cmd - Request command keyword.
3180: # $tail - Tail of the request. This is a colon
3181: # separated list containing:
3182: # domain/user - User and authentication domain.
3183: # namespace - Name of the database being modified
3184: # rid - Resource keyword to modify.
3185: # what - new value associated with rid.
3186: #
3187: # $client - Socket open on the client.
3188: #
3189: #
3190: # Returns:
3191: # 1 (keep on processing).
3192: # Side-Effects:
3193: # Writes to the client
3194: sub store_handler {
3195: my ($cmd, $tail, $client) = @_;
3196:
3197: my $userinput = "$cmd:$tail";
3198:
3199: my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
3200: if ($namespace ne 'roles') {
3201:
3202: chomp($what);
3203: my @pairs=split(/\&/,$what);
3204: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3205: &GDBM_WRCREAT(), "S",
3206: "$rid:$what");
3207: if ($hashref) {
3208: my $now = time;
3209: my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
3210: my $key;
3211: $hashref->{"version:$rid"}++;
3212: my $version=$hashref->{"version:$rid"};
3213: my $allkeys='';
3214: foreach my $pair (@pairs) {
3215: my ($key,$value)=split(/=/,$pair);
3216: $allkeys.=$key.':';
3217: $hashref->{"$version:$rid:$key"}=$value;
3218: }
3219: $hashref->{"$version:$rid:timestamp"}=$now;
3220: $allkeys.='timestamp';
3221: $hashref->{"$version:keys:$rid"}=$allkeys;
3222: if (&untie_user_hash($hashref)) {
3223: &Reply($client, "ok\n", $userinput);
3224: } else {
3225: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3226: "while attempting store\n", $userinput);
3227: }
3228: } else {
3229: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3230: "while attempting store\n", $userinput);
3231: }
3232: } else {
3233: &Failure($client, "refused\n", $userinput);
3234: }
3235:
3236: return 1;
3237: }
3238: ®ister_handler("store", \&store_handler, 0, 1, 0);
3239:
3240: # Modify a set of key=value pairs associated with a versioned name.
3241: #
3242: # Parameters:
3243: # $cmd - Request command keyword.
3244: # $tail - Tail of the request. This is a colon
3245: # separated list containing:
3246: # domain/user - User and authentication domain.
3247: # namespace - Name of the database being modified
3248: # rid - Resource keyword to modify.
3249: # v - Version item to modify
3250: # what - new value associated with rid.
3251: #
3252: # $client - Socket open on the client.
3253: #
3254: #
3255: # Returns:
3256: # 1 (keep on processing).
3257: # Side-Effects:
3258: # Writes to the client
3259: sub putstore_handler {
3260: my ($cmd, $tail, $client) = @_;
3261:
3262: my $userinput = "$cmd:$tail";
3263:
3264: my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
3265: if ($namespace ne 'roles') {
3266:
3267: chomp($what);
3268: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3269: &GDBM_WRCREAT(), "M",
3270: "$rid:$v:$what");
3271: if ($hashref) {
3272: my $now = time;
3273: my %data = &hash_extract($what);
3274: my @allkeys;
3275: while (my($key,$value) = each(%data)) {
3276: push(@allkeys,$key);
3277: $hashref->{"$v:$rid:$key"} = $value;
3278: }
3279: my $allkeys = join(':',@allkeys);
3280: $hashref->{"$v:keys:$rid"}=$allkeys;
3281:
3282: if (&untie_user_hash($hashref)) {
3283: &Reply($client, "ok\n", $userinput);
3284: } else {
3285: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3286: "while attempting store\n", $userinput);
3287: }
3288: } else {
3289: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3290: "while attempting store\n", $userinput);
3291: }
3292: } else {
3293: &Failure($client, "refused\n", $userinput);
3294: }
3295:
3296: return 1;
3297: }
3298: ®ister_handler("putstore", \&putstore_handler, 0, 1, 0);
3299:
3300: sub hash_extract {
3301: my ($str)=@_;
3302: my %hash;
3303: foreach my $pair (split(/\&/,$str)) {
3304: my ($key,$value)=split(/=/,$pair);
3305: $hash{$key}=$value;
3306: }
3307: return (%hash);
3308: }
3309: sub hash_to_str {
3310: my ($hash_ref)=@_;
3311: my $str;
3312: foreach my $key (keys(%$hash_ref)) {
3313: $str.=$key.'='.$hash_ref->{$key}.'&';
3314: }
3315: $str=~s/\&$//;
3316: return $str;
3317: }
3318:
3319: #
3320: # Dump out all versions of a resource that has key=value pairs associated
3321: # with it for each version. These resources are built up via the store
3322: # command.
3323: #
3324: # Parameters:
3325: # $cmd - Command keyword.
3326: # $tail - Remainder of the request which consists of:
3327: # domain/user - User and auth. domain.
3328: # namespace - name of resource database.
3329: # rid - Resource id.
3330: # $client - socket open on the client.
3331: #
3332: # Returns:
3333: # 1 indicating the caller should not yet exit.
3334: # Side-effects:
3335: # Writes a reply to the client.
3336: # The reply is a string of the following shape:
3337: # version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
3338: # Where the 1 above represents version 1.
3339: # this continues for all pairs of keys in all versions.
3340: #
3341: #
3342: #
3343: #
3344: sub restore_handler {
3345: my ($cmd, $tail, $client) = @_;
3346:
3347: my $userinput = "$cmd:$tail"; # Only used for logging purposes.
3348: my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
3349: $namespace=~s/\//\_/g;
3350: $namespace = &LONCAPA::clean_username($namespace);
3351:
3352: chomp($rid);
3353: my $qresult='';
3354: my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
3355: if ($hashref) {
3356: my $version=$hashref->{"version:$rid"};
3357: $qresult.="version=$version&";
3358: my $scope;
3359: for ($scope=1;$scope<=$version;$scope++) {
3360: my $vkeys=$hashref->{"$scope:keys:$rid"};
3361: my @keys=split(/:/,$vkeys);
3362: my $key;
3363: $qresult.="$scope:keys=$vkeys&";
3364: foreach $key (@keys) {
3365: $qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
3366: }
3367: }
3368: if (&untie_user_hash($hashref)) {
3369: $qresult=~s/\&$//;
3370: &Reply( $client, \$qresult, $userinput);
3371: } else {
3372: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3373: "while attempting restore\n", $userinput);
3374: }
3375: } else {
3376: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3377: "while attempting restore\n", $userinput);
3378: }
3379:
3380: return 1;
3381:
3382:
3383: }
3384: ®ister_handler("restore", \&restore_handler, 0,1,0);
3385:
3386: #
3387: # Add a chat message to a synchronous discussion board.
3388: #
3389: # Parameters:
3390: # $cmd - Request keyword.
3391: # $tail - Tail of the command. A colon separated list
3392: # containing:
3393: # cdom - Domain on which the chat board lives
3394: # cnum - Course containing the chat board.
3395: # newpost - Body of the posting.
3396: # group - Optional group, if chat board is only
3397: # accessible in a group within the course
3398: # $client - Socket open on the client.
3399: # Returns:
3400: # 1 - Indicating caller should keep on processing.
3401: #
3402: # Side-effects:
3403: # writes a reply to the client.
3404: #
3405: #
3406: sub send_chat_handler {
3407: my ($cmd, $tail, $client) = @_;
3408:
3409:
3410: my $userinput = "$cmd:$tail";
3411:
3412: my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
3413: &chat_add($cdom,$cnum,$newpost,$group);
3414: &Reply($client, "ok\n", $userinput);
3415:
3416: return 1;
3417: }
3418: ®ister_handler("chatsend", \&send_chat_handler, 0, 1, 0);
3419:
3420: #
3421: # Retrieve the set of chat messages from a discussion board.
3422: #
3423: # Parameters:
3424: # $cmd - Command keyword that initiated the request.
3425: # $tail - Remainder of the request after the command
3426: # keyword. In this case a colon separated list of
3427: # chat domain - Which discussion board.
3428: # chat id - Discussion thread(?)
3429: # domain/user - Authentication domain and username
3430: # of the requesting person.
3431: # group - Optional course group containing
3432: # the board.
3433: # $client - Socket open on the client program.
3434: # Returns:
3435: # 1 - continue processing
3436: # Side effects:
3437: # Response is written to the client.
3438: #
3439: sub retrieve_chat_handler {
3440: my ($cmd, $tail, $client) = @_;
3441:
3442:
3443: my $userinput = "$cmd:$tail";
3444:
3445: my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
3446: my $reply='';
3447: foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
3448: $reply.=&escape($_).':';
3449: }
3450: $reply=~s/\:$//;
3451: &Reply($client, \$reply, $userinput);
3452:
3453:
3454: return 1;
3455: }
3456: ®ister_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
3457:
3458: #
3459: # Initiate a query of an sql database. SQL query repsonses get put in
3460: # a file for later retrieval. This prevents sql query results from
3461: # bottlenecking the system. Note that with loncnew, perhaps this is
3462: # less of an issue since multiple outstanding requests can be concurrently
3463: # serviced.
3464: #
3465: # Parameters:
3466: # $cmd - COmmand keyword that initiated the request.
3467: # $tail - Remainder of the command after the keyword.
3468: # For this function, this consists of a query and
3469: # 3 arguments that are self-documentingly labelled
3470: # in the original arg1, arg2, arg3.
3471: # $client - Socket open on the client.
3472: # Return:
3473: # 1 - Indicating processing should continue.
3474: # Side-effects:
3475: # a reply is written to $client.
3476: #
3477: sub send_query_handler {
3478: my ($cmd, $tail, $client) = @_;
3479:
3480:
3481: my $userinput = "$cmd:$tail";
3482:
3483: my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
3484: $query=~s/\n*$//g;
3485: &Reply($client, "". &sql_reply("$clientname\&$query".
3486: "\&$arg1"."\&$arg2"."\&$arg3")."\n",
3487: $userinput);
3488:
3489: return 1;
3490: }
3491: ®ister_handler("querysend", \&send_query_handler, 0, 1, 0);
3492:
3493: #
3494: # Add a reply to an sql query. SQL queries are done asyncrhonously.
3495: # The query is submitted via a "querysend" transaction.
3496: # There it is passed on to the lonsql daemon, queued and issued to
3497: # mysql.
3498: # This transaction is invoked when the sql transaction is complete
3499: # it stores the query results in flie and indicates query completion.
3500: # presumably local software then fetches this response... I'm guessing
3501: # the sequence is: lonc does a querysend, we ask lonsql to do it.
3502: # lonsql on completion of the query interacts with the lond of our
3503: # client to do a query reply storing two files:
3504: # - id - The results of the query.
3505: # - id.end - Indicating the transaction completed.
3506: # NOTE: id is a unique id assigned to the query and querysend time.
3507: # Parameters:
3508: # $cmd - Command keyword that initiated this request.
3509: # $tail - Remainder of the tail. In this case that's a colon
3510: # separated list containing the query Id and the
3511: # results of the query.
3512: # $client - Socket open on the client.
3513: # Return:
3514: # 1 - Indicating that we should continue processing.
3515: # Side effects:
3516: # ok written to the client.
3517: #
3518: sub reply_query_handler {
3519: my ($cmd, $tail, $client) = @_;
3520:
3521:
3522: my $userinput = "$cmd:$tail";
3523:
3524: my ($id,$reply)=split(/:/,$tail);
3525: my $store;
3526: my $execdir=$perlvar{'lonDaemons'};
3527: if ($store=IO::File->new(">$execdir/tmp/$id")) {
3528: $reply=~s/\&/\n/g;
3529: print $store $reply;
3530: close $store;
3531: my $store2=IO::File->new(">$execdir/tmp/$id.end");
3532: print $store2 "done\n";
3533: close $store2;
3534: &Reply($client, "ok\n", $userinput);
3535: } else {
3536: &Failure($client, "error: ".($!+0)
3537: ." IO::File->new Failed ".
3538: "while attempting queryreply\n", $userinput);
3539: }
3540:
3541:
3542: return 1;
3543: }
3544: ®ister_handler("queryreply", \&reply_query_handler, 0, 1, 0);
3545:
3546: #
3547: # Process the courseidput request. Not quite sure what this means
3548: # at the system level sense. It appears a gdbm file in the
3549: # /home/httpd/lonUsers/$domain/nohist_courseids is tied and
3550: # a set of entries made in that database.
3551: #
3552: # Parameters:
3553: # $cmd - The command keyword that initiated this request.
3554: # $tail - Tail of the command. In this case consists of a colon
3555: # separated list contaning the domain to apply this to and
3556: # an ampersand separated list of keyword=value pairs.
3557: # Each value is a colon separated list that includes:
3558: # description, institutional code and course owner.
3559: # For backward compatibility with versions included
3560: # in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
3561: # code and/or course owner are preserved from the existing
3562: # record when writing a new record in response to 1.1 or
3563: # 1.2 implementations of lonnet::flushcourselogs().
3564: #
3565: # $client - Socket open on the client.
3566: # Returns:
3567: # 1 - indicating that processing should continue
3568: #
3569: # Side effects:
3570: # reply is written to the client.
3571: #
3572: sub put_course_id_handler {
3573: my ($cmd, $tail, $client) = @_;
3574:
3575:
3576: my $userinput = "$cmd:$tail";
3577:
3578: my ($udom, $what) = split(/:/, $tail,2);
3579: chomp($what);
3580: my $now=time;
3581: my @pairs=split(/\&/,$what);
3582:
3583: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3584: if ($hashref) {
3585: foreach my $pair (@pairs) {
3586: my ($key,$courseinfo) = split(/=/,$pair,2);
3587: $courseinfo =~ s/=/:/g;
3588: if (defined($hashref->{$key})) {
3589: my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
3590: if (ref($value) eq 'HASH') {
3591: my @items = ('description','inst_code','owner','type');
3592: my @new_items = split(/:/,$courseinfo,-1);
3593: my %storehash;
3594: for (my $i=0; $i<@new_items; $i++) {
3595: $storehash{$items[$i]} = &unescape($new_items[$i]);
3596: }
3597: $hashref->{$key} =
3598: &Apache::lonnet::freeze_escape(\%storehash);
3599: my $unesc_key = &unescape($key);
3600: $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
3601: next;
3602: }
3603: }
3604: my @current_items = split(/:/,$hashref->{$key},-1);
3605: shift(@current_items); # remove description
3606: pop(@current_items); # remove last access
3607: my $numcurrent = scalar(@current_items);
3608: if ($numcurrent > 3) {
3609: $numcurrent = 3;
3610: }
3611: my @new_items = split(/:/,$courseinfo,-1);
3612: my $numnew = scalar(@new_items);
3613: if ($numcurrent > 0) {
3614: if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2
3615: for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
3616: $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
3617: }
3618: }
3619: }
3620: $hashref->{$key}=$courseinfo.':'.$now;
3621: }
3622: if (&untie_domain_hash($hashref)) {
3623: &Reply( $client, "ok\n", $userinput);
3624: } else {
3625: &Failure($client, "error: ".($!+0)
3626: ." untie(GDBM) Failed ".
3627: "while attempting courseidput\n", $userinput);
3628: }
3629: } else {
3630: &Failure($client, "error: ".($!+0)
3631: ." tie(GDBM) Failed ".
3632: "while attempting courseidput\n", $userinput);
3633: }
3634:
3635: return 1;
3636: }
3637: ®ister_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
3638:
3639: sub put_course_id_hash_handler {
3640: my ($cmd, $tail, $client) = @_;
3641: my $userinput = "$cmd:$tail";
3642: my ($udom,$mode,$what) = split(/:/, $tail,3);
3643: chomp($what);
3644: my $now=time;
3645: my @pairs=split(/\&/,$what);
3646: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3647: if ($hashref) {
3648: foreach my $pair (@pairs) {
3649: my ($key,$value)=split(/=/,$pair);
3650: my $unesc_key = &unescape($key);
3651: if ($mode ne 'timeonly') {
3652: if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
3653: my $curritems = &Apache::lonnet::thaw_unescape($key);
3654: if (ref($curritems) ne 'HASH') {
3655: my @current_items = split(/:/,$hashref->{$key},-1);
3656: my $lasttime = pop(@current_items);
3657: $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
3658: } else {
3659: $hashref->{&escape('lasttime:'.$unesc_key)} = '';
3660: }
3661: }
3662: $hashref->{$key} = $value;
3663: }
3664: if ($mode ne 'notime') {
3665: $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
3666: }
3667: }
3668: if (&untie_domain_hash($hashref)) {
3669: &Reply($client, "ok\n", $userinput);
3670: } else {
3671: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3672: "while attempting courseidputhash\n", $userinput);
3673: }
3674: } else {
3675: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3676: "while attempting courseidputhash\n", $userinput);
3677: }
3678: return 1;
3679: }
3680: ®ister_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
3681:
3682: # Retrieves the value of a course id resource keyword pattern
3683: # defined since a starting date. Both the starting date and the
3684: # keyword pattern are optional. If the starting date is not supplied it
3685: # is treated as the beginning of time. If the pattern is not found,
3686: # it is treatred as "." matching everything.
3687: #
3688: # Parameters:
3689: # $cmd - Command keyword that resulted in us being dispatched.
3690: # $tail - The remainder of the command that, in this case, consists
3691: # of a colon separated list of:
3692: # domain - The domain in which the course database is
3693: # defined.
3694: # since - Optional parameter describing the minimum
3695: # time of definition(?) of the resources that
3696: # will match the dump.
3697: # description - regular expression that is used to filter
3698: # the dump. Only keywords matching this regexp
3699: # will be used.
3700: # institutional code - optional supplied code to filter
3701: # the dump. Only courses with an institutional code
3702: # that match the supplied code will be returned.
3703: # owner - optional supplied username and domain of owner to
3704: # filter the dump. Only courses for which the course
3705: # owner matches the supplied username and/or domain
3706: # will be returned. Pre-2.2.0 legacy entries from
3707: # nohist_courseiddump will only contain usernames.
3708: # type - optional parameter for selection
3709: # regexp_ok - if 1 or -1 allow the supplied institutional code
3710: # filter to behave as a regular expression:
3711: # 1 will not exclude the course if the instcode matches the RE
3712: # -1 will exclude the course if the instcode matches the RE
3713: # rtn_as_hash - whether to return the information available for
3714: # each matched item as a frozen hash of all
3715: # key, value pairs in the item's hash, or as a
3716: # colon-separated list of (in order) description,
3717: # institutional code, and course owner.
3718: # selfenrollonly - filter by courses allowing self-enrollment
3719: # now or in the future (selfenrollonly = 1).
3720: # catfilter - filter by course category, assigned to a course
3721: # using manually defined categories (i.e., not
3722: # self-cataloging based on on institutional code).
3723: # showhidden - include course in results even if course
3724: # was set to be excluded from course catalog (DC only).
3725: # caller - if set to 'coursecatalog', courses set to be hidden
3726: # from course catalog will be excluded from results (unless
3727: # overridden by "showhidden".
3728: # cloner - escaped username:domain of course cloner (if picking course to
3729: # clone).
3730: # cc_clone_list - escaped comma separated list of courses for which
3731: # course cloner has active CC role (and so can clone
3732: # automatically).
3733: # cloneonly - filter by courses for which cloner has rights to clone.
3734: # createdbefore - include courses for which creation date preceeded this date.
3735: # createdafter - include courses for which creation date followed this date.
3736: # creationcontext - include courses created in specified context
3737: #
3738: # domcloner - flag to indicate if user can create CCs in course's domain.
3739: # If so, ability to clone course is automatic.
3740: #
3741: # $client - The socket open on the client.
3742: # Returns:
3743: # 1 - Continue processing.
3744: # Side Effects:
3745: # a reply is written to $client.
3746: sub dump_course_id_handler {
3747: my ($cmd, $tail, $client) = @_;
3748: my $userinput = "$cmd:$tail";
3749:
3750: my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
3751: $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
3752: $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
3753: $creationcontext,$domcloner) =split(/:/,$tail);
3754: my $now = time;
3755: my ($cloneruname,$clonerudom,%cc_clone);
3756: if (defined($description)) {
3757: $description=&unescape($description);
3758: } else {
3759: $description='.';
3760: }
3761: if (defined($instcodefilter)) {
3762: $instcodefilter=&unescape($instcodefilter);
3763: } else {
3764: $instcodefilter='.';
3765: }
3766: my ($ownerunamefilter,$ownerdomfilter);
3767: if (defined($ownerfilter)) {
3768: $ownerfilter=&unescape($ownerfilter);
3769: if ($ownerfilter ne '.' && defined($ownerfilter)) {
3770: if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
3771: $ownerunamefilter = $1;
3772: $ownerdomfilter = $2;
3773: } else {
3774: $ownerunamefilter = $ownerfilter;
3775: $ownerdomfilter = '';
3776: }
3777: }
3778: } else {
3779: $ownerfilter='.';
3780: }
3781:
3782: if (defined($coursefilter)) {
3783: $coursefilter=&unescape($coursefilter);
3784: } else {
3785: $coursefilter='.';
3786: }
3787: if (defined($typefilter)) {
3788: $typefilter=&unescape($typefilter);
3789: } else {
3790: $typefilter='.';
3791: }
3792: if (defined($regexp_ok)) {
3793: $regexp_ok=&unescape($regexp_ok);
3794: }
3795: if (defined($catfilter)) {
3796: $catfilter=&unescape($catfilter);
3797: }
3798: if (defined($cloner)) {
3799: $cloner = &unescape($cloner);
3800: ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/);
3801: }
3802: if (defined($cc_clone_list)) {
3803: $cc_clone_list = &unescape($cc_clone_list);
3804: my @cc_cloners = split('&',$cc_clone_list);
3805: foreach my $cid (@cc_cloners) {
3806: my ($clonedom,$clonenum) = split(':',$cid);
3807: next if ($clonedom ne $udom);
3808: $cc_clone{$clonedom.'_'.$clonenum} = 1;
3809: }
3810: }
3811: if ($createdbefore ne '') {
3812: $createdbefore = &unescape($createdbefore);
3813: } else {
3814: $createdbefore = 0;
3815: }
3816: if ($createdafter ne '') {
3817: $createdafter = &unescape($createdafter);
3818: } else {
3819: $createdafter = 0;
3820: }
3821: if ($creationcontext ne '') {
3822: $creationcontext = &unescape($creationcontext);
3823: } else {
3824: $creationcontext = '.';
3825: }
3826: my $unpack = 1;
3827: if ($description eq '.' && $instcodefilter eq '.' && $coursefilter eq '.' &&
3828: $typefilter eq '.') {
3829: $unpack = 0;
3830: }
3831: if (!defined($since)) { $since=0; }
3832: my $qresult='';
3833: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3834: if ($hashref) {
3835: while (my ($key,$value) = each(%$hashref)) {
3836: my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
3837: %unesc_val,$selfenroll_end,$selfenroll_types,$created,
3838: $context);
3839: $unesc_key = &unescape($key);
3840: if ($unesc_key =~ /^lasttime:/) {
3841: next;
3842: } else {
3843: $lasttime_key = &escape('lasttime:'.$unesc_key);
3844: }
3845: if ($hashref->{$lasttime_key} ne '') {
3846: $lasttime = $hashref->{$lasttime_key};
3847: next if ($lasttime<$since);
3848: }
3849: my ($canclone,$valchange);
3850: my $items = &Apache::lonnet::thaw_unescape($value);
3851: if (ref($items) eq 'HASH') {
3852: if ($hashref->{$lasttime_key} eq '') {
3853: next if ($since > 1);
3854: }
3855: $is_hash = 1;
3856: if ($domcloner) {
3857: $canclone = 1;
3858: } elsif (defined($clonerudom)) {
3859: if ($items->{'cloners'}) {
3860: my @cloneable = split(',',$items->{'cloners'});
3861: if (@cloneable) {
3862: if (grep(/^\*$/,@cloneable)) {
3863: $canclone = 1;
3864: } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
3865: $canclone = 1;
3866: } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
3867: $canclone = 1;
3868: }
3869: }
3870: unless ($canclone) {
3871: if ($cloneruname ne '' && $clonerudom ne '') {
3872: if ($cc_clone{$unesc_key}) {
3873: $canclone = 1;
3874: $items->{'cloners'} .= ','.$cloneruname.':'.
3875: $clonerudom;
3876: $valchange = 1;
3877: }
3878: }
3879: }
3880: } elsif (defined($cloneruname)) {
3881: if ($cc_clone{$unesc_key}) {
3882: $canclone = 1;
3883: $items->{'cloners'} = $cloneruname.':'.$clonerudom;
3884: $valchange = 1;
3885: }
3886: unless ($canclone) {
3887: if ($items->{'owner'} =~ /:/) {
3888: if ($items->{'owner'} eq $cloner) {
3889: $canclone = 1;
3890: }
3891: } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
3892: $canclone = 1;
3893: }
3894: if ($canclone) {
3895: $items->{'cloners'} = $cloneruname.':'.$clonerudom;
3896: $valchange = 1;
3897: }
3898: }
3899: }
3900: }
3901: if ($unpack || !$rtn_as_hash) {
3902: $unesc_val{'descr'} = $items->{'description'};
3903: $unesc_val{'inst_code'} = $items->{'inst_code'};
3904: $unesc_val{'owner'} = $items->{'owner'};
3905: $unesc_val{'type'} = $items->{'type'};
3906: $unesc_val{'cloners'} = $items->{'cloners'};
3907: $unesc_val{'created'} = $items->{'created'};
3908: $unesc_val{'context'} = $items->{'context'};
3909: }
3910: $selfenroll_types = $items->{'selfenroll_types'};
3911: $selfenroll_end = $items->{'selfenroll_end_date'};
3912: $created = $items->{'created'};
3913: $context = $items->{'context'};
3914: if ($selfenrollonly) {
3915: next if (!$selfenroll_types);
3916: if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
3917: next;
3918: }
3919: }
3920: if ($creationcontext ne '.') {
3921: next if (($context ne '') && ($context ne $creationcontext));
3922: }
3923: if ($createdbefore > 0) {
3924: next if (($created eq '') || ($created > $createdbefore));
3925: }
3926: if ($createdafter > 0) {
3927: next if (($created eq '') || ($created <= $createdafter));
3928: }
3929: if ($catfilter ne '') {
3930: next if ($items->{'categories'} eq '');
3931: my @categories = split('&',$items->{'categories'});
3932: next if (@categories == 0);
3933: my @subcats = split('&',$catfilter);
3934: my $matchcat = 0;
3935: foreach my $cat (@categories) {
3936: if (grep(/^\Q$cat\E$/,@subcats)) {
3937: $matchcat = 1;
3938: last;
3939: }
3940: }
3941: next if (!$matchcat);
3942: }
3943: if ($caller eq 'coursecatalog') {
3944: if ($items->{'hidefromcat'} eq 'yes') {
3945: next if !$showhidden;
3946: }
3947: }
3948: } else {
3949: next if ($catfilter ne '');
3950: next if ($selfenrollonly);
3951: next if ($createdbefore || $createdafter);
3952: next if ($creationcontext ne '.');
3953: if ((defined($clonerudom)) && (defined($cloneruname))) {
3954: if ($cc_clone{$unesc_key}) {
3955: $canclone = 1;
3956: $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
3957: }
3958: }
3959: $is_hash = 0;
3960: my @courseitems = split(/:/,$value);
3961: $lasttime = pop(@courseitems);
3962: if ($hashref->{$lasttime_key} eq '') {
3963: next if ($lasttime<$since);
3964: }
3965: ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
3966: }
3967: if ($cloneonly) {
3968: next unless ($canclone);
3969: }
3970: my $match = 1;
3971: if ($description ne '.') {
3972: if (!$is_hash) {
3973: $unesc_val{'descr'} = &unescape($val{'descr'});
3974: }
3975: if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
3976: $match = 0;
3977: }
3978: }
3979: if ($instcodefilter ne '.') {
3980: if (!$is_hash) {
3981: $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
3982: }
3983: if ($regexp_ok == 1) {
3984: if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
3985: $match = 0;
3986: }
3987: } elsif ($regexp_ok == -1) {
3988: if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
3989: $match = 0;
3990: }
3991: } else {
3992: if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
3993: $match = 0;
3994: }
3995: }
3996: }
3997: if ($ownerfilter ne '.') {
3998: if (!$is_hash) {
3999: $unesc_val{'owner'} = &unescape($val{'owner'});
4000: }
4001: if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
4002: if ($unesc_val{'owner'} =~ /:/) {
4003: if (eval{$unesc_val{'owner'} !~
4004: /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
4005: $match = 0;
4006: }
4007: } else {
4008: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
4009: $match = 0;
4010: }
4011: }
4012: } elsif ($ownerunamefilter ne '') {
4013: if ($unesc_val{'owner'} =~ /:/) {
4014: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
4015: $match = 0;
4016: }
4017: } else {
4018: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
4019: $match = 0;
4020: }
4021: }
4022: } elsif ($ownerdomfilter ne '') {
4023: if ($unesc_val{'owner'} =~ /:/) {
4024: if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
4025: $match = 0;
4026: }
4027: } else {
4028: if ($ownerdomfilter ne $udom) {
4029: $match = 0;
4030: }
4031: }
4032: }
4033: }
4034: if ($coursefilter ne '.') {
4035: if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
4036: $match = 0;
4037: }
4038: }
4039: if ($typefilter ne '.') {
4040: if (!$is_hash) {
4041: $unesc_val{'type'} = &unescape($val{'type'});
4042: }
4043: if ($unesc_val{'type'} eq '') {
4044: if ($typefilter ne 'Course') {
4045: $match = 0;
4046: }
4047: } else {
4048: if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
4049: $match = 0;
4050: }
4051: }
4052: }
4053: if ($match == 1) {
4054: if ($rtn_as_hash) {
4055: if ($is_hash) {
4056: if ($valchange) {
4057: my $newvalue = &Apache::lonnet::freeze_escape($items);
4058: $qresult.=$key.'='.$newvalue.'&';
4059: } else {
4060: $qresult.=$key.'='.$value.'&';
4061: }
4062: } else {
4063: my %rtnhash = ( 'description' => &unescape($val{'descr'}),
4064: 'inst_code' => &unescape($val{'inst_code'}),
4065: 'owner' => &unescape($val{'owner'}),
4066: 'type' => &unescape($val{'type'}),
4067: 'cloners' => &unescape($val{'cloners'}),
4068: );
4069: my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
4070: $qresult.=$key.'='.$items.'&';
4071: }
4072: } else {
4073: if ($is_hash) {
4074: $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
4075: &escape($unesc_val{'inst_code'}).':'.
4076: &escape($unesc_val{'owner'}).'&';
4077: } else {
4078: $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
4079: ':'.$val{'owner'}.'&';
4080: }
4081: }
4082: }
4083: }
4084: if (&untie_domain_hash($hashref)) {
4085: chop($qresult);
4086: &Reply($client, \$qresult, $userinput);
4087: } else {
4088: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4089: "while attempting courseiddump\n", $userinput);
4090: }
4091: } else {
4092: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4093: "while attempting courseiddump\n", $userinput);
4094: }
4095: return 1;
4096: }
4097: ®ister_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
4098:
4099: sub course_lastaccess_handler {
4100: my ($cmd, $tail, $client) = @_;
4101: my $userinput = "$cmd:$tail";
4102: my ($cdom,$cnum) = split(':',$tail);
4103: my (%lastaccess,$qresult);
4104: my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
4105: if ($hashref) {
4106: while (my ($key,$value) = each(%$hashref)) {
4107: my ($unesc_key,$lasttime);
4108: $unesc_key = &unescape($key);
4109: if ($cnum) {
4110: next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
4111: }
4112: if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
4113: $lastaccess{$1} = $value;
4114: } else {
4115: my $items = &Apache::lonnet::thaw_unescape($value);
4116: if (ref($items) eq 'HASH') {
4117: unless ($lastaccess{$unesc_key}) {
4118: $lastaccess{$unesc_key} = '';
4119: }
4120: } else {
4121: my @courseitems = split(':',$value);
4122: $lastaccess{$unesc_key} = pop(@courseitems);
4123: }
4124: }
4125: }
4126: foreach my $cid (sort(keys(%lastaccess))) {
4127: $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&';
4128: }
4129: if (&untie_domain_hash($hashref)) {
4130: if ($qresult) {
4131: chop($qresult);
4132: }
4133: &Reply($client, \$qresult, $userinput);
4134: } else {
4135: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4136: "while attempting lastacourseaccess\n", $userinput);
4137: }
4138: } else {
4139: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4140: "while attempting lastcourseaccess\n", $userinput);
4141: }
4142: return 1;
4143: }
4144: ®ister_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
4145:
4146: #
4147: # Puts an unencrypted entry in a namespace db file at the domain level
4148: #
4149: # Parameters:
4150: # $cmd - The command that got us here.
4151: # $tail - Tail of the command (remaining parameters).
4152: # $client - File descriptor connected to client.
4153: # Returns
4154: # 0 - Requested to exit, caller should shut down.
4155: # 1 - Continue processing.
4156: # Side effects:
4157: # reply is written to $client.
4158: #
4159: sub put_domain_handler {
4160: my ($cmd,$tail,$client) = @_;
4161:
4162: my $userinput = "$cmd:$tail";
4163:
4164: my ($udom,$namespace,$what) =split(/:/,$tail,3);
4165: chomp($what);
4166: my @pairs=split(/\&/,$what);
4167: my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
4168: "P", $what);
4169: if ($hashref) {
4170: foreach my $pair (@pairs) {
4171: my ($key,$value)=split(/=/,$pair);
4172: $hashref->{$key}=$value;
4173: }
4174: if (&untie_domain_hash($hashref)) {
4175: &Reply($client, "ok\n", $userinput);
4176: } else {
4177: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4178: "while attempting putdom\n", $userinput);
4179: }
4180: } else {
4181: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4182: "while attempting putdom\n", $userinput);
4183: }
4184:
4185: return 1;
4186: }
4187: ®ister_handler("putdom", \&put_domain_handler, 0, 1, 0);
4188:
4189: # Unencrypted get from the namespace database file at the domain level.
4190: # This function retrieves a keyed item from a specific named database in the
4191: # domain directory.
4192: #
4193: # Parameters:
4194: # $cmd - Command request keyword (get).
4195: # $tail - Tail of the command. This is a colon separated list
4196: # consisting of the domain and the 'namespace'
4197: # which selects the gdbm file to do the lookup in,
4198: # & separated list of keys to lookup. Note that
4199: # the values are returned as an & separated list too.
4200: # $client - File descriptor open on the client.
4201: # Returns:
4202: # 1 - Continue processing.
4203: # 0 - Exit.
4204: # Side effects:
4205: # reply is written to $client.
4206: #
4207:
4208: sub get_domain_handler {
4209: my ($cmd, $tail, $client) = @_;
4210:
4211: my $userinput = "$client:$tail";
4212:
4213: my ($udom,$namespace,$what)=split(/:/,$tail,3);
4214: chomp($what);
4215: my @queries=split(/\&/,$what);
4216: my $qresult='';
4217: my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
4218: if ($hashref) {
4219: for (my $i=0;$i<=$#queries;$i++) {
4220: $qresult.="$hashref->{$queries[$i]}&";
4221: }
4222: if (&untie_domain_hash($hashref)) {
4223: $qresult=~s/\&$//;
4224: &Reply($client, \$qresult, $userinput);
4225: } else {
4226: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
4227: "while attempting getdom\n",$userinput);
4228: }
4229: } else {
4230: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4231: "while attempting getdom\n",$userinput);
4232: }
4233:
4234: return 1;
4235: }
4236: ®ister_handler("getdom", \&get_domain_handler, 0, 1, 0);
4237:
4238: #
4239: # Puts an id to a domains id database.
4240: #
4241: # Parameters:
4242: # $cmd - The command that triggered us.
4243: # $tail - Remainder of the request other than the command. This is a
4244: # colon separated list containing:
4245: # $domain - The domain for which we are writing the id.
4246: # $pairs - The id info to write... this is and & separated list
4247: # of keyword=value.
4248: # $client - Socket open on the client.
4249: # Returns:
4250: # 1 - Continue processing.
4251: # Side effects:
4252: # reply is written to $client.
4253: #
4254: sub put_id_handler {
4255: my ($cmd,$tail,$client) = @_;
4256:
4257:
4258: my $userinput = "$cmd:$tail";
4259:
4260: my ($udom,$what)=split(/:/,$tail);
4261: chomp($what);
4262: my @pairs=split(/\&/,$what);
4263: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
4264: "P", $what);
4265: if ($hashref) {
4266: foreach my $pair (@pairs) {
4267: my ($key,$value)=split(/=/,$pair);
4268: $hashref->{$key}=$value;
4269: }
4270: if (&untie_domain_hash($hashref)) {
4271: &Reply($client, "ok\n", $userinput);
4272: } else {
4273: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4274: "while attempting idput\n", $userinput);
4275: }
4276: } else {
4277: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4278: "while attempting idput\n", $userinput);
4279: }
4280:
4281: return 1;
4282: }
4283: ®ister_handler("idput", \&put_id_handler, 0, 1, 0);
4284:
4285: #
4286: # Retrieves a set of id values from the id database.
4287: # Returns an & separated list of results, one for each requested id to the
4288: # client.
4289: #
4290: # Parameters:
4291: # $cmd - Command keyword that caused us to be dispatched.
4292: # $tail - Tail of the command. Consists of a colon separated:
4293: # domain - the domain whose id table we dump
4294: # ids Consists of an & separated list of
4295: # id keywords whose values will be fetched.
4296: # nonexisting keywords will have an empty value.
4297: # $client - Socket open on the client.
4298: #
4299: # Returns:
4300: # 1 - indicating processing should continue.
4301: # Side effects:
4302: # An & separated list of results is written to $client.
4303: #
4304: sub get_id_handler {
4305: my ($cmd, $tail, $client) = @_;
4306:
4307:
4308: my $userinput = "$client:$tail";
4309:
4310: my ($udom,$what)=split(/:/,$tail);
4311: chomp($what);
4312: my @queries=split(/\&/,$what);
4313: my $qresult='';
4314: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
4315: if ($hashref) {
4316: for (my $i=0;$i<=$#queries;$i++) {
4317: $qresult.="$hashref->{$queries[$i]}&";
4318: }
4319: if (&untie_domain_hash($hashref)) {
4320: $qresult=~s/\&$//;
4321: &Reply($client, \$qresult, $userinput);
4322: } else {
4323: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
4324: "while attempting idget\n",$userinput);
4325: }
4326: } else {
4327: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4328: "while attempting idget\n",$userinput);
4329: }
4330:
4331: return 1;
4332: }
4333: ®ister_handler("idget", \&get_id_handler, 0, 1, 0);
4334:
4335: #
4336: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database
4337: #
4338: # Parameters
4339: # $cmd - Command keyword that caused us to be dispatched.
4340: # $tail - Tail of the command. Consists of a colon separated:
4341: # domain - the domain whose dcmail we are recording
4342: # email Consists of key=value pair
4343: # where key is unique msgid
4344: # and value is message (in XML)
4345: # $client - Socket open on the client.
4346: #
4347: # Returns:
4348: # 1 - indicating processing should continue.
4349: # Side effects
4350: # reply is written to $client.
4351: #
4352: sub put_dcmail_handler {
4353: my ($cmd,$tail,$client) = @_;
4354: my $userinput = "$cmd:$tail";
4355:
4356: my ($udom,$what)=split(/:/,$tail);
4357: chomp($what);
4358: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
4359: if ($hashref) {
4360: my ($key,$value)=split(/=/,$what);
4361: $hashref->{$key}=$value;
4362: }
4363: if (&untie_domain_hash($hashref)) {
4364: &Reply($client, "ok\n", $userinput);
4365: } else {
4366: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4367: "while attempting dcmailput\n", $userinput);
4368: }
4369: return 1;
4370: }
4371: ®ister_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
4372:
4373: #
4374: # Retrieves broadcast e-mail from nohist_dcmail database
4375: # Returns to client an & separated list of key=value pairs,
4376: # where key is msgid and value is message information.
4377: #
4378: # Parameters
4379: # $cmd - Command keyword that caused us to be dispatched.
4380: # $tail - Tail of the command. Consists of a colon separated:
4381: # domain - the domain whose dcmail table we dump
4382: # startfilter - beginning of time window
4383: # endfilter - end of time window
4384: # sendersfilter - & separated list of username:domain
4385: # for senders to search for.
4386: # $client - Socket open on the client.
4387: #
4388: # Returns:
4389: # 1 - indicating processing should continue.
4390: # Side effects
4391: # reply (& separated list of msgid=messageinfo pairs) is
4392: # written to $client.
4393: #
4394: sub dump_dcmail_handler {
4395: my ($cmd, $tail, $client) = @_;
4396:
4397: my $userinput = "$cmd:$tail";
4398: my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
4399: chomp($sendersfilter);
4400: my @senders = ();
4401: if (defined($startfilter)) {
4402: $startfilter=&unescape($startfilter);
4403: } else {
4404: $startfilter='.';
4405: }
4406: if (defined($endfilter)) {
4407: $endfilter=&unescape($endfilter);
4408: } else {
4409: $endfilter='.';
4410: }
4411: if (defined($sendersfilter)) {
4412: $sendersfilter=&unescape($sendersfilter);
4413: @senders = map { &unescape($_) } split(/\&/,$sendersfilter);
4414: }
4415:
4416: my $qresult='';
4417: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
4418: if ($hashref) {
4419: while (my ($key,$value) = each(%$hashref)) {
4420: my $match = 1;
4421: my ($timestamp,$subj,$uname,$udom) =
4422: split(/:/,&unescape(&unescape($key)),5); # yes, twice really
4423: $subj = &unescape($subj);
4424: unless ($startfilter eq '.' || !defined($startfilter)) {
4425: if ($timestamp < $startfilter) {
4426: $match = 0;
4427: }
4428: }
4429: unless ($endfilter eq '.' || !defined($endfilter)) {
4430: if ($timestamp > $endfilter) {
4431: $match = 0;
4432: }
4433: }
4434: unless (@senders < 1) {
4435: unless (grep/^$uname:$udom$/,@senders) {
4436: $match = 0;
4437: }
4438: }
4439: if ($match == 1) {
4440: $qresult.=$key.'='.$value.'&';
4441: }
4442: }
4443: if (&untie_domain_hash($hashref)) {
4444: chop($qresult);
4445: &Reply($client, \$qresult, $userinput);
4446: } else {
4447: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4448: "while attempting dcmaildump\n", $userinput);
4449: }
4450: } else {
4451: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4452: "while attempting dcmaildump\n", $userinput);
4453: }
4454: return 1;
4455: }
4456:
4457: ®ister_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
4458:
4459: #
4460: # Puts domain roles in nohist_domainroles database
4461: #
4462: # Parameters
4463: # $cmd - Command keyword that caused us to be dispatched.
4464: # $tail - Tail of the command. Consists of a colon separated:
4465: # domain - the domain whose roles we are recording
4466: # role - Consists of key=value pair
4467: # where key is unique role
4468: # and value is start/end date information
4469: # $client - Socket open on the client.
4470: #
4471: # Returns:
4472: # 1 - indicating processing should continue.
4473: # Side effects
4474: # reply is written to $client.
4475: #
4476:
4477: sub put_domainroles_handler {
4478: my ($cmd,$tail,$client) = @_;
4479:
4480: my $userinput = "$cmd:$tail";
4481: my ($udom,$what)=split(/:/,$tail);
4482: chomp($what);
4483: my @pairs=split(/\&/,$what);
4484: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
4485: if ($hashref) {
4486: foreach my $pair (@pairs) {
4487: my ($key,$value)=split(/=/,$pair);
4488: $hashref->{$key}=$value;
4489: }
4490: if (&untie_domain_hash($hashref)) {
4491: &Reply($client, "ok\n", $userinput);
4492: } else {
4493: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4494: "while attempting domroleput\n", $userinput);
4495: }
4496: } else {
4497: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4498: "while attempting domroleput\n", $userinput);
4499: }
4500:
4501: return 1;
4502: }
4503:
4504: ®ister_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
4505:
4506: #
4507: # Retrieves domain roles from nohist_domainroles database
4508: # Returns to client an & separated list of key=value pairs,
4509: # where key is role and value is start and end date information.
4510: #
4511: # Parameters
4512: # $cmd - Command keyword that caused us to be dispatched.
4513: # $tail - Tail of the command. Consists of a colon separated:
4514: # domain - the domain whose domain roles table we dump
4515: # $client - Socket open on the client.
4516: #
4517: # Returns:
4518: # 1 - indicating processing should continue.
4519: # Side effects
4520: # reply (& separated list of role=start/end info pairs) is
4521: # written to $client.
4522: #
4523: sub dump_domainroles_handler {
4524: my ($cmd, $tail, $client) = @_;
4525:
4526: my $userinput = "$cmd:$tail";
4527: my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
4528: chomp($rolesfilter);
4529: my @roles = ();
4530: if (defined($startfilter)) {
4531: $startfilter=&unescape($startfilter);
4532: } else {
4533: $startfilter='.';
4534: }
4535: if (defined($endfilter)) {
4536: $endfilter=&unescape($endfilter);
4537: } else {
4538: $endfilter='.';
4539: }
4540: if (defined($rolesfilter)) {
4541: $rolesfilter=&unescape($rolesfilter);
4542: @roles = split(/\&/,$rolesfilter);
4543: }
4544:
4545: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
4546: if ($hashref) {
4547: my $qresult = '';
4548: while (my ($key,$value) = each(%$hashref)) {
4549: my $match = 1;
4550: my ($end,$start) = split(/:/,&unescape($value));
4551: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
4552: unless (@roles < 1) {
4553: unless (grep/^\Q$trole\E$/,@roles) {
4554: $match = 0;
4555: next;
4556: }
4557: }
4558: unless ($startfilter eq '.' || !defined($startfilter)) {
4559: if ((defined($start)) && ($start >= $startfilter)) {
4560: $match = 0;
4561: next;
4562: }
4563: }
4564: unless ($endfilter eq '.' || !defined($endfilter)) {
4565: if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
4566: $match = 0;
4567: next;
4568: }
4569: }
4570: if ($match == 1) {
4571: $qresult.=$key.'='.$value.'&';
4572: }
4573: }
4574: if (&untie_domain_hash($hashref)) {
4575: chop($qresult);
4576: &Reply($client, \$qresult, $userinput);
4577: } else {
4578: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4579: "while attempting domrolesdump\n", $userinput);
4580: }
4581: } else {
4582: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4583: "while attempting domrolesdump\n", $userinput);
4584: }
4585: return 1;
4586: }
4587:
4588: ®ister_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
4589:
4590:
4591: # Process the tmpput command I'm not sure what this does.. Seems to
4592: # create a file in the lonDaemons/tmp directory of the form $id.tmp
4593: # where Id is the client's ip concatenated with a sequence number.
4594: # The file will contain some value that is passed in. Is this e.g.
4595: # a login token?
4596: #
4597: # Parameters:
4598: # $cmd - The command that got us dispatched.
4599: # $tail - The remainder of the request following $cmd:
4600: # In this case this will be the contents of the file.
4601: # $client - Socket connected to the client.
4602: # Returns:
4603: # 1 indicating processing can continue.
4604: # Side effects:
4605: # A file is created in the local filesystem.
4606: # A reply is sent to the client.
4607: sub tmp_put_handler {
4608: my ($cmd, $what, $client) = @_;
4609:
4610: my $userinput = "$cmd:$what"; # Reconstruct for logging.
4611:
4612: my ($record,$context) = split(/:/,$what);
4613: if ($context ne '') {
4614: chomp($context);
4615: $context = &unescape($context);
4616: }
4617: my ($id,$store);
4618: $tmpsnum++;
4619: if ($context eq 'resetpw') {
4620: $id = &md5_hex(&md5_hex(time.{}.rand().$$));
4621: } else {
4622: $id = $$.'_'.$clientip.'_'.$tmpsnum;
4623: }
4624: $id=~s/\W/\_/g;
4625: $record=~s/\n//g;
4626: my $execdir=$perlvar{'lonDaemons'};
4627: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
4628: print $store $record;
4629: close $store;
4630: &Reply($client, \$id, $userinput);
4631: } else {
4632: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
4633: "while attempting tmpput\n", $userinput);
4634: }
4635: return 1;
4636:
4637: }
4638: ®ister_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
4639:
4640: # Processes the tmpget command. This command returns the contents
4641: # of a temporary resource file(?) created via tmpput.
4642: #
4643: # Paramters:
4644: # $cmd - Command that got us dispatched.
4645: # $id - Tail of the command, contain the id of the resource
4646: # we want to fetch.
4647: # $client - socket open on the client.
4648: # Return:
4649: # 1 - Inidcating processing can continue.
4650: # Side effects:
4651: # A reply is sent to the client.
4652: #
4653: sub tmp_get_handler {
4654: my ($cmd, $id, $client) = @_;
4655:
4656: my $userinput = "$cmd:$id";
4657:
4658:
4659: $id=~s/\W/\_/g;
4660: my $store;
4661: my $execdir=$perlvar{'lonDaemons'};
4662: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
4663: my $reply=<$store>;
4664: &Reply( $client, \$reply, $userinput);
4665: close $store;
4666: } else {
4667: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
4668: "while attempting tmpget\n", $userinput);
4669: }
4670:
4671: return 1;
4672: }
4673: ®ister_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
4674:
4675: #
4676: # Process the tmpdel command. This command deletes a temp resource
4677: # created by the tmpput command.
4678: #
4679: # Parameters:
4680: # $cmd - Command that got us here.
4681: # $id - Id of the temporary resource created.
4682: # $client - socket open on the client process.
4683: #
4684: # Returns:
4685: # 1 - Indicating processing should continue.
4686: # Side Effects:
4687: # A file is deleted
4688: # A reply is sent to the client.
4689: sub tmp_del_handler {
4690: my ($cmd, $id, $client) = @_;
4691:
4692: my $userinput= "$cmd:$id";
4693:
4694: chomp($id);
4695: $id=~s/\W/\_/g;
4696: my $execdir=$perlvar{'lonDaemons'};
4697: if (unlink("$execdir/tmp/$id.tmp")) {
4698: &Reply($client, "ok\n", $userinput);
4699: } else {
4700: &Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
4701: "while attempting tmpdel\n", $userinput);
4702: }
4703:
4704: return 1;
4705:
4706: }
4707: ®ister_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
4708:
4709: #
4710: # Processes the setannounce command. This command
4711: # creates a file named announce.txt in the top directory of
4712: # the documentn root and sets its contents. The announce.txt file is
4713: # printed in its entirety at the LonCAPA login page. Note:
4714: # once the announcement.txt fileis created it cannot be deleted.
4715: # However, setting the contents of the file to empty removes the
4716: # announcement from the login page of loncapa so who cares.
4717: #
4718: # Parameters:
4719: # $cmd - The command that got us dispatched.
4720: # $announcement - The text of the announcement.
4721: # $client - Socket open on the client process.
4722: # Retunrns:
4723: # 1 - Indicating request processing should continue
4724: # Side Effects:
4725: # The file {DocRoot}/announcement.txt is created.
4726: # A reply is sent to $client.
4727: #
4728: sub set_announce_handler {
4729: my ($cmd, $announcement, $client) = @_;
4730:
4731: my $userinput = "$cmd:$announcement";
4732:
4733: chomp($announcement);
4734: $announcement=&unescape($announcement);
4735: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
4736: '/announcement.txt')) {
4737: print $store $announcement;
4738: close $store;
4739: &Reply($client, "ok\n", $userinput);
4740: } else {
4741: &Failure($client, "error: ".($!+0)."\n", $userinput);
4742: }
4743:
4744: return 1;
4745: }
4746: ®ister_handler("setannounce", \&set_announce_handler, 0, 1, 0);
4747:
4748: #
4749: # Return the version of the daemon. This can be used to determine
4750: # the compatibility of cross version installations or, alternatively to
4751: # simply know who's out of date and who isn't. Note that the version
4752: # is returned concatenated with the tail.
4753: # Parameters:
4754: # $cmd - the request that dispatched to us.
4755: # $tail - Tail of the request (client's version?).
4756: # $client - Socket open on the client.
4757: #Returns:
4758: # 1 - continue processing requests.
4759: # Side Effects:
4760: # Replies with version to $client.
4761: sub get_version_handler {
4762: my ($cmd, $tail, $client) = @_;
4763:
4764: my $userinput = $cmd.$tail;
4765:
4766: &Reply($client, &version($userinput)."\n", $userinput);
4767:
4768:
4769: return 1;
4770: }
4771: ®ister_handler("version", \&get_version_handler, 0, 1, 0);
4772:
4773: # Set the current host and domain. This is used to support
4774: # multihomed systems. Each IP of the system, or even separate daemons
4775: # on the same IP can be treated as handling a separate lonCAPA virtual
4776: # machine. This command selects the virtual lonCAPA. The client always
4777: # knows the right one since it is lonc and it is selecting the domain/system
4778: # from the hosts.tab file.
4779: # Parameters:
4780: # $cmd - Command that dispatched us.
4781: # $tail - Tail of the command (domain/host requested).
4782: # $socket - Socket open on the client.
4783: #
4784: # Returns:
4785: # 1 - Indicates the program should continue to process requests.
4786: # Side-effects:
4787: # The default domain/system context is modified for this daemon.
4788: # a reply is sent to the client.
4789: #
4790: sub set_virtual_host_handler {
4791: my ($cmd, $tail, $socket) = @_;
4792:
4793: my $userinput ="$cmd:$tail";
4794:
4795: &Reply($client, &sethost($userinput)."\n", $userinput);
4796:
4797:
4798: return 1;
4799: }
4800: ®ister_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
4801:
4802: # Process a request to exit:
4803: # - "bye" is sent to the client.
4804: # - The client socket is shutdown and closed.
4805: # - We indicate to the caller that we should exit.
4806: # Formal Parameters:
4807: # $cmd - The command that got us here.
4808: # $tail - Tail of the command (empty).
4809: # $client - Socket open on the tail.
4810: # Returns:
4811: # 0 - Indicating the program should exit!!
4812: #
4813: sub exit_handler {
4814: my ($cmd, $tail, $client) = @_;
4815:
4816: my $userinput = "$cmd:$tail";
4817:
4818: &logthis("Client $clientip ($clientname) hanging up: $userinput");
4819: &Reply($client, "bye\n", $userinput);
4820: $client->shutdown(2); # shutdown the socket forcibly.
4821: $client->close();
4822:
4823: return 0;
4824: }
4825: ®ister_handler("exit", \&exit_handler, 0,1,1);
4826: ®ister_handler("init", \&exit_handler, 0,1,1);
4827: ®ister_handler("quit", \&exit_handler, 0,1,1);
4828:
4829: # Determine if auto-enrollment is enabled.
4830: # Note that the original had what I believe to be a defect.
4831: # The original returned 0 if the requestor was not a registerd client.
4832: # It should return "refused".
4833: # Formal Parameters:
4834: # $cmd - The command that invoked us.
4835: # $tail - The tail of the command (Extra command parameters.
4836: # $client - The socket open on the client that issued the request.
4837: # Returns:
4838: # 1 - Indicating processing should continue.
4839: #
4840: sub enrollment_enabled_handler {
4841: my ($cmd, $tail, $client) = @_;
4842: my $userinput = $cmd.":".$tail; # For logging purposes.
4843:
4844:
4845: my ($cdom) = split(/:/, $tail, 2); # Domain we're asking about.
4846:
4847: my $outcome = &localenroll::run($cdom);
4848: &Reply($client, \$outcome, $userinput);
4849:
4850: return 1;
4851: }
4852: ®ister_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
4853:
4854: #
4855: # Validate an institutional code used for a LON-CAPA course.
4856: #
4857: # Formal Parameters:
4858: # $cmd - The command request that got us dispatched.
4859: # $tail - The tail of the command. In this case,
4860: # this is a colon separated set of words that will be split
4861: # into:
4862: # $dom - The domain for which the check of
4863: # institutional course code will occur.
4864: #
4865: # $instcode - The institutional code for the course
4866: # being requested, or validated for rights
4867: # to request.
4868: #
4869: # $owner - The course requestor (who will be the
4870: # course owner, in the form username:domain
4871: #
4872: # $client - Socket open on the client.
4873: # Returns:
4874: # 1 - Indicating processing should continue.
4875: #
4876: sub validate_instcode_handler {
4877: my ($cmd, $tail, $client) = @_;
4878: my $userinput = "$cmd:$tail";
4879: my ($dom,$instcode,$owner) = split(/:/, $tail);
4880: $instcode = &unescape($instcode);
4881: $owner = &unescape($owner);
4882: my ($outcome,$description) =
4883: &localenroll::validate_instcode($dom,$instcode,$owner);
4884: my $result = &escape($outcome).'&'.&escape($description);
4885: &Reply($client, \$result, $userinput);
4886:
4887: return 1;
4888: }
4889: ®ister_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
4890:
4891: # Get the official sections for which auto-enrollment is possible.
4892: # Since the admin people won't know about 'unofficial sections'
4893: # we cannot auto-enroll on them.
4894: # Formal Parameters:
4895: # $cmd - The command request that got us dispatched here.
4896: # $tail - The remainder of the request. In our case this
4897: # will be split into:
4898: # $coursecode - The course name from the admin point of view.
4899: # $cdom - The course's domain(?).
4900: # $client - Socket open on the client.
4901: # Returns:
4902: # 1 - Indiciting processing should continue.
4903: #
4904: sub get_sections_handler {
4905: my ($cmd, $tail, $client) = @_;
4906: my $userinput = "$cmd:$tail";
4907:
4908: my ($coursecode, $cdom) = split(/:/, $tail);
4909: my @secs = &localenroll::get_sections($coursecode,$cdom);
4910: my $seclist = &escape(join(':',@secs));
4911:
4912: &Reply($client, \$seclist, $userinput);
4913:
4914:
4915: return 1;
4916: }
4917: ®ister_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
4918:
4919: # Validate the owner of a new course section.
4920: #
4921: # Formal Parameters:
4922: # $cmd - Command that got us dispatched.
4923: # $tail - the remainder of the command. For us this consists of a
4924: # colon separated string containing:
4925: # $inst - Course Id from the institutions point of view.
4926: # $owner - Proposed owner of the course.
4927: # $cdom - Domain of the course (from the institutions
4928: # point of view?)..
4929: # $client - Socket open on the client.
4930: #
4931: # Returns:
4932: # 1 - Processing should continue.
4933: #
4934: sub validate_course_owner_handler {
4935: my ($cmd, $tail, $client) = @_;
4936: my $userinput = "$cmd:$tail";
4937: my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
4938:
4939: $owner = &unescape($owner);
4940: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
4941: &Reply($client, \$outcome, $userinput);
4942:
4943:
4944:
4945: return 1;
4946: }
4947: ®ister_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
4948:
4949: #
4950: # Validate a course section in the official schedule of classes
4951: # from the institutions point of view (part of autoenrollment).
4952: #
4953: # Formal Parameters:
4954: # $cmd - The command request that got us dispatched.
4955: # $tail - The tail of the command. In this case,
4956: # this is a colon separated set of words that will be split
4957: # into:
4958: # $inst_course_id - The course/section id from the
4959: # institutions point of view.
4960: # $cdom - The domain from the institutions
4961: # point of view.
4962: # $client - Socket open on the client.
4963: # Returns:
4964: # 1 - Indicating processing should continue.
4965: #
4966: sub validate_course_section_handler {
4967: my ($cmd, $tail, $client) = @_;
4968: my $userinput = "$cmd:$tail";
4969: my ($inst_course_id, $cdom) = split(/:/, $tail);
4970:
4971: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
4972: &Reply($client, \$outcome, $userinput);
4973:
4974:
4975: return 1;
4976: }
4977: ®ister_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
4978:
4979: #
4980: # Validate course owner's access to enrollment data for specific class section.
4981: #
4982: #
4983: # Formal Parameters:
4984: # $cmd - The command request that got us dispatched.
4985: # $tail - The tail of the command. In this case this is a colon separated
4986: # set of words that will be split into:
4987: # $inst_class - Institutional code for the specific class section
4988: # $courseowner - The escaped username:domain of the course owner
4989: # $cdom - The domain of the course from the institution's
4990: # point of view.
4991: # $client - The socket open on the client.
4992: # Returns:
4993: # 1 - continue processing.
4994: #
4995:
4996: sub validate_class_access_handler {
4997: my ($cmd, $tail, $client) = @_;
4998: my $userinput = "$cmd:$tail";
4999: my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
5000: my $owners = &unescape($ownerlist);
5001: my $outcome;
5002: eval {
5003: local($SIG{__DIE__})='DEFAULT';
5004: $outcome=&localenroll::check_section($inst_class,$owners,$cdom);
5005: };
5006: &Reply($client,\$outcome, $userinput);
5007:
5008: return 1;
5009: }
5010: ®ister_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
5011:
5012: #
5013: # Create a password for a new LON-CAPA user added by auto-enrollment.
5014: # Only used for case where authentication method for new user is localauth
5015: #
5016: # Formal Parameters:
5017: # $cmd - The command request that got us dispatched.
5018: # $tail - The tail of the command. In this case this is a colon separated
5019: # set of words that will be split into:
5020: # $authparam - An authentication parameter (localauth parameter).
5021: # $cdom - The domain of the course from the institution's
5022: # point of view.
5023: # $client - The socket open on the client.
5024: # Returns:
5025: # 1 - continue processing.
5026: #
5027: sub create_auto_enroll_password_handler {
5028: my ($cmd, $tail, $client) = @_;
5029: my $userinput = "$cmd:$tail";
5030:
5031: my ($authparam, $cdom) = split(/:/, $userinput);
5032:
5033: my ($create_passwd,$authchk);
5034: ($authparam,
5035: $create_passwd,
5036: $authchk) = &localenroll::create_password($authparam,$cdom);
5037:
5038: &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
5039: $userinput);
5040:
5041:
5042: return 1;
5043: }
5044: ®ister_handler("autocreatepassword", \&create_auto_enroll_password_handler,
5045: 0, 1, 0);
5046:
5047: # Retrieve and remove temporary files created by/during autoenrollment.
5048: #
5049: # Formal Parameters:
5050: # $cmd - The command that got us dispatched.
5051: # $tail - The tail of the command. In our case this is a colon
5052: # separated list that will be split into:
5053: # $filename - The name of the file to remove.
5054: # The filename is given as a path relative to
5055: # the LonCAPA temp file directory.
5056: # $client - Socket open on the client.
5057: #
5058: # Returns:
5059: # 1 - Continue processing.
5060: sub retrieve_auto_file_handler {
5061: my ($cmd, $tail, $client) = @_;
5062: my $userinput = "cmd:$tail";
5063:
5064: my ($filename) = split(/:/, $tail);
5065:
5066: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
5067: if ( (-e $source) && ($filename ne '') ) {
5068: my $reply = '';
5069: if (open(my $fh,$source)) {
5070: while (<$fh>) {
5071: chomp($_);
5072: $_ =~ s/^\s+//g;
5073: $_ =~ s/\s+$//g;
5074: $reply .= $_;
5075: }
5076: close($fh);
5077: &Reply($client, &escape($reply)."\n", $userinput);
5078:
5079: # Does this have to be uncommented??!? (RF).
5080: #
5081: # unlink($source);
5082: } else {
5083: &Failure($client, "error\n", $userinput);
5084: }
5085: } else {
5086: &Failure($client, "error\n", $userinput);
5087: }
5088:
5089:
5090: return 1;
5091: }
5092: ®ister_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
5093:
5094: sub crsreq_checks_handler {
5095: my ($cmd, $tail, $client) = @_;
5096: my $userinput = "$cmd:$tail";
5097: my $dom = $tail;
5098: my $result;
5099: my @reqtypes = ('official','unofficial','community');
5100: eval {
5101: local($SIG{__DIE__})='DEFAULT';
5102: my %validations;
5103: my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
5104: \%validations);
5105: if ($response eq 'ok') {
5106: foreach my $key (keys(%validations)) {
5107: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
5108: }
5109: $result =~ s/\&$//;
5110: } else {
5111: $result = 'error';
5112: }
5113: };
5114: if (!$@) {
5115: &Reply($client, \$result, $userinput);
5116: } else {
5117: &Failure($client,"unknown_cmd\n",$userinput);
5118: }
5119: return 1;
5120: }
5121: ®ister_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
5122:
5123: sub validate_crsreq_handler {
5124: my ($cmd, $tail, $client) = @_;
5125: my $userinput = "$cmd:$tail";
5126: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = split(/:/, $tail);
5127: $instcode = &unescape($instcode);
5128: $owner = &unescape($owner);
5129: $crstype = &unescape($crstype);
5130: $inststatuslist = &unescape($inststatuslist);
5131: $instcode = &unescape($instcode);
5132: $instseclist = &unescape($instseclist);
5133: my $outcome;
5134: eval {
5135: local($SIG{__DIE__})='DEFAULT';
5136: $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
5137: $inststatuslist,$instcode,
5138: $instseclist);
5139: };
5140: if (!$@) {
5141: &Reply($client, \$outcome, $userinput);
5142: } else {
5143: &Failure($client,"unknown_cmd\n",$userinput);
5144: }
5145: return 1;
5146: }
5147: ®ister_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
5148:
5149: #
5150: # Read and retrieve institutional code format (for support form).
5151: # Formal Parameters:
5152: # $cmd - Command that dispatched us.
5153: # $tail - Tail of the command. In this case it conatins
5154: # the course domain and the coursename.
5155: # $client - Socket open on the client.
5156: # Returns:
5157: # 1 - Continue processing.
5158: #
5159: sub get_institutional_code_format_handler {
5160: my ($cmd, $tail, $client) = @_;
5161: my $userinput = "$cmd:$tail";
5162:
5163: my $reply;
5164: my($cdom,$course) = split(/:/,$tail);
5165: my @pairs = split/\&/,$course;
5166: my %instcodes = ();
5167: my %codes = ();
5168: my @codetitles = ();
5169: my %cat_titles = ();
5170: my %cat_order = ();
5171: foreach (@pairs) {
5172: my ($key,$value) = split/=/,$_;
5173: $instcodes{&unescape($key)} = &unescape($value);
5174: }
5175: my $formatreply = &localenroll::instcode_format($cdom,
5176: \%instcodes,
5177: \%codes,
5178: \@codetitles,
5179: \%cat_titles,
5180: \%cat_order);
5181: if ($formatreply eq 'ok') {
5182: my $codes_str = &Apache::lonnet::hash2str(%codes);
5183: my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
5184: my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
5185: my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
5186: &Reply($client,
5187: $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
5188: .$cat_order_str."\n",
5189: $userinput);
5190: } else {
5191: # this else branch added by RF since if not ok, lonc will
5192: # hang waiting on reply until timeout.
5193: #
5194: &Reply($client, "format_error\n", $userinput);
5195: }
5196:
5197: return 1;
5198: }
5199: ®ister_handler("autoinstcodeformat",
5200: \&get_institutional_code_format_handler,0,1,0);
5201:
5202: sub get_institutional_defaults_handler {
5203: my ($cmd, $tail, $client) = @_;
5204: my $userinput = "$cmd:$tail";
5205:
5206: my $dom = $tail;
5207: my %defaults_hash;
5208: my @code_order;
5209: my $outcome;
5210: eval {
5211: local($SIG{__DIE__})='DEFAULT';
5212: $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
5213: \@code_order);
5214: };
5215: if (!$@) {
5216: if ($outcome eq 'ok') {
5217: my $result='';
5218: while (my ($key,$value) = each(%defaults_hash)) {
5219: $result.=&escape($key).'='.&escape($value).'&';
5220: }
5221: $result .= 'code_order='.&escape(join('&',@code_order));
5222: &Reply($client,\$result,$userinput);
5223: } else {
5224: &Reply($client,"error\n", $userinput);
5225: }
5226: } else {
5227: &Failure($client,"unknown_cmd\n",$userinput);
5228: }
5229: }
5230: ®ister_handler("autoinstcodedefaults",
5231: \&get_institutional_defaults_handler,0,1,0);
5232:
5233: sub get_possible_instcodes_handler {
5234: my ($cmd, $tail, $client) = @_;
5235: my $userinput = "$cmd:$tail";
5236:
5237: my $reply;
5238: my $cdom = $tail;
5239: my (@codetitles,%cat_titles,%cat_order,@code_order);
5240: my $formatreply = &localenroll::possible_instcodes($cdom,
5241: \@codetitles,
5242: \%cat_titles,
5243: \%cat_order,
5244: \@code_order);
5245: if ($formatreply eq 'ok') {
5246: my $result = join('&',map {&escape($_);} (@codetitles)).':';
5247: $result .= join('&',map {&escape($_);} (@code_order)).':';
5248: foreach my $key (keys(%cat_titles)) {
5249: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
5250: }
5251: $result =~ s/\&$//;
5252: $result .= ':';
5253: foreach my $key (keys(%cat_order)) {
5254: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
5255: }
5256: $result =~ s/\&$//;
5257: &Reply($client,\$result,$userinput);
5258: } else {
5259: &Reply($client, "format_error\n", $userinput);
5260: }
5261: return 1;
5262: }
5263: ®ister_handler("autopossibleinstcodes",
5264: \&get_possible_instcodes_handler,0,1,0);
5265:
5266: sub get_institutional_user_rules {
5267: my ($cmd, $tail, $client) = @_;
5268: my $userinput = "$cmd:$tail";
5269: my $dom = &unescape($tail);
5270: my (%rules_hash,@rules_order);
5271: my $outcome;
5272: eval {
5273: local($SIG{__DIE__})='DEFAULT';
5274: $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
5275: };
5276: if (!$@) {
5277: if ($outcome eq 'ok') {
5278: my $result;
5279: foreach my $key (keys(%rules_hash)) {
5280: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
5281: }
5282: $result =~ s/\&$//;
5283: $result .= ':';
5284: if (@rules_order > 0) {
5285: foreach my $item (@rules_order) {
5286: $result .= &escape($item).'&';
5287: }
5288: }
5289: $result =~ s/\&$//;
5290: &Reply($client,\$result,$userinput);
5291: } else {
5292: &Reply($client,"error\n", $userinput);
5293: }
5294: } else {
5295: &Failure($client,"unknown_cmd\n",$userinput);
5296: }
5297: }
5298: ®ister_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
5299:
5300: sub get_institutional_id_rules {
5301: my ($cmd, $tail, $client) = @_;
5302: my $userinput = "$cmd:$tail";
5303: my $dom = &unescape($tail);
5304: my (%rules_hash,@rules_order);
5305: my $outcome;
5306: eval {
5307: local($SIG{__DIE__})='DEFAULT';
5308: $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
5309: };
5310: if (!$@) {
5311: if ($outcome eq 'ok') {
5312: my $result;
5313: foreach my $key (keys(%rules_hash)) {
5314: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
5315: }
5316: $result =~ s/\&$//;
5317: $result .= ':';
5318: if (@rules_order > 0) {
5319: foreach my $item (@rules_order) {
5320: $result .= &escape($item).'&';
5321: }
5322: }
5323: $result =~ s/\&$//;
5324: &Reply($client,\$result,$userinput);
5325: } else {
5326: &Reply($client,"error\n", $userinput);
5327: }
5328: } else {
5329: &Failure($client,"unknown_cmd\n",$userinput);
5330: }
5331: }
5332: ®ister_handler("instidrules",\&get_institutional_id_rules,0,1,0);
5333:
5334: sub get_institutional_selfcreate_rules {
5335: my ($cmd, $tail, $client) = @_;
5336: my $userinput = "$cmd:$tail";
5337: my $dom = &unescape($tail);
5338: my (%rules_hash,@rules_order);
5339: my $outcome;
5340: eval {
5341: local($SIG{__DIE__})='DEFAULT';
5342: $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
5343: };
5344: if (!$@) {
5345: if ($outcome eq 'ok') {
5346: my $result;
5347: foreach my $key (keys(%rules_hash)) {
5348: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
5349: }
5350: $result =~ s/\&$//;
5351: $result .= ':';
5352: if (@rules_order > 0) {
5353: foreach my $item (@rules_order) {
5354: $result .= &escape($item).'&';
5355: }
5356: }
5357: $result =~ s/\&$//;
5358: &Reply($client,\$result,$userinput);
5359: } else {
5360: &Reply($client,"error\n", $userinput);
5361: }
5362: } else {
5363: &Failure($client,"unknown_cmd\n",$userinput);
5364: }
5365: }
5366: ®ister_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
5367:
5368:
5369: sub institutional_username_check {
5370: my ($cmd, $tail, $client) = @_;
5371: my $userinput = "$cmd:$tail";
5372: my %rulecheck;
5373: my $outcome;
5374: my ($udom,$uname,@rules) = split(/:/,$tail);
5375: $udom = &unescape($udom);
5376: $uname = &unescape($uname);
5377: @rules = map {&unescape($_);} (@rules);
5378: eval {
5379: local($SIG{__DIE__})='DEFAULT';
5380: $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
5381: };
5382: if (!$@) {
5383: if ($outcome eq 'ok') {
5384: my $result='';
5385: foreach my $key (keys(%rulecheck)) {
5386: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
5387: }
5388: &Reply($client,\$result,$userinput);
5389: } else {
5390: &Reply($client,"error\n", $userinput);
5391: }
5392: } else {
5393: &Failure($client,"unknown_cmd\n",$userinput);
5394: }
5395: }
5396: ®ister_handler("instrulecheck",\&institutional_username_check,0,1,0);
5397:
5398: sub institutional_id_check {
5399: my ($cmd, $tail, $client) = @_;
5400: my $userinput = "$cmd:$tail";
5401: my %rulecheck;
5402: my $outcome;
5403: my ($udom,$id,@rules) = split(/:/,$tail);
5404: $udom = &unescape($udom);
5405: $id = &unescape($id);
5406: @rules = map {&unescape($_);} (@rules);
5407: eval {
5408: local($SIG{__DIE__})='DEFAULT';
5409: $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
5410: };
5411: if (!$@) {
5412: if ($outcome eq 'ok') {
5413: my $result='';
5414: foreach my $key (keys(%rulecheck)) {
5415: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
5416: }
5417: &Reply($client,\$result,$userinput);
5418: } else {
5419: &Reply($client,"error\n", $userinput);
5420: }
5421: } else {
5422: &Failure($client,"unknown_cmd\n",$userinput);
5423: }
5424: }
5425: ®ister_handler("instidrulecheck",\&institutional_id_check,0,1,0);
5426:
5427: sub institutional_selfcreate_check {
5428: my ($cmd, $tail, $client) = @_;
5429: my $userinput = "$cmd:$tail";
5430: my %rulecheck;
5431: my $outcome;
5432: my ($udom,$email,@rules) = split(/:/,$tail);
5433: $udom = &unescape($udom);
5434: $email = &unescape($email);
5435: @rules = map {&unescape($_);} (@rules);
5436: eval {
5437: local($SIG{__DIE__})='DEFAULT';
5438: $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
5439: };
5440: if (!$@) {
5441: if ($outcome eq 'ok') {
5442: my $result='';
5443: foreach my $key (keys(%rulecheck)) {
5444: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
5445: }
5446: &Reply($client,\$result,$userinput);
5447: } else {
5448: &Reply($client,"error\n", $userinput);
5449: }
5450: } else {
5451: &Failure($client,"unknown_cmd\n",$userinput);
5452: }
5453: }
5454: ®ister_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
5455:
5456: # Get domain specific conditions for import of student photographs to a course
5457: #
5458: # Retrieves information from photo_permission subroutine in localenroll.
5459: # Returns outcome (ok) if no processing errors, and whether course owner is
5460: # required to accept conditions of use (yes/no).
5461: #
5462: #
5463: sub photo_permission_handler {
5464: my ($cmd, $tail, $client) = @_;
5465: my $userinput = "$cmd:$tail";
5466: my $cdom = $tail;
5467: my ($perm_reqd,$conditions);
5468: my $outcome;
5469: eval {
5470: local($SIG{__DIE__})='DEFAULT';
5471: $outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
5472: \$conditions);
5473: };
5474: if (!$@) {
5475: &Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
5476: $userinput);
5477: } else {
5478: &Failure($client,"unknown_cmd\n",$userinput);
5479: }
5480: return 1;
5481: }
5482: ®ister_handler("autophotopermission",\&photo_permission_handler,0,1,0);
5483:
5484: #
5485: # Checks if student photo is available for a user in the domain, in the user's
5486: # directory (in /userfiles/internal/studentphoto.jpg).
5487: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
5488: # the student's photo.
5489:
5490: sub photo_check_handler {
5491: my ($cmd, $tail, $client) = @_;
5492: my $userinput = "$cmd:$tail";
5493: my ($udom,$uname,$pid) = split(/:/,$tail);
5494: $udom = &unescape($udom);
5495: $uname = &unescape($uname);
5496: $pid = &unescape($pid);
5497: my $path=&propath($udom,$uname).'/userfiles/internal/';
5498: if (!-e $path) {
5499: &mkpath($path);
5500: }
5501: my $response;
5502: my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
5503: $result .= ':'.$response;
5504: &Reply($client, &escape($result)."\n",$userinput);
5505: return 1;
5506: }
5507: ®ister_handler("autophotocheck",\&photo_check_handler,0,1,0);
5508:
5509: #
5510: # Retrieve information from localenroll about whether to provide a button
5511: # for users who have enbled import of student photos to initiate an
5512: # update of photo files for registered students. Also include
5513: # comment to display alongside button.
5514:
5515: sub photo_choice_handler {
5516: my ($cmd, $tail, $client) = @_;
5517: my $userinput = "$cmd:$tail";
5518: my $cdom = &unescape($tail);
5519: my ($update,$comment);
5520: eval {
5521: local($SIG{__DIE__})='DEFAULT';
5522: ($update,$comment) = &localenroll::manager_photo_update($cdom);
5523: };
5524: if (!$@) {
5525: &Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
5526: } else {
5527: &Failure($client,"unknown_cmd\n",$userinput);
5528: }
5529: return 1;
5530: }
5531: ®ister_handler("autophotochoice",\&photo_choice_handler,0,1,0);
5532:
5533: #
5534: # Gets a student's photo to exist (in the correct image type) in the user's
5535: # directory.
5536: # Formal Parameters:
5537: # $cmd - The command request that got us dispatched.
5538: # $tail - A colon separated set of words that will be split into:
5539: # $domain - student's domain
5540: # $uname - student username
5541: # $type - image type desired
5542: # $client - The socket open on the client.
5543: # Returns:
5544: # 1 - continue processing.
5545:
5546: sub student_photo_handler {
5547: my ($cmd, $tail, $client) = @_;
5548: my ($domain,$uname,$ext,$type) = split(/:/, $tail);
5549:
5550: my $path=&propath($domain,$uname). '/userfiles/internal/';
5551: my $filename = 'studentphoto.'.$ext;
5552: if ($type eq 'thumbnail') {
5553: $filename = 'studentphoto_tn.'.$ext;
5554: }
5555: if (-e $path.$filename) {
5556: &Reply($client,"ok\n","$cmd:$tail");
5557: return 1;
5558: }
5559: &mkpath($path);
5560: my $file;
5561: if ($type eq 'thumbnail') {
5562: eval {
5563: local($SIG{__DIE__})='DEFAULT';
5564: $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
5565: };
5566: } else {
5567: $file=&localstudentphoto::fetch($domain,$uname);
5568: }
5569: if (!$file) {
5570: &Failure($client,"unavailable\n","$cmd:$tail");
5571: return 1;
5572: }
5573: if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
5574: if (-e $path.$filename) {
5575: &Reply($client,"ok\n","$cmd:$tail");
5576: return 1;
5577: }
5578: &Failure($client,"unable_to_convert\n","$cmd:$tail");
5579: return 1;
5580: }
5581: ®ister_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
5582:
5583: sub inst_usertypes_handler {
5584: my ($cmd, $domain, $client) = @_;
5585: my $res;
5586: my $userinput = $cmd.":".$domain; # For logging purposes.
5587: my (%typeshash,@order,$result);
5588: eval {
5589: local($SIG{__DIE__})='DEFAULT';
5590: $result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
5591: };
5592: if ($result eq 'ok') {
5593: if (keys(%typeshash) > 0) {
5594: foreach my $key (keys(%typeshash)) {
5595: $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
5596: }
5597: }
5598: $res=~s/\&$//;
5599: $res .= ':';
5600: if (@order > 0) {
5601: foreach my $item (@order) {
5602: $res .= &escape($item).'&';
5603: }
5604: }
5605: $res=~s/\&$//;
5606: }
5607: &Reply($client, \$res, $userinput);
5608: return 1;
5609: }
5610: ®ister_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
5611:
5612: # mkpath makes all directories for a file, expects an absolute path with a
5613: # file or a trailing / if just a dir is passed
5614: # returns 1 on success 0 on failure
5615: sub mkpath {
5616: my ($file)=@_;
5617: my @parts=split(/\//,$file,-1);
5618: my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
5619: for (my $i=3;$i<= ($#parts-1);$i++) {
5620: $now.='/'.$parts[$i];
5621: if (!-e $now) {
5622: if (!mkdir($now,0770)) { return 0; }
5623: }
5624: }
5625: return 1;
5626: }
5627:
5628: #---------------------------------------------------------------
5629: #
5630: # Getting, decoding and dispatching requests:
5631: #
5632: #
5633: # Get a Request:
5634: # Gets a Request message from the client. The transaction
5635: # is defined as a 'line' of text. We remove the new line
5636: # from the text line.
5637: #
5638: sub get_request {
5639: my $input = <$client>;
5640: chomp($input);
5641:
5642: &Debug("get_request: Request = $input\n");
5643:
5644: &status('Processing '.$clientname.':'.$input);
5645:
5646: return $input;
5647: }
5648: #---------------------------------------------------------------
5649: #
5650: # Process a request. This sub should shrink as each action
5651: # gets farmed out into a separat sub that is registered
5652: # with the dispatch hash.
5653: #
5654: # Parameters:
5655: # user_input - The request received from the client (lonc).
5656: # Returns:
5657: # true to keep processing, false if caller should exit.
5658: #
5659: sub process_request {
5660: my ($userinput) = @_; # Easier for now to break style than to
5661: # fix all the userinput -> user_input.
5662: my $wasenc = 0; # True if request was encrypted.
5663: # ------------------------------------------------------------ See if encrypted
5664: # for command
5665: # sethost:<server>
5666: # <command>:<args>
5667: # we just send it to the processor
5668: # for
5669: # sethost:<server>:<command>:<args>
5670: # we do the implict set host and then do the command
5671: if ($userinput =~ /^sethost:/) {
5672: (my $cmd,my $newid,$userinput) = split(':',$userinput,3);
5673: if (defined($userinput)) {
5674: &sethost("$cmd:$newid");
5675: } else {
5676: $userinput = "$cmd:$newid";
5677: }
5678: }
5679:
5680: if ($userinput =~ /^enc/) {
5681: $userinput = decipher($userinput);
5682: $wasenc=1;
5683: if(!$userinput) { # Cipher not defined.
5684: &Failure($client, "error: Encrypted data without negotated key\n");
5685: return 0;
5686: }
5687: }
5688: Debug("process_request: $userinput\n");
5689:
5690: #
5691: # The 'correct way' to add a command to lond is now to
5692: # write a sub to execute it and Add it to the command dispatch
5693: # hash via a call to register_handler.. The comments to that
5694: # sub should give you enough to go on to show how to do this
5695: # along with the examples that are building up as this code
5696: # is getting refactored. Until all branches of the
5697: # if/elseif monster below have been factored out into
5698: # separate procesor subs, if the dispatch hash is missing
5699: # the command keyword, we will fall through to the remainder
5700: # of the if/else chain below in order to keep this thing in
5701: # working order throughout the transmogrification.
5702:
5703: my ($command, $tail) = split(/:/, $userinput, 2);
5704: chomp($command);
5705: chomp($tail);
5706: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
5707: $command =~ s/(\r)//; # And this too for parameterless commands.
5708: if(!$tail) {
5709: $tail =""; # defined but blank.
5710: }
5711:
5712: &Debug("Command received: $command, encoded = $wasenc");
5713:
5714: if(defined $Dispatcher{$command}) {
5715:
5716: my $dispatch_info = $Dispatcher{$command};
5717: my $handler = $$dispatch_info[0];
5718: my $need_encode = $$dispatch_info[1];
5719: my $client_types = $$dispatch_info[2];
5720: Debug("Matched dispatch hash: mustencode: $need_encode "
5721: ."ClientType $client_types");
5722:
5723: # Validate the request:
5724:
5725: my $ok = 1;
5726: my $requesterprivs = 0;
5727: if(&isClient()) {
5728: $requesterprivs |= $CLIENT_OK;
5729: }
5730: if(&isManager()) {
5731: $requesterprivs |= $MANAGER_OK;
5732: }
5733: if($need_encode && (!$wasenc)) {
5734: Debug("Must encode but wasn't: $need_encode $wasenc");
5735: $ok = 0;
5736: }
5737: if(($client_types & $requesterprivs) == 0) {
5738: Debug("Client not privileged to do this operation");
5739: $ok = 0;
5740: }
5741:
5742: if($ok) {
5743: Debug("Dispatching to handler $command $tail");
5744: my $keep_going = &$handler($command, $tail, $client);
5745: return $keep_going;
5746: } else {
5747: Debug("Refusing to dispatch because client did not match requirements");
5748: Failure($client, "refused\n", $userinput);
5749: return 1;
5750: }
5751:
5752: }
5753:
5754: print $client "unknown_cmd\n";
5755: # -------------------------------------------------------------------- complete
5756: Debug("process_request - returning 1");
5757: return 1;
5758: }
5759: #
5760: # Decipher encoded traffic
5761: # Parameters:
5762: # input - Encoded data.
5763: # Returns:
5764: # Decoded data or undef if encryption key was not yet negotiated.
5765: # Implicit input:
5766: # cipher - This global holds the negotiated encryption key.
5767: #
5768: sub decipher {
5769: my ($input) = @_;
5770: my $output = '';
5771:
5772:
5773: if($cipher) {
5774: my($enc, $enclength, $encinput) = split(/:/, $input);
5775: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
5776: $output .=
5777: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
5778: }
5779: return substr($output, 0, $enclength);
5780: } else {
5781: return undef;
5782: }
5783: }
5784:
5785: #
5786: # Register a command processor. This function is invoked to register a sub
5787: # to process a request. Once registered, the ProcessRequest sub can automatically
5788: # dispatch requests to an appropriate sub, and do the top level validity checking
5789: # as well:
5790: # - Is the keyword recognized.
5791: # - Is the proper client type attempting the request.
5792: # - Is the request encrypted if it has to be.
5793: # Parameters:
5794: # $request_name - Name of the request being registered.
5795: # This is the command request that will match
5796: # against the hash keywords to lookup the information
5797: # associated with the dispatch information.
5798: # $procedure - Reference to a sub to call to process the request.
5799: # All subs get called as follows:
5800: # Procedure($cmd, $tail, $replyfd, $key)
5801: # $cmd - the actual keyword that invoked us.
5802: # $tail - the tail of the request that invoked us.
5803: # $replyfd- File descriptor connected to the client
5804: # $must_encode - True if the request must be encoded to be good.
5805: # $client_ok - True if it's ok for a client to request this.
5806: # $manager_ok - True if it's ok for a manager to request this.
5807: # Side effects:
5808: # - On success, the Dispatcher hash has an entry added for the key $RequestName
5809: # - On failure, the program will die as it's a bad internal bug to try to
5810: # register a duplicate command handler.
5811: #
5812: sub register_handler {
5813: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
5814:
5815: # Don't allow duplication#
5816:
5817: if (defined $Dispatcher{$request_name}) {
5818: die "Attempting to define a duplicate request handler for $request_name\n";
5819: }
5820: # Build the client type mask:
5821:
5822: my $client_type_mask = 0;
5823: if($client_ok) {
5824: $client_type_mask |= $CLIENT_OK;
5825: }
5826: if($manager_ok) {
5827: $client_type_mask |= $MANAGER_OK;
5828: }
5829:
5830: # Enter the hash:
5831:
5832: my @entry = ($procedure, $must_encode, $client_type_mask);
5833:
5834: $Dispatcher{$request_name} = \@entry;
5835:
5836: }
5837:
5838:
5839: #------------------------------------------------------------------
5840:
5841:
5842:
5843:
5844: #
5845: # Convert an error return code from lcpasswd to a string value.
5846: #
5847: sub lcpasswdstrerror {
5848: my $ErrorCode = shift;
5849: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
5850: return "lcpasswd Unrecognized error return value ".$ErrorCode;
5851: } else {
5852: return $passwderrors[$ErrorCode];
5853: }
5854: }
5855:
5856: #
5857: # Convert an error return code from lcuseradd to a string value:
5858: #
5859: sub lcuseraddstrerror {
5860: my $ErrorCode = shift;
5861: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
5862: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
5863: } else {
5864: return $adderrors[$ErrorCode];
5865: }
5866: }
5867:
5868: # grabs exception and records it to log before exiting
5869: sub catchexception {
5870: my ($error)=@_;
5871: $SIG{'QUIT'}='DEFAULT';
5872: $SIG{__DIE__}='DEFAULT';
5873: &status("Catching exception");
5874: &logthis("<font color='red'>CRITICAL: "
5875: ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
5876: ."a crash with this error msg->[$error]</font>");
5877: &logthis('Famous last words: '.$status.' - '.$lastlog);
5878: if ($client) { print $client "error: $error\n"; }
5879: $server->close();
5880: die($error);
5881: }
5882: sub timeout {
5883: &status("Handling Timeout");
5884: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
5885: &catchexception('Timeout');
5886: }
5887: # -------------------------------- Set signal handlers to record abnormal exits
5888:
5889:
5890: $SIG{'QUIT'}=\&catchexception;
5891: $SIG{__DIE__}=\&catchexception;
5892:
5893: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
5894: &status("Read loncapa.conf and loncapa_apache.conf");
5895: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
5896: %perlvar=%{$perlvarref};
5897: undef $perlvarref;
5898:
5899: # ----------------------------- Make sure this process is running from user=www
5900: my $wwwid=getpwnam('www');
5901: if ($wwwid!=$<) {
5902: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
5903: my $subj="LON: $currenthostid User ID mismatch";
5904: system("echo 'User ID mismatch. lond must be run as user www.' |\
5905: mailto $emailto -s '$subj' > /dev/null");
5906: exit 1;
5907: }
5908:
5909: # --------------------------------------------- Check if other instance running
5910:
5911: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
5912:
5913: if (-e $pidfile) {
5914: my $lfh=IO::File->new("$pidfile");
5915: my $pide=<$lfh>;
5916: chomp($pide);
5917: if (kill 0 => $pide) { die "already running"; }
5918: }
5919:
5920: # ------------------------------------------------------------- Read hosts file
5921:
5922:
5923:
5924: # establish SERVER socket, bind and listen.
5925: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
5926: Type => SOCK_STREAM,
5927: Proto => 'tcp',
5928: Reuse => 1,
5929: Listen => 10 )
5930: or die "making socket: $@\n";
5931:
5932: # --------------------------------------------------------- Do global variables
5933:
5934: # global variables
5935:
5936: my %children = (); # keys are current child process IDs
5937:
5938: sub REAPER { # takes care of dead children
5939: $SIG{CHLD} = \&REAPER;
5940: &status("Handling child death");
5941: my $pid;
5942: do {
5943: $pid = waitpid(-1,&WNOHANG());
5944: if (defined($children{$pid})) {
5945: &logthis("Child $pid died");
5946: delete($children{$pid});
5947: } elsif ($pid > 0) {
5948: &logthis("Unknown Child $pid died");
5949: }
5950: } while ( $pid > 0 );
5951: foreach my $child (keys(%children)) {
5952: $pid = waitpid($child,&WNOHANG());
5953: if ($pid > 0) {
5954: &logthis("Child $child - $pid looks like we missed it's death");
5955: delete($children{$pid});
5956: }
5957: }
5958: &status("Finished Handling child death");
5959: }
5960:
5961: sub HUNTSMAN { # signal handler for SIGINT
5962: &status("Killing children (INT)");
5963: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
5964: kill 'INT' => keys %children;
5965: &logthis("Free socket: ".shutdown($server,2)); # free up socket
5966: my $execdir=$perlvar{'lonDaemons'};
5967: unlink("$execdir/logs/lond.pid");
5968: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
5969: &status("Done killing children");
5970: exit; # clean up with dignity
5971: }
5972:
5973: sub HUPSMAN { # signal handler for SIGHUP
5974: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
5975: &status("Killing children for restart (HUP)");
5976: kill 'INT' => keys %children;
5977: &logthis("Free socket: ".shutdown($server,2)); # free up socket
5978: &logthis("<font color='red'>CRITICAL: Restarting</font>");
5979: my $execdir=$perlvar{'lonDaemons'};
5980: unlink("$execdir/logs/lond.pid");
5981: &status("Restarting self (HUP)");
5982: exec("$execdir/lond"); # here we go again
5983: }
5984:
5985: #
5986: # Reload the Apache daemon's state.
5987: # This is done by invoking /home/httpd/perl/apachereload
5988: # a setuid perl script that can be root for us to do this job.
5989: #
5990: sub ReloadApache {
5991: my $execdir = $perlvar{'lonDaemons'};
5992: my $script = $execdir."/apachereload";
5993: system($script);
5994: }
5995:
5996: #
5997: # Called in response to a USR2 signal.
5998: # - Reread hosts.tab
5999: # - All children connected to hosts that were removed from hosts.tab
6000: # are killed via SIGINT
6001: # - All children connected to previously existing hosts are sent SIGUSR1
6002: # - Our internal hosts hash is updated to reflect the new contents of
6003: # hosts.tab causing connections from hosts added to hosts.tab to
6004: # now be honored.
6005: #
6006: sub UpdateHosts {
6007: &status("Reload hosts.tab");
6008: logthis('<font color="blue"> Updating connections </font>');
6009: #
6010: # The %children hash has the set of IP's we currently have children
6011: # on. These need to be matched against records in the hosts.tab
6012: # Any ip's no longer in the table get killed off they correspond to
6013: # either dropped or changed hosts. Note that the re-read of the table
6014: # will take care of new and changed hosts as connections come into being.
6015:
6016: &Apache::lonnet::reset_hosts_info();
6017:
6018: foreach my $child (keys(%children)) {
6019: my $childip = $children{$child};
6020: if ($childip ne '127.0.0.1'
6021: && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
6022: logthis('<font color="blue"> UpdateHosts killing child '
6023: ." $child for ip $childip </font>");
6024: kill('INT', $child);
6025: } else {
6026: logthis('<font color="green"> keeping child for ip '
6027: ." $childip (pid=$child) </font>");
6028: }
6029: }
6030: ReloadApache;
6031: &status("Finished reloading hosts.tab");
6032: }
6033:
6034:
6035: sub checkchildren {
6036: &status("Checking on the children (sending signals)");
6037: &initnewstatus();
6038: &logstatus();
6039: &logthis('Going to check on the children');
6040: my $docdir=$perlvar{'lonDocRoot'};
6041: foreach (sort keys %children) {
6042: #sleep 1;
6043: unless (kill 'USR1' => $_) {
6044: &logthis ('Child '.$_.' is dead');
6045: &logstatus($$.' is dead');
6046: delete($children{$_});
6047: }
6048: }
6049: sleep 5;
6050: $SIG{ALRM} = sub { Debug("timeout");
6051: die "timeout"; };
6052: $SIG{__DIE__} = 'DEFAULT';
6053: &status("Checking on the children (waiting for reports)");
6054: foreach (sort keys %children) {
6055: unless (-e "$docdir/lon-status/londchld/$_.txt") {
6056: eval {
6057: alarm(300);
6058: &logthis('Child '.$_.' did not respond');
6059: kill 9 => $_;
6060: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
6061: #$subj="LON: $currenthostid killed lond process $_";
6062: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
6063: #$execdir=$perlvar{'lonDaemons'};
6064: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
6065: delete($children{$_});
6066: alarm(0);
6067: }
6068: }
6069: }
6070: $SIG{ALRM} = 'DEFAULT';
6071: $SIG{__DIE__} = \&catchexception;
6072: &status("Finished checking children");
6073: &logthis('Finished Checking children');
6074: }
6075:
6076: # --------------------------------------------------------------------- Logging
6077:
6078: sub logthis {
6079: my $message=shift;
6080: my $execdir=$perlvar{'lonDaemons'};
6081: my $fh=IO::File->new(">>$execdir/logs/lond.log");
6082: my $now=time;
6083: my $local=localtime($now);
6084: $lastlog=$local.': '.$message;
6085: print $fh "$local ($$): $message\n";
6086: }
6087:
6088: # ------------------------- Conditional log if $DEBUG true.
6089: sub Debug {
6090: my $message = shift;
6091: if($DEBUG) {
6092: &logthis($message);
6093: }
6094: }
6095:
6096: #
6097: # Sub to do replies to client.. this gives a hook for some
6098: # debug tracing too:
6099: # Parameters:
6100: # fd - File open on client.
6101: # reply - Text to send to client.
6102: # request - Original request from client.
6103: #
6104: sub Reply {
6105: my ($fd, $reply, $request) = @_;
6106: if (ref($reply)) {
6107: print $fd $$reply;
6108: print $fd "\n";
6109: if ($DEBUG) { Debug("Request was $request Reply was $$reply"); }
6110: } else {
6111: print $fd $reply;
6112: if ($DEBUG) { Debug("Request was $request Reply was $reply"); }
6113: }
6114: $Transactions++;
6115: }
6116:
6117:
6118: #
6119: # Sub to report a failure.
6120: # This function:
6121: # - Increments the failure statistic counters.
6122: # - Invokes Reply to send the error message to the client.
6123: # Parameters:
6124: # fd - File descriptor open on the client
6125: # reply - Reply text to emit.
6126: # request - The original request message (used by Reply
6127: # to debug if that's enabled.
6128: # Implicit outputs:
6129: # $Failures- The number of failures is incremented.
6130: # Reply (invoked here) sends a message to the
6131: # client:
6132: #
6133: sub Failure {
6134: my $fd = shift;
6135: my $reply = shift;
6136: my $request = shift;
6137:
6138: $Failures++;
6139: Reply($fd, $reply, $request); # That's simple eh?
6140: }
6141: # ------------------------------------------------------------------ Log status
6142:
6143: sub logstatus {
6144: &status("Doing logging");
6145: my $docdir=$perlvar{'lonDocRoot'};
6146: {
6147: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
6148: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
6149: $fh->close();
6150: }
6151: &status("Finished $$.txt");
6152: {
6153: open(LOG,">>$docdir/lon-status/londstatus.txt");
6154: flock(LOG,LOCK_EX);
6155: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
6156: .$status."\t".$lastlog."\t $keymode\n";
6157: flock(LOG,LOCK_UN);
6158: close(LOG);
6159: }
6160: &status("Finished logging");
6161: }
6162:
6163: sub initnewstatus {
6164: my $docdir=$perlvar{'lonDocRoot'};
6165: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
6166: my $now=time;
6167: my $local=localtime($now);
6168: print $fh "LOND status $local - parent $$\n\n";
6169: opendir(DIR,"$docdir/lon-status/londchld");
6170: while (my $filename=readdir(DIR)) {
6171: unlink("$docdir/lon-status/londchld/$filename");
6172: }
6173: closedir(DIR);
6174: }
6175:
6176: # -------------------------------------------------------------- Status setting
6177:
6178: sub status {
6179: my $what=shift;
6180: my $now=time;
6181: my $local=localtime($now);
6182: $status=$local.': '.$what;
6183: $0='lond: '.$what.' '.$local;
6184: }
6185:
6186: # -------------------------------------------------------------- Talk to lonsql
6187:
6188: sub sql_reply {
6189: my ($cmd)=@_;
6190: my $answer=&sub_sql_reply($cmd);
6191: if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
6192: return $answer;
6193: }
6194:
6195: sub sub_sql_reply {
6196: my ($cmd)=@_;
6197: my $unixsock="mysqlsock";
6198: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
6199: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
6200: Type => SOCK_STREAM,
6201: Timeout => 10)
6202: or return "con_lost";
6203: print $sclient "$cmd:$currentdomainid\n";
6204: my $answer=<$sclient>;
6205: chomp($answer);
6206: if (!$answer) { $answer="con_lost"; }
6207: return $answer;
6208: }
6209:
6210: # --------------------------------------- Is this the home server of an author?
6211:
6212: sub ishome {
6213: my $author=shift;
6214: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
6215: my ($udom,$uname)=split(/\//,$author);
6216: my $proname=propath($udom,$uname);
6217: if (-e $proname) {
6218: return 'owner';
6219: } else {
6220: return 'not_owner';
6221: }
6222: }
6223:
6224: # ======================================================= Continue main program
6225: # ---------------------------------------------------- Fork once and dissociate
6226:
6227: my $fpid=fork;
6228: exit if $fpid;
6229: die "Couldn't fork: $!" unless defined ($fpid);
6230:
6231: POSIX::setsid() or die "Can't start new session: $!";
6232:
6233: # ------------------------------------------------------- Write our PID on disk
6234:
6235: my $execdir=$perlvar{'lonDaemons'};
6236: open (PIDSAVE,">$execdir/logs/lond.pid");
6237: print PIDSAVE "$$\n";
6238: close(PIDSAVE);
6239: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
6240: &status('Starting');
6241:
6242:
6243:
6244: # ----------------------------------------------------- Install signal handlers
6245:
6246:
6247: $SIG{CHLD} = \&REAPER;
6248: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
6249: $SIG{HUP} = \&HUPSMAN;
6250: $SIG{USR1} = \&checkchildren;
6251: $SIG{USR2} = \&UpdateHosts;
6252:
6253: # Read the host hashes:
6254: &Apache::lonnet::load_hosts_tab();
6255:
6256: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
6257:
6258: # --------------------------------------------------------------
6259: # Accept connections. When a connection comes in, it is validated
6260: # and if good, a child process is created to process transactions
6261: # along the connection.
6262:
6263: while (1) {
6264: &status('Starting accept');
6265: $client = $server->accept() or next;
6266: &status('Accepted '.$client.' off to spawn');
6267: make_new_child($client);
6268: &status('Finished spawning');
6269: }
6270:
6271: sub make_new_child {
6272: my $pid;
6273: # my $cipher; # Now global
6274: my $sigset;
6275:
6276: $client = shift;
6277: &status('Starting new child '.$client);
6278: &logthis('<font color="green"> Attempting to start child ('.$client.
6279: ")</font>");
6280: # block signal for fork
6281: $sigset = POSIX::SigSet->new(SIGINT);
6282: sigprocmask(SIG_BLOCK, $sigset)
6283: or die "Can't block SIGINT for fork: $!\n";
6284:
6285: die "fork: $!" unless defined ($pid = fork);
6286:
6287: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
6288: # connection liveness.
6289:
6290: #
6291: # Figure out who we're talking to so we can record the peer in
6292: # the pid hash.
6293: #
6294: my $caller = getpeername($client);
6295: my ($port,$iaddr);
6296: if (defined($caller) && length($caller) > 0) {
6297: ($port,$iaddr)=unpack_sockaddr_in($caller);
6298: } else {
6299: &logthis("Unable to determine who caller was, getpeername returned nothing");
6300: }
6301: if (defined($iaddr)) {
6302: $clientip = inet_ntoa($iaddr);
6303: Debug("Connected with $clientip");
6304: } else {
6305: &logthis("Unable to determine clientip");
6306: $clientip='Unavailable';
6307: }
6308:
6309: if ($pid) {
6310: # Parent records the child's birth and returns.
6311: sigprocmask(SIG_UNBLOCK, $sigset)
6312: or die "Can't unblock SIGINT for fork: $!\n";
6313: $children{$pid} = $clientip;
6314: &status('Started child '.$pid);
6315: close($client);
6316: return;
6317: } else {
6318: # Child can *not* return from this subroutine.
6319: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
6320: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
6321: #don't get intercepted
6322: $SIG{USR1}= \&logstatus;
6323: $SIG{ALRM}= \&timeout;
6324: $lastlog='Forked ';
6325: $status='Forked';
6326:
6327: # unblock signals
6328: sigprocmask(SIG_UNBLOCK, $sigset)
6329: or die "Can't unblock SIGINT for fork: $!\n";
6330:
6331: # my $tmpsnum=0; # Now global
6332: #---------------------------------------------------- kerberos 5 initialization
6333: &Authen::Krb5::init_context();
6334: unless (($dist eq 'fedora5') || ($dist eq 'fedora4') ||
6335: ($dist eq 'fedora6') || ($dist eq 'suse9.3')) {
6336: &Authen::Krb5::init_ets();
6337: }
6338:
6339: &status('Accepted connection');
6340: # =============================================================================
6341: # do something with the connection
6342: # -----------------------------------------------------------------------------
6343: # see if we know client and 'check' for spoof IP by ineffective challenge
6344:
6345: my $outsideip=$clientip;
6346: if ($clientip eq '127.0.0.1') {
6347: $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
6348: }
6349: &ReadManagerTable();
6350: my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
6351: my $ismanager=($managers{$outsideip} ne undef);
6352: $clientname = "[unknown]";
6353: if($clientrec) { # Establish client type.
6354: $ConnectionType = "client";
6355: $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
6356: if($ismanager) {
6357: $ConnectionType = "both";
6358: }
6359: } else {
6360: $ConnectionType = "manager";
6361: $clientname = $managers{$outsideip};
6362: }
6363: my $clientok;
6364:
6365: if ($clientrec || $ismanager) {
6366: &status("Waiting for init from $clientip $clientname");
6367: &logthis('<font color="yellow">INFO: Connection, '.
6368: $clientip.
6369: " ($clientname) connection type = $ConnectionType </font>" );
6370: &status("Connecting $clientip ($clientname))");
6371: my $remotereq=<$client>;
6372: chomp($remotereq);
6373: Debug("Got init: $remotereq");
6374:
6375: if ($remotereq =~ /^init/) {
6376: &sethost("sethost:$perlvar{'lonHostID'}");
6377: #
6378: # If the remote is attempting a local init... give that a try:
6379: #
6380: (my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
6381:
6382: # If the connection type is ssl, but I didn't get my
6383: # certificate files yet, then I'll drop back to
6384: # insecure (if allowed).
6385:
6386: if($inittype eq "ssl") {
6387: my ($ca, $cert) = lonssl::CertificateFile;
6388: my $kfile = lonssl::KeyFile;
6389: if((!$ca) ||
6390: (!$cert) ||
6391: (!$kfile)) {
6392: $inittype = ""; # This forces insecure attempt.
6393: &logthis("<font color=\"blue\"> Certificates not "
6394: ."installed -- trying insecure auth</font>");
6395: } else { # SSL certificates are in place so
6396: } # Leave the inittype alone.
6397: }
6398:
6399: if($inittype eq "local") {
6400: $clientversion = $perlvar{'lonVersion'};
6401: my $key = LocalConnection($client, $remotereq);
6402: if($key) {
6403: Debug("Got local key $key");
6404: $clientok = 1;
6405: my $cipherkey = pack("H32", $key);
6406: $cipher = new IDEA($cipherkey);
6407: print $client "ok:local\n";
6408: &logthis('<font color="green">'
6409: . "Successful local authentication </font>");
6410: $keymode = "local"
6411: } else {
6412: Debug("Failed to get local key");
6413: $clientok = 0;
6414: shutdown($client, 3);
6415: close $client;
6416: }
6417: } elsif ($inittype eq "ssl") {
6418: my $key = SSLConnection($client);
6419: if ($key) {
6420: $clientok = 1;
6421: my $cipherkey = pack("H32", $key);
6422: $cipher = new IDEA($cipherkey);
6423: &logthis('<font color="green">'
6424: ."Successfull ssl authentication with $clientname </font>");
6425: $keymode = "ssl";
6426:
6427: } else {
6428: $clientok = 0;
6429: close $client;
6430: }
6431:
6432: } else {
6433: my $ok = InsecureConnection($client);
6434: if($ok) {
6435: $clientok = 1;
6436: &logthis('<font color="green">'
6437: ."Successful insecure authentication with $clientname </font>");
6438: print $client "ok\n";
6439: $keymode = "insecure";
6440: } else {
6441: &logthis('<font color="yellow">'
6442: ."Attempted insecure connection disallowed </font>");
6443: close $client;
6444: $clientok = 0;
6445:
6446: }
6447: }
6448: } else {
6449: &logthis(
6450: "<font color='blue'>WARNING: "
6451: ."$clientip failed to initialize: >$remotereq< </font>");
6452: &status('No init '.$clientip);
6453: }
6454:
6455: } else {
6456: &logthis(
6457: "<font color='blue'>WARNING: Unknown client $clientip</font>");
6458: &status('Hung up on '.$clientip);
6459: }
6460:
6461: if ($clientok) {
6462: # ---------------- New known client connecting, could mean machine online again
6463: if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip
6464: && $clientip ne '127.0.0.1') {
6465: &Apache::lonnet::reconlonc($clientname);
6466: }
6467: &logthis("<font color='green'>Established connection: $clientname</font>");
6468: &status('Will listen to '.$clientname);
6469: # ------------------------------------------------------------ Process requests
6470: my $keep_going = 1;
6471: my $user_input;
6472: while(($user_input = get_request) && $keep_going) {
6473: alarm(120);
6474: Debug("Main: Got $user_input\n");
6475: $keep_going = &process_request($user_input);
6476: alarm(0);
6477: &status('Listening to '.$clientname." ($keymode)");
6478: }
6479:
6480: # --------------------------------------------- client unknown or fishy, refuse
6481: } else {
6482: print $client "refused\n";
6483: $client->close();
6484: &logthis("<font color='blue'>WARNING: "
6485: ."Rejected client $clientip, closing connection</font>");
6486: }
6487: }
6488:
6489: # =============================================================================
6490:
6491: &logthis("<font color='red'>CRITICAL: "
6492: ."Disconnect from $clientip ($clientname)</font>");
6493:
6494:
6495: # this exit is VERY important, otherwise the child will become
6496: # a producer of more and more children, forking yourself into
6497: # process death.
6498: exit;
6499:
6500: }
6501: #
6502: # Determine if a user is an author for the indicated domain.
6503: #
6504: # Parameters:
6505: # domain - domain to check in .
6506: # user - Name of user to check.
6507: #
6508: # Return:
6509: # 1 - User is an author for domain.
6510: # 0 - User is not an author for domain.
6511: sub is_author {
6512: my ($domain, $user) = @_;
6513:
6514: &Debug("is_author: $user @ $domain");
6515:
6516: my $hashref = &tie_user_hash($domain, $user, "roles",
6517: &GDBM_READER());
6518:
6519: # Author role should show up as a key /domain/_au
6520:
6521: my $key = "/$domain/_au";
6522: my $value;
6523: if (defined($hashref)) {
6524: $value = $hashref->{$key};
6525: }
6526:
6527: if(defined($value)) {
6528: &Debug("$user @ $domain is an author");
6529: }
6530:
6531: return defined($value);
6532: }
6533: #
6534: # Checks to see if the input roleput request was to set
6535: # an author role. If so, invokes the lchtmldir script to set
6536: # up a correct public_html
6537: # Parameters:
6538: # request - The request sent to the rolesput subchunk.
6539: # We're looking for /domain/_au
6540: # domain - The domain in which the user is having roles doctored.
6541: # user - Name of the user for which the role is being put.
6542: # authtype - The authentication type associated with the user.
6543: #
6544: sub manage_permissions {
6545: my ($request, $domain, $user, $authtype) = @_;
6546:
6547: &Debug("manage_permissions: $request $domain $user $authtype");
6548:
6549: # See if the request is of the form /$domain/_au
6550: if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
6551: my $execdir = $perlvar{'lonDaemons'};
6552: my $userhome= "/home/$user" ;
6553: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
6554: &Debug("Setting homedir permissions for $userhome");
6555: system("$execdir/lchtmldir $userhome $user $authtype");
6556: }
6557: }
6558:
6559:
6560: #
6561: # Return the full path of a user password file, whether it exists or not.
6562: # Parameters:
6563: # domain - Domain in which the password file lives.
6564: # user - name of the user.
6565: # Returns:
6566: # Full passwd path:
6567: #
6568: sub password_path {
6569: my ($domain, $user) = @_;
6570: return &propath($domain, $user).'/passwd';
6571: }
6572:
6573: # Password Filename
6574: # Returns the path to a passwd file given domain and user... only if
6575: # it exists.
6576: # Parameters:
6577: # domain - Domain in which to search.
6578: # user - username.
6579: # Returns:
6580: # - If the password file exists returns its path.
6581: # - If the password file does not exist, returns undefined.
6582: #
6583: sub password_filename {
6584: my ($domain, $user) = @_;
6585:
6586: Debug ("PasswordFilename called: dom = $domain user = $user");
6587:
6588: my $path = &password_path($domain, $user);
6589: Debug("PasswordFilename got path: $path");
6590: if(-e $path) {
6591: return $path;
6592: } else {
6593: return undef;
6594: }
6595: }
6596:
6597: #
6598: # Rewrite the contents of the user's passwd file.
6599: # Parameters:
6600: # domain - domain of the user.
6601: # name - User's name.
6602: # contents - New contents of the file.
6603: # Returns:
6604: # 0 - Failed.
6605: # 1 - Success.
6606: #
6607: sub rewrite_password_file {
6608: my ($domain, $user, $contents) = @_;
6609:
6610: my $file = &password_filename($domain, $user);
6611: if (defined $file) {
6612: my $pf = IO::File->new(">$file");
6613: if($pf) {
6614: print $pf "$contents\n";
6615: return 1;
6616: } else {
6617: return 0;
6618: }
6619: } else {
6620: return 0;
6621: }
6622:
6623: }
6624:
6625: #
6626: # get_auth_type - Determines the authorization type of a user in a domain.
6627:
6628: # Returns the authorization type or nouser if there is no such user.
6629: #
6630: sub get_auth_type {
6631: my ($domain, $user) = @_;
6632:
6633: Debug("get_auth_type( $domain, $user ) \n");
6634: my $proname = &propath($domain, $user);
6635: my $passwdfile = "$proname/passwd";
6636: if( -e $passwdfile ) {
6637: my $pf = IO::File->new($passwdfile);
6638: my $realpassword = <$pf>;
6639: chomp($realpassword);
6640: Debug("Password info = $realpassword\n");
6641: my ($authtype, $contentpwd) = split(/:/, $realpassword);
6642: Debug("Authtype = $authtype, content = $contentpwd\n");
6643: return "$authtype:$contentpwd";
6644: } else {
6645: Debug("Returning nouser");
6646: return "nouser";
6647: }
6648: }
6649:
6650: #
6651: # Validate a user given their domain, name and password. This utility
6652: # function is used by both AuthenticateHandler and ChangePasswordHandler
6653: # to validate the login credentials of a user.
6654: # Parameters:
6655: # $domain - The domain being logged into (this is required due to
6656: # the capability for multihomed systems.
6657: # $user - The name of the user being validated.
6658: # $password - The user's propoposed password.
6659: #
6660: # Returns:
6661: # 1 - The domain,user,pasword triplet corresponds to a valid
6662: # user.
6663: # 0 - The domain,user,password triplet is not a valid user.
6664: #
6665: sub validate_user {
6666: my ($domain, $user, $password, $checkdefauth) = @_;
6667:
6668: # Why negative ~pi you may well ask? Well this function is about
6669: # authentication, and therefore very important to get right.
6670: # I've initialized the flag that determines whether or not I've
6671: # validated correctly to a value it's not supposed to get.
6672: # At the end of this function. I'll ensure that it's not still that
6673: # value so we don't just wind up returning some accidental value
6674: # as a result of executing an unforseen code path that
6675: # did not set $validated. At the end of valid execution paths,
6676: # validated shoule be 1 for success or 0 for failuer.
6677:
6678: my $validated = -3.14159;
6679:
6680: # How we authenticate is determined by the type of authentication
6681: # the user has been assigned. If the authentication type is
6682: # "nouser", the user does not exist so we will return 0.
6683:
6684: my $contents = &get_auth_type($domain, $user);
6685: my ($howpwd, $contentpwd) = split(/:/, $contents);
6686:
6687: my $null = pack("C",0); # Used by kerberos auth types.
6688:
6689: if ($howpwd eq 'nouser') {
6690: if ($checkdefauth) {
6691: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
6692: if ($domdefaults{'auth_def'} eq 'localauth') {
6693: $howpwd = $domdefaults{'auth_def'};
6694: $contentpwd = $domdefaults{'auth_arg_def'};
6695: } elsif ((($domdefaults{'auth_def'} eq 'krb4') ||
6696: ($domdefaults{'auth_def'} eq 'krb5')) &&
6697: ($domdefaults{'auth_arg_def'} ne '')) {
6698: $howpwd = $domdefaults{'auth_def'};
6699: $contentpwd = $domdefaults{'auth_arg_def'};
6700: }
6701: }
6702: }
6703: if ($howpwd ne 'nouser') {
6704: if($howpwd eq "internal") { # Encrypted is in local password file.
6705: $validated = (crypt($password, $contentpwd) eq $contentpwd);
6706: }
6707: elsif ($howpwd eq "unix") { # User is a normal unix user.
6708: $contentpwd = (getpwnam($user))[1];
6709: if($contentpwd) {
6710: if($contentpwd eq 'x') { # Shadow password file...
6711: my $pwauth_path = "/usr/local/sbin/pwauth";
6712: open PWAUTH, "|$pwauth_path" or
6713: die "Cannot invoke authentication";
6714: print PWAUTH "$user\n$password\n";
6715: close PWAUTH;
6716: $validated = ! $?;
6717:
6718: } else { # Passwords in /etc/passwd.
6719: $validated = (crypt($password,
6720: $contentpwd) eq $contentpwd);
6721: }
6722: } else {
6723: $validated = 0;
6724: }
6725: } elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
6726: my $checkwithkrb5 = 0;
6727: if ($dist =~/^fedora(\d+)$/) {
6728: if ($1 > 11) {
6729: $checkwithkrb5 = 1;
6730: }
6731: } elsif ($dist =~ /^suse([\d.]+)$/) {
6732: if ($1 > 11.1) {
6733: $checkwithkrb5 = 1;
6734: }
6735: }
6736: if ($checkwithkrb5) {
6737: $validated = &krb5_authen($password,$null,$user,$contentpwd);
6738: } else {
6739: $validated = &krb4_authen($password,$null,$user,$contentpwd);
6740: }
6741: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
6742: $validated = &krb5_authen($password,$null,$user,$contentpwd);
6743: } elsif ($howpwd eq "localauth") {
6744: # Authenticate via installation specific authentcation method:
6745: $validated = &localauth::localauth($user,
6746: $password,
6747: $contentpwd,
6748: $domain);
6749: if ($validated < 0) {
6750: &logthis("localauth for $contentpwd $user:$domain returned a $validated");
6751: $validated = 0;
6752: }
6753: } else { # Unrecognized auth is also bad.
6754: $validated = 0;
6755: }
6756: } else {
6757: $validated = 0;
6758: }
6759: #
6760: # $validated has the correct stat of the authentication:
6761: #
6762:
6763: unless ($validated != -3.14159) {
6764: # I >really really< want to know if this happens.
6765: # since it indicates that user authentication is badly
6766: # broken in some code path.
6767: #
6768: die "ValidateUser - failed to set the value of validated $domain, $user $password";
6769: }
6770: return $validated;
6771: }
6772:
6773: sub krb4_authen {
6774: my ($password,$null,$user,$contentpwd) = @_;
6775: my $validated = 0;
6776: if (!($password =~ /$null/) ) { # Null password not allowed.
6777: eval {
6778: require Authen::Krb4;
6779: };
6780: if (!$@) {
6781: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
6782: "",
6783: $contentpwd,,
6784: 'krbtgt',
6785: $contentpwd,
6786: 1,
6787: $password);
6788: if(!$k4error) {
6789: $validated = 1;
6790: } else {
6791: $validated = 0;
6792: &logthis('krb4: '.$user.', '.$contentpwd.', '.
6793: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
6794: }
6795: } else {
6796: $validated = krb5_authen($password,$null,$user,$contentpwd);
6797: }
6798: }
6799: return $validated;
6800: }
6801:
6802: sub krb5_authen {
6803: my ($password,$null,$user,$contentpwd) = @_;
6804: my $validated = 0;
6805: if(!($password =~ /$null/)) { # Null password not allowed.
6806: my $krbclient = &Authen::Krb5::parse_name($user.'@'
6807: .$contentpwd);
6808: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
6809: my $krbserver = &Authen::Krb5::parse_name($krbservice);
6810: my $credentials= &Authen::Krb5::cc_default();
6811: $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
6812: .$contentpwd));
6813: my $krbreturn;
6814: if (exists(&Authen::Krb5::get_init_creds_password)) {
6815: $krbreturn =
6816: &Authen::Krb5::get_init_creds_password($krbclient,$password,
6817: $krbservice);
6818: $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
6819: } else {
6820: $krbreturn =
6821: &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
6822: $password,$credentials);
6823: $validated = ($krbreturn == 1);
6824: }
6825: if (!$validated) {
6826: &logthis('krb5: '.$user.', '.$contentpwd.', '.
6827: &Authen::Krb5::error());
6828: }
6829: }
6830: return $validated;
6831: }
6832:
6833: sub addline {
6834: my ($fname,$hostid,$ip,$newline)=@_;
6835: my $contents;
6836: my $found=0;
6837: my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
6838: my $sh;
6839: if ($sh=IO::File->new("$fname.subscription")) {
6840: while (my $subline=<$sh>) {
6841: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
6842: }
6843: $sh->close();
6844: }
6845: $sh=IO::File->new(">$fname.subscription");
6846: if ($contents) { print $sh $contents; }
6847: if ($newline) { print $sh $newline; }
6848: $sh->close();
6849: return $found;
6850: }
6851:
6852: sub get_chat {
6853: my ($cdom,$cname,$udom,$uname,$group)=@_;
6854:
6855: my @entries=();
6856: my $namespace = 'nohist_chatroom';
6857: my $namespace_inroom = 'nohist_inchatroom';
6858: if ($group ne '') {
6859: $namespace .= '_'.$group;
6860: $namespace_inroom .= '_'.$group;
6861: }
6862: my $hashref = &tie_user_hash($cdom, $cname, $namespace,
6863: &GDBM_READER());
6864: if ($hashref) {
6865: @entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
6866: &untie_user_hash($hashref);
6867: }
6868: my @participants=();
6869: my $cutoff=time-60;
6870: $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
6871: &GDBM_WRCREAT());
6872: if ($hashref) {
6873: $hashref->{$uname.':'.$udom}=time;
6874: foreach my $user (sort(keys(%$hashref))) {
6875: if ($hashref->{$user}>$cutoff) {
6876: push(@participants, 'active_participant:'.$user);
6877: }
6878: }
6879: &untie_user_hash($hashref);
6880: }
6881: return (@participants,@entries);
6882: }
6883:
6884: sub chat_add {
6885: my ($cdom,$cname,$newchat,$group)=@_;
6886: my @entries=();
6887: my $time=time;
6888: my $namespace = 'nohist_chatroom';
6889: my $logfile = 'chatroom.log';
6890: if ($group ne '') {
6891: $namespace .= '_'.$group;
6892: $logfile = 'chatroom_'.$group.'.log';
6893: }
6894: my $hashref = &tie_user_hash($cdom, $cname, $namespace,
6895: &GDBM_WRCREAT());
6896: if ($hashref) {
6897: @entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
6898: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
6899: my ($thentime,$idnum)=split(/\_/,$lastid);
6900: my $newid=$time.'_000000';
6901: if ($thentime==$time) {
6902: $idnum=~s/^0+//;
6903: $idnum++;
6904: $idnum=substr('000000'.$idnum,-6,6);
6905: $newid=$time.'_'.$idnum;
6906: }
6907: $hashref->{$newid}=$newchat;
6908: my $expired=$time-3600;
6909: foreach my $comment (keys(%$hashref)) {
6910: my ($thistime) = ($comment=~/(\d+)\_/);
6911: if ($thistime<$expired) {
6912: delete $hashref->{$comment};
6913: }
6914: }
6915: {
6916: my $proname=&propath($cdom,$cname);
6917: if (open(CHATLOG,">>$proname/$logfile")) {
6918: print CHATLOG ("$time:".&unescape($newchat)."\n");
6919: }
6920: close(CHATLOG);
6921: }
6922: &untie_user_hash($hashref);
6923: }
6924: }
6925:
6926: sub unsub {
6927: my ($fname,$clientip)=@_;
6928: my $result;
6929: my $unsubs = 0; # Number of successful unsubscribes:
6930:
6931:
6932: # An old way subscriptions were handled was to have a
6933: # subscription marker file:
6934:
6935: Debug("Attempting unlink of $fname.$clientname");
6936: if (unlink("$fname.$clientname")) {
6937: $unsubs++; # Successful unsub via marker file.
6938: }
6939:
6940: # The more modern way to do it is to have a subscription list
6941: # file:
6942:
6943: if (-e "$fname.subscription") {
6944: my $found=&addline($fname,$clientname,$clientip,'');
6945: if ($found) {
6946: $unsubs++;
6947: }
6948: }
6949:
6950: # If either or both of these mechanisms succeeded in unsubscribing a
6951: # resource we can return ok:
6952:
6953: if($unsubs) {
6954: $result = "ok\n";
6955: } else {
6956: $result = "not_subscribed\n";
6957: }
6958:
6959: return $result;
6960: }
6961:
6962: sub currentversion {
6963: my $fname=shift;
6964: my $version=-1;
6965: my $ulsdir='';
6966: if ($fname=~/^(.+)\/[^\/]+$/) {
6967: $ulsdir=$1;
6968: }
6969: my ($fnamere1,$fnamere2);
6970: # remove version if already specified
6971: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
6972: # get the bits that go before and after the version number
6973: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
6974: $fnamere1=$1;
6975: $fnamere2='.'.$2;
6976: }
6977: if (-e $fname) { $version=1; }
6978: if (-e $ulsdir) {
6979: if(-d $ulsdir) {
6980: if (opendir(LSDIR,$ulsdir)) {
6981: my $ulsfn;
6982: while ($ulsfn=readdir(LSDIR)) {
6983: # see if this is a regular file (ignore links produced earlier)
6984: my $thisfile=$ulsdir.'/'.$ulsfn;
6985: unless (-l $thisfile) {
6986: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
6987: if ($1>$version) { $version=$1; }
6988: }
6989: }
6990: }
6991: closedir(LSDIR);
6992: $version++;
6993: }
6994: }
6995: }
6996: return $version;
6997: }
6998:
6999: sub thisversion {
7000: my $fname=shift;
7001: my $version=-1;
7002: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
7003: $version=$1;
7004: }
7005: return $version;
7006: }
7007:
7008: sub subscribe {
7009: my ($userinput,$clientip)=@_;
7010: my $result;
7011: my ($cmd,$fname)=split(/:/,$userinput,2);
7012: my $ownership=&ishome($fname);
7013: if ($ownership eq 'owner') {
7014: # explitly asking for the current version?
7015: unless (-e $fname) {
7016: my $currentversion=¤tversion($fname);
7017: if (&thisversion($fname)==$currentversion) {
7018: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
7019: my $root=$1;
7020: my $extension=$2;
7021: symlink($root.'.'.$extension,
7022: $root.'.'.$currentversion.'.'.$extension);
7023: unless ($extension=~/\.meta$/) {
7024: symlink($root.'.'.$extension.'.meta',
7025: $root.'.'.$currentversion.'.'.$extension.'.meta');
7026: }
7027: }
7028: }
7029: }
7030: if (-e $fname) {
7031: if (-d $fname) {
7032: $result="directory\n";
7033: } else {
7034: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
7035: my $now=time;
7036: my $found=&addline($fname,$clientname,$clientip,
7037: "$clientname:$clientip:$now\n");
7038: if ($found) { $result="$fname\n"; }
7039: # if they were subscribed to only meta data, delete that
7040: # subscription, when you subscribe to a file you also get
7041: # the metadata
7042: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
7043: $fname=~s/\/home\/httpd\/html\/res/raw/;
7044: my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
7045: $protocol = 'http' if ($protocol ne 'https');
7046: $fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
7047: $result="$fname\n";
7048: }
7049: } else {
7050: $result="not_found\n";
7051: }
7052: } else {
7053: $result="rejected\n";
7054: }
7055: return $result;
7056: }
7057: # Change the passwd of a unix user. The caller must have
7058: # first verified that the user is a loncapa user.
7059: #
7060: # Parameters:
7061: # user - Unix user name to change.
7062: # pass - New password for the user.
7063: # Returns:
7064: # ok - if success
7065: # other - Some meaningfule error message string.
7066: # NOTE:
7067: # invokes a setuid script to change the passwd.
7068: sub change_unix_password {
7069: my ($user, $pass) = @_;
7070:
7071: &Debug("change_unix_password");
7072: my $execdir=$perlvar{'lonDaemons'};
7073: &Debug("Opening lcpasswd pipeline");
7074: my $pf = IO::File->new("|$execdir/lcpasswd > "
7075: ."$perlvar{'lonDaemons'}"
7076: ."/logs/lcpasswd.log");
7077: print $pf "$user\n$pass\n$pass\n";
7078: close $pf;
7079: my $err = $?;
7080: return ($err < @passwderrors) ? $passwderrors[$err] :
7081: "pwchange_falure - unknown error";
7082:
7083:
7084: }
7085:
7086:
7087: sub make_passwd_file {
7088: my ($uname, $umode,$npass,$passfilename)=@_;
7089: my $result="ok";
7090: if ($umode eq 'krb4' or $umode eq 'krb5') {
7091: {
7092: my $pf = IO::File->new(">$passfilename");
7093: if ($pf) {
7094: print $pf "$umode:$npass\n";
7095: } else {
7096: $result = "pass_file_failed_error";
7097: }
7098: }
7099: } elsif ($umode eq 'internal') {
7100: my $salt=time;
7101: $salt=substr($salt,6,2);
7102: my $ncpass=crypt($npass,$salt);
7103: {
7104: &Debug("Creating internal auth");
7105: my $pf = IO::File->new(">$passfilename");
7106: if($pf) {
7107: print $pf "internal:$ncpass\n";
7108: } else {
7109: $result = "pass_file_failed_error";
7110: }
7111: }
7112: } elsif ($umode eq 'localauth') {
7113: {
7114: my $pf = IO::File->new(">$passfilename");
7115: if($pf) {
7116: print $pf "localauth:$npass\n";
7117: } else {
7118: $result = "pass_file_failed_error";
7119: }
7120: }
7121: } elsif ($umode eq 'unix') {
7122: {
7123: #
7124: # Don't allow the creation of privileged accounts!!! that would
7125: # be real bad!!!
7126: #
7127: my $uid = getpwnam($uname);
7128: if((defined $uid) && ($uid == 0)) {
7129: &logthis(">>>Attempted to create privilged account blocked");
7130: return "no_priv_account_error\n";
7131: }
7132:
7133: my $execpath ="$perlvar{'lonDaemons'}/"."lcuseradd";
7134:
7135: my $lc_error_file = $execdir."/tmp/lcuseradd".$$.".status";
7136: {
7137: &Debug("Executing external: ".$execpath);
7138: &Debug("user = ".$uname.", Password =". $npass);
7139: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
7140: print $se "$uname\n";
7141: print $se "$npass\n";
7142: print $se "$npass\n";
7143: print $se "$lc_error_file\n"; # Status -> unique file.
7144: }
7145: if (-r $lc_error_file) {
7146: &Debug("Opening error file: $lc_error_file");
7147: my $error = IO::File->new("< $lc_error_file");
7148: my $useraddok = <$error>;
7149: $error->close;
7150: unlink($lc_error_file);
7151:
7152: chomp $useraddok;
7153:
7154: if($useraddok > 0) {
7155: my $error_text = &lcuseraddstrerror($useraddok);
7156: &logthis("Failed lcuseradd: $error_text");
7157: $result = "lcuseradd_failed:$error_text";
7158: } else {
7159: my $pf = IO::File->new(">$passfilename");
7160: if($pf) {
7161: print $pf "unix:\n";
7162: } else {
7163: $result = "pass_file_failed_error";
7164: }
7165: }
7166: } else {
7167: &Debug("Could not locate lcuseradd error: $lc_error_file");
7168: $result="bug_lcuseradd_no_output_file";
7169: }
7170: }
7171: } elsif ($umode eq 'none') {
7172: {
7173: my $pf = IO::File->new("> $passfilename");
7174: if($pf) {
7175: print $pf "none:\n";
7176: } else {
7177: $result = "pass_file_failed_error";
7178: }
7179: }
7180: } else {
7181: $result="auth_mode_error";
7182: }
7183: return $result;
7184: }
7185:
7186: sub convert_photo {
7187: my ($start,$dest)=@_;
7188: system("convert $start $dest");
7189: }
7190:
7191: sub sethost {
7192: my ($remotereq) = @_;
7193: my (undef,$hostid)=split(/:/,$remotereq);
7194: # ignore sethost if we are already correct
7195: if ($hostid eq $currenthostid) {
7196: return 'ok';
7197: }
7198:
7199: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
7200: if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'})
7201: eq &Apache::lonnet::get_host_ip($hostid)) {
7202: $currenthostid =$hostid;
7203: $currentdomainid=&Apache::lonnet::host_domain($hostid);
7204: # &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
7205: } else {
7206: &logthis("Requested host id $hostid not an alias of ".
7207: $perlvar{'lonHostID'}." refusing connection");
7208: return 'unable_to_set';
7209: }
7210: return 'ok';
7211: }
7212:
7213: sub version {
7214: my ($userinput)=@_;
7215: $remoteVERSION=(split(/:/,$userinput))[1];
7216: return "version:$VERSION";
7217: }
7218:
7219:
7220: # ----------------------------------- POD (plain old documentation, CPAN style)
7221:
7222: =head1 NAME
7223:
7224: lond - "LON Daemon" Server (port "LOND" 5663)
7225:
7226: =head1 SYNOPSIS
7227:
7228: Usage: B<lond>
7229:
7230: Should only be run as user=www. This is a command-line script which
7231: is invoked by B<loncron>. There is no expectation that a typical user
7232: will manually start B<lond> from the command-line. (In other words,
7233: DO NOT START B<lond> YOURSELF.)
7234:
7235: =head1 DESCRIPTION
7236:
7237: There are two characteristics associated with the running of B<lond>,
7238: PROCESS MANAGEMENT (starting, stopping, handling child processes)
7239: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
7240: subscriptions, etc). These are described in two large
7241: sections below.
7242:
7243: B<PROCESS MANAGEMENT>
7244:
7245: Preforker - server who forks first. Runs as a daemon. HUPs.
7246: Uses IDEA encryption
7247:
7248: B<lond> forks off children processes that correspond to the other servers
7249: in the network. Management of these processes can be done at the
7250: parent process level or the child process level.
7251:
7252: B<logs/lond.log> is the location of log messages.
7253:
7254: The process management is now explained in terms of linux shell commands,
7255: subroutines internal to this code, and signal assignments:
7256:
7257: =over 4
7258:
7259: =item *
7260:
7261: PID is stored in B<logs/lond.pid>
7262:
7263: This is the process id number of the parent B<lond> process.
7264:
7265: =item *
7266:
7267: SIGTERM and SIGINT
7268:
7269: Parent signal assignment:
7270: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
7271:
7272: Child signal assignment:
7273: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
7274: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
7275: to restart a new child.)
7276:
7277: Command-line invocations:
7278: B<kill> B<-s> SIGTERM I<PID>
7279: B<kill> B<-s> SIGINT I<PID>
7280:
7281: Subroutine B<HUNTSMAN>:
7282: This is only invoked for the B<lond> parent I<PID>.
7283: This kills all the children, and then the parent.
7284: The B<lonc.pid> file is cleared.
7285:
7286: =item *
7287:
7288: SIGHUP
7289:
7290: Current bug:
7291: This signal can only be processed the first time
7292: on the parent process. Subsequent SIGHUP signals
7293: have no effect.
7294:
7295: Parent signal assignment:
7296: $SIG{HUP} = \&HUPSMAN;
7297:
7298: Child signal assignment:
7299: none (nothing happens)
7300:
7301: Command-line invocations:
7302: B<kill> B<-s> SIGHUP I<PID>
7303:
7304: Subroutine B<HUPSMAN>:
7305: This is only invoked for the B<lond> parent I<PID>,
7306: This kills all the children, and then the parent.
7307: The B<lond.pid> file is cleared.
7308:
7309: =item *
7310:
7311: SIGUSR1
7312:
7313: Parent signal assignment:
7314: $SIG{USR1} = \&USRMAN;
7315:
7316: Child signal assignment:
7317: $SIG{USR1}= \&logstatus;
7318:
7319: Command-line invocations:
7320: B<kill> B<-s> SIGUSR1 I<PID>
7321:
7322: Subroutine B<USRMAN>:
7323: When invoked for the B<lond> parent I<PID>,
7324: SIGUSR1 is sent to all the children, and the status of
7325: each connection is logged.
7326:
7327: =item *
7328:
7329: SIGUSR2
7330:
7331: Parent Signal assignment:
7332: $SIG{USR2} = \&UpdateHosts
7333:
7334: Child signal assignment:
7335: NONE
7336:
7337:
7338: =item *
7339:
7340: SIGCHLD
7341:
7342: Parent signal assignment:
7343: $SIG{CHLD} = \&REAPER;
7344:
7345: Child signal assignment:
7346: none
7347:
7348: Command-line invocations:
7349: B<kill> B<-s> SIGCHLD I<PID>
7350:
7351: Subroutine B<REAPER>:
7352: This is only invoked for the B<lond> parent I<PID>.
7353: Information pertaining to the child is removed.
7354: The socket port is cleaned up.
7355:
7356: =back
7357:
7358: B<SERVER-SIDE ACTIVITIES>
7359:
7360: Server-side information can be accepted in an encrypted or non-encrypted
7361: method.
7362:
7363: =over 4
7364:
7365: =item ping
7366:
7367: Query a client in the hosts.tab table; "Are you there?"
7368:
7369: =item pong
7370:
7371: Respond to a ping query.
7372:
7373: =item ekey
7374:
7375: Read in encrypted key, make cipher. Respond with a buildkey.
7376:
7377: =item load
7378:
7379: Respond with CPU load based on a computation upon /proc/loadavg.
7380:
7381: =item currentauth
7382:
7383: Reply with current authentication information (only over an
7384: encrypted channel).
7385:
7386: =item auth
7387:
7388: Only over an encrypted channel, reply as to whether a user's
7389: authentication information can be validated.
7390:
7391: =item passwd
7392:
7393: Allow for a password to be set.
7394:
7395: =item makeuser
7396:
7397: Make a user.
7398:
7399: =item passwd
7400:
7401: Allow for authentication mechanism and password to be changed.
7402:
7403: =item home
7404:
7405: Respond to a question "are you the home for a given user?"
7406:
7407: =item update
7408:
7409: Update contents of a subscribed resource.
7410:
7411: =item unsubscribe
7412:
7413: The server is unsubscribing from a resource.
7414:
7415: =item subscribe
7416:
7417: The server is subscribing to a resource.
7418:
7419: =item log
7420:
7421: Place in B<logs/lond.log>
7422:
7423: =item put
7424:
7425: stores hash in namespace
7426:
7427: =item rolesputy
7428:
7429: put a role into a user's environment
7430:
7431: =item get
7432:
7433: returns hash with keys from array
7434: reference filled in from namespace
7435:
7436: =item eget
7437:
7438: returns hash with keys from array
7439: reference filled in from namesp (encrypts the return communication)
7440:
7441: =item rolesget
7442:
7443: get a role from a user's environment
7444:
7445: =item del
7446:
7447: deletes keys out of array from namespace
7448:
7449: =item keys
7450:
7451: returns namespace keys
7452:
7453: =item dump
7454:
7455: dumps the complete (or key matching regexp) namespace into a hash
7456:
7457: =item store
7458:
7459: stores hash permanently
7460: for this url; hashref needs to be given and should be a \%hashname; the
7461: remaining args aren't required and if they aren't passed or are '' they will
7462: be derived from the ENV
7463:
7464: =item restore
7465:
7466: returns a hash for a given url
7467:
7468: =item querysend
7469:
7470: Tells client about the lonsql process that has been launched in response
7471: to a sent query.
7472:
7473: =item queryreply
7474:
7475: Accept information from lonsql and make appropriate storage in temporary
7476: file space.
7477:
7478: =item idput
7479:
7480: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
7481: for each student, defined perhaps by the institutional Registrar.)
7482:
7483: =item idget
7484:
7485: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
7486: for each student, defined perhaps by the institutional Registrar.)
7487:
7488: =item tmpput
7489:
7490: Accept and store information in temporary space.
7491:
7492: =item tmpget
7493:
7494: Send along temporarily stored information.
7495:
7496: =item ls
7497:
7498: List part of a user's directory.
7499:
7500: =item pushtable
7501:
7502: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
7503: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
7504: must be restored manually in case of a problem with the new table file.
7505: pushtable requires that the request be encrypted and validated via
7506: ValidateManager. The form of the command is:
7507: enc:pushtable tablename <tablecontents> \n
7508: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
7509: cleartext newline.
7510:
7511: =item Hanging up (exit or init)
7512:
7513: What to do when a client tells the server that they (the client)
7514: are leaving the network.
7515:
7516: =item unknown command
7517:
7518: If B<lond> is sent an unknown command (not in the list above),
7519: it replys to the client "unknown_cmd".
7520:
7521:
7522: =item UNKNOWN CLIENT
7523:
7524: If the anti-spoofing algorithm cannot verify the client,
7525: the client is rejected (with a "refused" message sent
7526: to the client, and the connection is closed.
7527:
7528: =back
7529:
7530: =head1 PREREQUISITES
7531:
7532: IO::Socket
7533: IO::File
7534: Apache::File
7535: POSIX
7536: Crypt::IDEA
7537: LWP::UserAgent()
7538: GDBM_File
7539: Authen::Krb4
7540: Authen::Krb5
7541:
7542: =head1 COREQUISITES
7543:
7544: =head1 OSNAMES
7545:
7546: linux
7547:
7548: =head1 SCRIPT CATEGORIES
7549:
7550: Server/Process
7551:
7552: =cut
7553:
7554:
7555: =pod
7556:
7557: =head1 LOG MESSAGES
7558:
7559: The messages below can be emitted in the lond log. This log is located
7560: in ~httpd/perl/logs/lond.log Many log messages have HTML encapsulation
7561: to provide coloring if examined from inside a web page. Some do not.
7562: Where color is used, the colors are; Red for sometihhng to get excited
7563: about and to follow up on. Yellow for something to keep an eye on to
7564: be sure it does not get worse, Green,and Blue for informational items.
7565:
7566: In the discussions below, sometimes reference is made to ~httpd
7567: when describing file locations. There isn't really an httpd
7568: user, however there is an httpd directory that gets installed in the
7569: place that user home directories go. On linux, this is usually
7570: (always?) /home/httpd.
7571:
7572:
7573: Some messages are colorless. These are usually (not always)
7574: Green/Blue color level messages.
7575:
7576: =over 2
7577:
7578: =item (Red) LocalConnection rejecting non local: <ip> ne 127.0.0.1
7579:
7580: A local connection negotiation was attempted by
7581: a host whose IP address was not 127.0.0.1.
7582: The socket is closed and the child will exit.
7583: lond has three ways to establish an encyrption
7584: key with a client:
7585:
7586: =over 2
7587:
7588: =item local
7589:
7590: The key is written and read from a file.
7591: This is only valid for connections from localhost.
7592:
7593: =item insecure
7594:
7595: The key is generated by the server and
7596: transmitted to the client.
7597:
7598: =item ssl (secure)
7599:
7600: An ssl connection is negotiated with the client,
7601: the key is generated by the server and sent to the
7602: client across this ssl connection before the
7603: ssl connectionis terminated and clear text
7604: transmission resumes.
7605:
7606: =back
7607:
7608: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
7609:
7610: The client is local but has not sent an initialization
7611: string that is the literal "init:local" The connection
7612: is closed and the child exits.
7613:
7614: =item Red CRITICAL Can't get key file <error>
7615:
7616: SSL key negotiation is being attempted but the call to
7617: lonssl::KeyFile failed. This usually means that the
7618: configuration file is not correctly defining or protecting
7619: the directories/files lonCertificateDirectory or
7620: lonnetPrivateKey
7621: <error> is a string that describes the reason that
7622: the key file could not be located.
7623:
7624: =item (Red) CRITICAL Can't get certificates <error>
7625:
7626: SSL key negotiation failed because we were not able to retrives our certificate
7627: or the CA's certificate in the call to lonssl::CertificateFile
7628: <error> is the textual reason this failed. Usual reasons:
7629:
7630: =over 2
7631:
7632: =item Apache config file for loncapa incorrect:
7633:
7634: one of the variables
7635: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
7636: undefined or incorrect
7637:
7638: =item Permission error:
7639:
7640: The directory pointed to by lonCertificateDirectory is not readable by lond
7641:
7642: =item Permission error:
7643:
7644: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
7645:
7646: =item Installation error:
7647:
7648: Either the certificate authority file or the certificate have not
7649: been installed in lonCertificateDirectory.
7650:
7651: =item (Red) CRITICAL SSL Socket promotion failed: <err>
7652:
7653: The promotion of the connection from plaintext to SSL failed
7654: <err> is the reason for the failure. There are two
7655: system calls involved in the promotion (one of which failed),
7656: a dup to produce
7657: a second fd on the raw socket over which the encrypted data
7658: will flow and IO::SOcket::SSL->new_from_fd which creates
7659: the SSL connection on the duped fd.
7660:
7661: =item (Blue) WARNING client did not respond to challenge
7662:
7663: This occurs on an insecure (non SSL) connection negotiation request.
7664: lond generates some number from the time, the PID and sends it to
7665: the client. The client must respond by echoing this information back.
7666: If the client does not do so, that's a violation of the challenge
7667: protocols and the connection will be failed.
7668:
7669: =item (Red) No manager table. Nobody can manage!!
7670:
7671: lond has the concept of privileged hosts that
7672: can perform remote management function such
7673: as update the hosts.tab. The manager hosts
7674: are described in the
7675: ~httpd/lonTabs/managers.tab file.
7676: this message is logged if this file is missing.
7677:
7678:
7679: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
7680:
7681: Reports the successful parse and registration
7682: of a specific manager.
7683:
7684: =item Green existing host <clustername:dnsname>
7685:
7686: The manager host is already defined in the hosts.tab
7687: the information in that table, rather than the info in the
7688: manager table will be used to determine the manager's ip.
7689:
7690: =item (Red) Unable to craete <filename>
7691:
7692: lond has been asked to create new versions of an administrative
7693: file (by a manager). When this is done, the new file is created
7694: in a temp file and then renamed into place so that there are always
7695: usable administrative files, even if the update fails. This failure
7696: message means that the temp file could not be created.
7697: The update is abandoned, and the old file is available for use.
7698:
7699: =item (Green) CopyFile from <oldname> to <newname> failed
7700:
7701: In an update of administrative files, the copy of the existing file to a
7702: backup file failed. The installation of the new file may still succeed,
7703: but there will not be a back up file to rever to (this should probably
7704: be yellow).
7705:
7706: =item (Green) Pushfile: backed up <oldname> to <newname>
7707:
7708: See above, the backup of the old administrative file succeeded.
7709:
7710: =item (Red) Pushfile: Unable to install <filename> <reason>
7711:
7712: The new administrative file could not be installed. In this case,
7713: the old administrative file is still in use.
7714:
7715: =item (Green) Installed new < filename>.
7716:
7717: The new administrative file was successfullly installed.
7718:
7719: =item (Red) Reinitializing lond pid=<pid>
7720:
7721: The lonc child process <pid> will be sent a USR2
7722: signal.
7723:
7724: =item (Red) Reinitializing self
7725:
7726: We've been asked to re-read our administrative files,and
7727: are doing so.
7728:
7729: =item (Yellow) error:Invalid process identifier <ident>
7730:
7731: A reinit command was received, but the target part of the
7732: command was not valid. It must be either
7733: 'lond' or 'lonc' but was <ident>
7734:
7735: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
7736:
7737: Checking to see if lond has been handed a valid edit
7738: command. It is possible the edit command is not valid
7739: in that case there are no log messages to indicate that.
7740:
7741: =item Result of password change for <username> pwchange_success
7742:
7743: The password for <username> was
7744: successfully changed.
7745:
7746: =item Unable to open <user> passwd to change password
7747:
7748: Could not rewrite the
7749: internal password file for a user
7750:
7751: =item Result of password change for <user> : <result>
7752:
7753: A unix password change for <user> was attempted
7754: and the pipe returned <result>
7755:
7756: =item LWP GET: <message> for <fname> (<remoteurl>)
7757:
7758: The lightweight process fetch for a resource failed
7759: with <message> the local filename that should
7760: have existed/been created was <fname> the
7761: corresponding URI: <remoteurl> This is emitted in several
7762: places.
7763:
7764: =item Unable to move <transname> to <destname>
7765:
7766: From fetch_user_file_handler - the user file was replicated but could not
7767: be mv'd to its final location.
7768:
7769: =item Looking for <domain> <username>
7770:
7771: From user_has_session_handler - This should be a Debug call instead
7772: it indicates lond is about to check whether the specified user has a
7773: session active on the specified domain on the local host.
7774:
7775: =item Client <ip> (<name>) hanging up: <input>
7776:
7777: lond has been asked to exit by its client. The <ip> and <name> identify the
7778: client systemand <input> is the full exit command sent to the server.
7779:
7780: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
7781:
7782: A lond child terminated. NOte that this termination can also occur when the
7783: child receives the QUIT or DIE signals. <pid> is the process id of the child,
7784: <hostname> the host lond is working for, and <message> the reason the child died
7785: to the best of our ability to get it (I would guess that any numeric value
7786: represents and errno value). This is immediately followed by
7787:
7788: =item Famous last words: Catching exception - <log>
7789:
7790: Where log is some recent information about the state of the child.
7791:
7792: =item Red CRITICAL: TIME OUT <pid>
7793:
7794: Some timeout occured for server <pid>. THis is normally a timeout on an LWP
7795: doing an HTTP::GET.
7796:
7797: =item child <pid> died
7798:
7799: The reaper caught a SIGCHILD for the lond child process <pid>
7800: This should be modified to also display the IP of the dying child
7801: $children{$pid}
7802:
7803: =item Unknown child 0 died
7804: A child died but the wait for it returned a pid of zero which really should not
7805: ever happen.
7806:
7807: =item Child <which> - <pid> looks like we missed it's death
7808:
7809: When a sigchild is received, the reaper process checks all children to see if they are
7810: alive. If children are dying quite quickly, the lack of signal queuing can mean
7811: that a signal hearalds the death of more than one child. If so this message indicates
7812: which other one died. <which> is the ip of a dead child
7813:
7814: =item Free socket: <shutdownretval>
7815:
7816: The HUNTSMAN sub was called due to a SIGINT in a child process. The socket is being shutdown.
7817: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
7818: to return anything. This is followed by:
7819:
7820: =item Red CRITICAL: Shutting down
7821:
7822: Just prior to exit.
7823:
7824: =item Free socket: <shutdownretval>
7825:
7826: The HUPSMAN sub was called due to a SIGHUP. all children get killsed, and lond execs itself.
7827: This is followed by:
7828:
7829: =item (Red) CRITICAL: Restarting
7830:
7831: lond is about to exec itself to restart.
7832:
7833: =item (Blue) Updating connections
7834:
7835: (In response to a USR2). All the children (except the one for localhost)
7836: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
7837:
7838: =item (Blue) UpdateHosts killing child <pid> for ip <ip>
7839:
7840: Due to USR2 as above.
7841:
7842: =item (Green) keeping child for ip <ip> (pid = <pid>)
7843:
7844: In response to USR2 as above, the child indicated is not being restarted because
7845: it's assumed that we'll always need a child for the localhost.
7846:
7847:
7848: =item Going to check on the children
7849:
7850: Parent is about to check on the health of the child processes.
7851: Note that this is in response to a USR1 sent to the parent lond.
7852: there may be one or more of the next two messages:
7853:
7854: =item <pid> is dead
7855:
7856: A child that we have in our child hash as alive has evidently died.
7857:
7858: =item Child <pid> did not respond
7859:
7860: In the health check the child <pid> did not update/produce a pid_.txt
7861: file when sent it's USR1 signal. That process is killed with a 9 signal, as it's
7862: assumed to be hung in some un-fixable way.
7863:
7864: =item Finished checking children
7865:
7866: Master processs's USR1 processing is cojmplete.
7867:
7868: =item (Red) CRITICAL: ------- Starting ------
7869:
7870: (There are more '-'s on either side). Lond has forked itself off to
7871: form a new session and is about to start actual initialization.
7872:
7873: =item (Green) Attempting to start child (<client>)
7874:
7875: Started a new child process for <client>. Client is IO::Socket object
7876: connected to the child. This was as a result of a TCP/IP connection from a client.
7877:
7878: =item Unable to determine who caller was, getpeername returned nothing
7879:
7880: In child process initialization. either getpeername returned undef or
7881: a zero sized object was returned. Processing continues, but in my opinion,
7882: this should be cause for the child to exit.
7883:
7884: =item Unable to determine clientip
7885:
7886: In child process initialization. The peer address from getpeername was not defined.
7887: The client address is stored as "Unavailable" and processing continues.
7888:
7889: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
7890:
7891: In child initialization. A good connectionw as received from <ip>.
7892:
7893: =over 2
7894:
7895: =item <name>
7896:
7897: is the name of the client from hosts.tab.
7898:
7899: =item <type>
7900:
7901: Is the connection type which is either
7902:
7903: =over 2
7904:
7905: =item manager
7906:
7907: The connection is from a manager node, not in hosts.tab
7908:
7909: =item client
7910:
7911: the connection is from a non-manager in the hosts.tab
7912:
7913: =item both
7914:
7915: The connection is from a manager in the hosts.tab.
7916:
7917: =back
7918:
7919: =back
7920:
7921: =item (Blue) Certificates not installed -- trying insecure auth
7922:
7923: One of the certificate file, key file or
7924: certificate authority file could not be found for a client attempting
7925: SSL connection intiation. COnnection will be attemptied in in-secure mode.
7926: (this would be a system with an up to date lond that has not gotten a
7927: certificate from us).
7928:
7929: =item (Green) Successful local authentication
7930:
7931: A local connection successfully negotiated the encryption key.
7932: In this case the IDEA key is in a file (that is hopefully well protected).
7933:
7934: =item (Green) Successful ssl authentication with <client>
7935:
7936: The client (<client> is the peer's name in hosts.tab), has successfully
7937: negotiated an SSL connection with this child process.
7938:
7939: =item (Green) Successful insecure authentication with <client>
7940:
7941:
7942: The client has successfully negotiated an insecure connection withthe child process.
7943:
7944: =item (Yellow) Attempted insecure connection disallowed
7945:
7946: The client attempted and failed to successfully negotiate a successful insecure
7947: connection. This can happen either because the variable londAllowInsecure is false
7948: or undefined, or becuse the child did not successfully echo back the challenge
7949: string.
7950:
7951:
7952: =back
7953:
7954: =back
7955:
7956:
7957: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>