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