Annotation of loncom/lond, revision 1.489.2.43.2.12
1.1 albertel 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60 www 4: #
1.489.2.43.2. 2(raebur 5:5): # $Id: lond,v 1.489.2.43.2.11 2024/08/18 16:20:24 raeburn Exp $
1.60 www 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
1.167 foxr 13: # the Free Software Foundation; either version 2 of the License, or
1.60 www 14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
1.178 foxr 23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1.60 www 24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
1.161 foxr 27:
28:
1.60 www 29: # http://www.lon-capa.org/
30: #
1.54 harris41 31:
1.134 albertel 32: use strict;
1.80 harris41 33: use lib '/home/httpd/lib/perl/';
1.325 albertel 34: use LONCAPA;
1.80 harris41 35: use LONCAPA::Configuration;
1.489.2.4 raeburn 36: use LONCAPA::Lond;
1.80 harris41 37:
1.1 albertel 38: use IO::Socket;
39: use IO::File;
1.126 albertel 40: #use Apache::File;
1.1 albertel 41: use POSIX;
42: use Crypt::IDEA;
43: use LWP::UserAgent();
1.347 raeburn 44: use Digest::MD5 qw(md5_hex);
1.3 www 45: use GDBM_File;
1.91 albertel 46: use Authen::Krb5;
1.49 albertel 47: use localauth;
1.193 raeburn 48: use localenroll;
1.265 albertel 49: use localstudentphoto;
1.143 foxr 50: use File::Copy;
1.292 albertel 51: use File::Find;
1.200 matthew 52: use LONCAPA::lonlocal;
53: use LONCAPA::lonssl;
1.221 albertel 54: use Fcntl qw(:flock);
1.383 raeburn 55: use Apache::lonnet;
1.472 raeburn 56: use Mail::Send;
1.489.2.21 raeburn 57: use Crypt::Eksblowfish::Bcrypt;
58: use Digest::SHA;
59: use Encode;
1.1 albertel 60:
1.463 foxr 61: my $DEBUG = 0; # Non zero to enable debug log entries.
1.77 foxr 62:
1.57 www 63: my $status='';
64: my $lastlog='';
65:
1.489.2.43.2. 2(raebur 66:5): my $VERSION='$Revision: 1.489.2.43.2.11 $'; #' stupid emacs
1.121 albertel 67: my $remoteVERSION;
1.214 foxr 68: my $currenthostid="default";
1.115 albertel 69: my $currentdomainid;
1.134 albertel 70:
71: my $client;
1.200 matthew 72: my $clientip; # IP address of client.
73: my $clientname; # LonCAPA name of client.
1.448 raeburn 74: my $clientversion; # LonCAPA version running on client.
75: my $clienthomedom; # LonCAPA domain of homeID for client.
76: # primary library server.
1.140 foxr 77:
1.134 albertel 78: my $server;
1.200 matthew 79:
80: my $keymode;
1.198 foxr 81:
1.207 foxr 82: my $cipher; # Cipher key negotiated with client
83: my $tmpsnum = 0; # Id of tmpputs.
84:
1.178 foxr 85: #
86: # Connection type is:
87: # client - All client actions are allowed
88: # manager - only management functions allowed.
89: # both - Both management and client actions are allowed
90: #
1.161 foxr 91:
1.178 foxr 92: my $ConnectionType;
1.161 foxr 93:
1.178 foxr 94: my %managers; # Ip -> manager names
1.161 foxr 95:
1.178 foxr 96: my %perlvar; # Will have the apache conf defined perl vars.
1.134 albertel 97:
1.480 raeburn 98: my $dist;
99:
1.178 foxr 100: #
1.207 foxr 101: # The hash below is used for command dispatching, and is therefore keyed on the request keyword.
102: # Each element of the hash contains a reference to an array that contains:
103: # A reference to a sub that executes the request corresponding to the keyword.
104: # A flag that is true if the request must be encoded to be acceptable.
105: # A mask with bits as follows:
106: # CLIENT_OK - Set when the function is allowed by ordinary clients
107: # MANAGER_OK - Set when the function is allowed to manager clients.
108: #
109: my $CLIENT_OK = 1;
110: my $MANAGER_OK = 2;
111: my %Dispatcher;
112:
113:
114: #
1.178 foxr 115: # The array below are password error strings."
116: #
117: my $lastpwderror = 13; # Largest error number from lcpasswd.
118: my @passwderrors = ("ok",
1.287 foxr 119: "pwchange_failure - lcpasswd must be run as user 'www'",
120: "pwchange_failure - lcpasswd got incorrect number of arguments",
121: "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
122: "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
123: "pwchange_failure - lcpasswd User does not exist.",
124: "pwchange_failure - lcpasswd Incorrect current passwd",
125: "pwchange_failure - lcpasswd Unable to su to root.",
126: "pwchange_failure - lcpasswd Cannot set new passwd.",
127: "pwchange_failure - lcpasswd Username has invalid characters",
128: "pwchange_failure - lcpasswd Invalid characters in password",
129: "pwchange_failure - lcpasswd User already exists",
130: "pwchange_failure - lcpasswd Something went wrong with user addition.",
131: "pwchange_failure - lcpasswd Password mismatch",
132: "pwchange_failure - lcpasswd Error filename is invalid");
1.97 foxr 133:
134:
1.412 foxr 135: # This array are the errors from lcinstallfile:
136:
137: my @installerrors = ("ok",
138: "Initial user id of client not that of www",
139: "Usage error, not enough command line arguments",
1.489.2.5 raeburn 140: "Source filename does not exist",
141: "Destination filename does not exist",
1.412 foxr 142: "Some file operation failed",
143: "Invalid table filename."
144: );
1.207 foxr 145:
146: #
147: # Statistics that are maintained and dislayed in the status line.
148: #
1.212 foxr 149: my $Transactions = 0; # Number of attempted transactions.
150: my $Failures = 0; # Number of transcations failed.
1.207 foxr 151:
152: # ResetStatistics:
153: # Resets the statistics counters:
154: #
155: sub ResetStatistics {
156: $Transactions = 0;
157: $Failures = 0;
158: }
159:
1.200 matthew 160: #------------------------------------------------------------------------
161: #
162: # LocalConnection
163: # Completes the formation of a locally authenticated connection.
164: # This function will ensure that the 'remote' client is really the
165: # local host. If not, the connection is closed, and the function fails.
166: # If so, initcmd is parsed for the name of a file containing the
167: # IDEA session key. The fie is opened, read, deleted and the session
168: # key returned to the caller.
169: #
170: # Parameters:
171: # $Socket - Socket open on client.
172: # $initcmd - The full text of the init command.
173: #
174: # Returns:
175: # IDEA session key on success.
176: # undef on failure.
177: #
178: sub LocalConnection {
179: my ($Socket, $initcmd) = @_;
1.373 albertel 180: Debug("Attempting local connection: $initcmd client: $clientip");
1.277 albertel 181: if($clientip ne "127.0.0.1") {
1.200 matthew 182: &logthis('<font color="red"> LocalConnection rejecting non local: '
1.373 albertel 183: ."$clientip ne 127.0.0.1 </font>");
1.200 matthew 184: close $Socket;
185: return undef;
1.224 foxr 186: } else {
1.200 matthew 187: chomp($initcmd); # Get rid of \n in filename.
188: my ($init, $type, $name) = split(/:/, $initcmd);
189: Debug(" Init command: $init $type $name ");
190:
191: # Require that $init = init, and $type = local: Otherwise
192: # the caller is insane:
193:
194: if(($init ne "init") && ($type ne "local")) {
195: &logthis('<font color = "red"> LocalConnection: caller is insane! '
196: ."init = $init, and type = $type </font>");
197: close($Socket);;
198: return undef;
199:
200: }
201: # Now get the key filename:
202:
203: my $IDEAKey = lonlocal::ReadKeyFile($name);
204: return $IDEAKey;
205: }
206: }
207: #------------------------------------------------------------------------------
208: #
209: # SSLConnection
210: # Completes the formation of an ssh authenticated connection. The
211: # socket is promoted to an ssl socket. If this promotion and the associated
212: # certificate exchange are successful, the IDEA key is generated and sent
213: # to the remote peer via the SSL tunnel. The IDEA key is also returned to
214: # the caller after the SSL tunnel is torn down.
215: #
216: # Parameters:
217: # Name Type Purpose
218: # $Socket IO::Socket::INET Plaintext socket.
219: #
220: # Returns:
221: # IDEA key on success.
222: # undef on failure.
223: #
224: sub SSLConnection {
225: my $Socket = shift;
226:
227: Debug("SSLConnection: ");
228: my $KeyFile = lonssl::KeyFile();
229: if(!$KeyFile) {
230: my $err = lonssl::LastError();
231: &logthis("<font color=\"red\"> CRITICAL"
232: ."Can't get key file $err </font>");
233: return undef;
234: }
235: my ($CACertificate,
236: $Certificate) = lonssl::CertificateFile();
237:
238:
239: # If any of the key, certificate or certificate authority
240: # certificate filenames are not defined, this can't work.
241:
242: if((!$Certificate) || (!$CACertificate)) {
243: my $err = lonssl::LastError();
244: &logthis("<font color=\"red\"> CRITICAL"
245: ."Can't get certificates: $err </font>");
246:
247: return undef;
248: }
249: Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
250:
251: # Indicate to our peer that we can procede with
252: # a transition to ssl authentication:
253:
254: print $Socket "ok:ssl\n";
255:
256: Debug("Approving promotion -> ssl");
257: # And do so:
258:
259: my $SSLSocket = lonssl::PromoteServerSocket($Socket,
260: $CACertificate,
261: $Certificate,
262: $KeyFile);
263: if(! ($SSLSocket) ) { # SSL socket promotion failed.
264: my $err = lonssl::LastError();
265: &logthis("<font color=\"red\"> CRITICAL "
266: ."SSL Socket promotion failed: $err </font>");
267: return undef;
268: }
269: Debug("SSL Promotion successful");
270:
271: #
272: # The only thing we'll use the socket for is to send the IDEA key
273: # to the peer:
274:
275: my $Key = lonlocal::CreateCipherKey();
276: print $SSLSocket "$Key\n";
277:
278: lonssl::Close($SSLSocket);
279:
280: Debug("Key exchange complete: $Key");
281:
282: return $Key;
283: }
284: #
285: # InsecureConnection:
286: # If insecure connections are allowd,
287: # exchange a challenge with the client to 'validate' the
288: # client (not really, but that's the protocol):
289: # We produce a challenge string that's sent to the client.
290: # The client must then echo the challenge verbatim to us.
291: #
292: # Parameter:
293: # Socket - Socket open on the client.
294: # Returns:
295: # 1 - success.
296: # 0 - failure (e.g.mismatch or insecure not allowed).
297: #
298: sub InsecureConnection {
299: my $Socket = shift;
300:
301: # Don't even start if insecure connections are not allowed.
302:
303: if(! $perlvar{londAllowInsecure}) { # Insecure connections not allowed.
304: return 0;
305: }
306:
307: # Fabricate a challenge string and send it..
308:
309: my $challenge = "$$".time; # pid + time.
310: print $Socket "$challenge\n";
311: &status("Waiting for challenge reply");
312:
313: my $answer = <$Socket>;
314: $answer =~s/\W//g;
315: if($challenge eq $answer) {
316: return 1;
1.224 foxr 317: } else {
1.200 matthew 318: logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
319: &status("No challenge reqply");
320: return 0;
321: }
322:
323:
324: }
1.251 foxr 325: #
326: # Safely execute a command (as long as it's not a shel command and doesn
327: # not require/rely on shell escapes. The function operates by doing a
328: # a pipe based fork and capturing stdout and stderr from the pipe.
329: #
330: # Formal Parameters:
331: # $line - A line of text to be executed as a command.
332: # Returns:
333: # The output from that command. If the output is multiline the caller
334: # must know how to split up the output.
335: #
336: #
337: sub execute_command {
338: my ($line) = @_;
339: my @words = split(/\s/, $line); # Bust the command up into words.
340: my $output = "";
341:
342: my $pid = open(CHILD, "-|");
343:
344: if($pid) { # Parent process
345: Debug("In parent process for execute_command");
346: my @data = <CHILD>; # Read the child's outupt...
347: close CHILD;
348: foreach my $output_line (@data) {
349: Debug("Adding $output_line");
350: $output .= $output_line; # Presumably has a \n on it.
351: }
352:
353: } else { # Child process
354: close (STDERR);
355: open (STDERR, ">&STDOUT");# Combine stderr, and stdout...
356: exec(@words); # won't return.
357: }
358: return $output;
359: }
360:
1.200 matthew 361:
1.140 foxr 362: # GetCertificate: Given a transaction that requires a certificate,
363: # this function will extract the certificate from the transaction
364: # request. Note that at this point, the only concept of a certificate
365: # is the hostname to which we are connected.
366: #
367: # Parameter:
368: # request - The request sent by our client (this parameterization may
369: # need to change when we really use a certificate granting
370: # authority.
371: #
372: sub GetCertificate {
373: my $request = shift;
374:
375: return $clientip;
376: }
1.161 foxr 377:
1.178 foxr 378: #
379: # Return true if client is a manager.
380: #
381: sub isManager {
382: return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
383: }
384: #
385: # Return tru if client can do client functions
386: #
387: sub isClient {
388: return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
389: }
1.161 foxr 390:
391:
1.156 foxr 392: #
393: # ReadManagerTable: Reads in the current manager table. For now this is
394: # done on each manager authentication because:
395: # - These authentications are not frequent
396: # - This allows dynamic changes to the manager table
397: # without the need to signal to the lond.
398: #
399: sub ReadManagerTable {
400:
1.412 foxr 401: &Debug("Reading manager table");
1.156 foxr 402: # Clean out the old table first..
403:
1.166 foxr 404: foreach my $key (keys %managers) {
405: delete $managers{$key};
406: }
407:
408: my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
409: if (!open (MANAGERS, $tablename)) {
1.473 raeburn 410: my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
411: if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472 raeburn 412: &logthis('<font color="red">No manager table. Nobody can manage!!</font>');
413: }
414: return;
1.166 foxr 415: }
416: while(my $host = <MANAGERS>) {
417: chomp($host);
418: if ($host =~ "^#") { # Comment line.
419: next;
420: }
1.368 albertel 421: if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161 foxr 422: # The entry is of the form:
423: # cluname:hostname
424: # cluname - A 'cluster hostname' is needed in order to negotiate
425: # the host key.
426: # hostname- The dns name of the host.
427: #
1.166 foxr 428: my($cluname, $dnsname) = split(/:/, $host);
429:
430: my $ip = gethostbyname($dnsname);
431: if(defined($ip)) { # bad names don't deserve entry.
432: my $hostip = inet_ntoa($ip);
433: $managers{$hostip} = $cluname;
434: logthis('<font color="green"> registering manager '.
435: "$dnsname as $cluname with $hostip </font>\n");
436: }
437: } else {
438: logthis('<font color="green"> existing host'." $host</font>\n");
1.472 raeburn 439: $managers{&Apache::lonnet::get_host_ip($host)} = $host; # Use info from cluster tab if cluster memeber
1.166 foxr 440: }
441: }
1.156 foxr 442: }
1.140 foxr 443:
444: #
445: # ValidManager: Determines if a given certificate represents a valid manager.
446: # in this primitive implementation, the 'certificate' is
447: # just the connecting loncapa client name. This is checked
448: # against a valid client list in the configuration.
449: #
450: #
451: sub ValidManager {
452: my $certificate = shift;
453:
1.163 foxr 454: return isManager;
1.140 foxr 455: }
456: #
1.143 foxr 457: # CopyFile: Called as part of the process of installing a
458: # new configuration file. This function copies an existing
459: # file to a backup file.
460: # Parameters:
461: # oldfile - Name of the file to backup.
462: # newfile - Name of the backup file.
463: # Return:
464: # 0 - Failure (errno has failure reason).
465: # 1 - Success.
466: #
467: sub CopyFile {
1.192 foxr 468:
469: my ($oldfile, $newfile) = @_;
1.143 foxr 470:
1.281 matthew 471: if (! copy($oldfile,$newfile)) {
472: return 0;
1.143 foxr 473: }
1.281 matthew 474: chmod(0660, $newfile);
475: return 1;
1.143 foxr 476: }
1.157 foxr 477: #
478: # Host files are passed out with externally visible host IPs.
479: # If, for example, we are behind a fire-wall or NAT host, our
480: # internally visible IP may be different than the externally
481: # visible IP. Therefore, we always adjust the contents of the
482: # host file so that the entry for ME is the IP that we believe
483: # we have. At present, this is defined as the entry that
484: # DNS has for us. If by some chance we are not able to get a
485: # DNS translation for us, then we assume that the host.tab file
486: # is correct.
487: # BUGBUGBUG - in the future, we really should see if we can
488: # easily query the interface(s) instead.
489: # Parameter(s):
490: # contents - The contents of the host.tab to check.
491: # Returns:
492: # newcontents - The adjusted contents.
493: #
494: #
495: sub AdjustHostContents {
496: my $contents = shift;
497: my $adjusted;
498: my $me = $perlvar{'lonHostID'};
499:
1.354 albertel 500: foreach my $line (split(/\n/,$contents)) {
1.472 raeburn 501: if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
502: ($line =~ /^\s*\^/))) {
1.157 foxr 503: chomp($line);
504: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
505: if ($id eq $me) {
1.354 albertel 506: my $ip = gethostbyname($name);
507: my $ipnew = inet_ntoa($ip);
508: $ip = $ipnew;
1.157 foxr 509: # Reconstruct the host line and append to adjusted:
510:
1.354 albertel 511: my $newline = "$id:$domain:$role:$name:$ip";
512: if($maxcon ne "") { # Not all hosts have loncnew tuning params
513: $newline .= ":$maxcon:$idleto:$mincon";
514: }
515: $adjusted .= $newline."\n";
1.157 foxr 516:
1.354 albertel 517: } else { # Not me, pass unmodified.
518: $adjusted .= $line."\n";
519: }
1.157 foxr 520: } else { # Blank or comment never re-written.
521: $adjusted .= $line."\n"; # Pass blanks and comments as is.
522: }
1.354 albertel 523: }
524: return $adjusted;
1.157 foxr 525: }
1.143 foxr 526: #
527: # InstallFile: Called to install an administrative file:
1.412 foxr 528: # - The file is created int a temp directory called <name>.tmp
529: # - lcinstall file is called to install the file.
530: # since the web app has no direct write access to the table directory
1.143 foxr 531: #
532: # Parameters:
533: # Name of the file
534: # File Contents.
535: # Return:
536: # nonzero - success.
537: # 0 - failure and $! has an errno.
1.412 foxr 538: # Assumptions:
539: # File installtion is a relatively infrequent
1.143 foxr 540: #
541: sub InstallFile {
1.192 foxr 542:
543: my ($Filename, $Contents) = @_;
1.412 foxr 544: # my $TempFile = $Filename.".tmp";
545: my $exedir = $perlvar{'lonDaemons'};
546: my $tmpdir = $exedir.'/tmp/';
547: my $TempFile = $tmpdir."TempTableFile.tmp";
1.143 foxr 548:
549: # Open the file for write:
550:
551: my $fh = IO::File->new("> $TempFile"); # Write to temp.
552: if(!(defined $fh)) {
553: &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
554: return 0;
555: }
556: # write the contents of the file:
557:
558: print $fh ($Contents);
559: $fh->close; # In case we ever have a filesystem w. locking
560:
1.412 foxr 561: chmod(0664, $TempFile); # Everyone can write it.
562:
563: # Use lcinstall file to put the file in the table directory...
564:
565: &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
566: my $pf = IO::File->new("| $exedir/lcinstallfile $TempFile $Filename > $exedir/logs/lcinstallfile.log");
567: close $pf;
568: my $err = $?;
569: &Debug("Status is $err");
570: if ($err != 0) {
571: my $msg = $err;
572: if ($err < @installerrors) {
573: $msg = $installerrors[$err];
574: }
575: &logthis("Install failed for table file $Filename : $msg");
576: return 0;
577: }
578:
579: # Remove the temp file:
1.143 foxr 580:
1.412 foxr 581: unlink($TempFile);
1.143 foxr 582:
583: return 1;
584: }
1.200 matthew 585:
586:
1.169 foxr 587: #
588: # ConfigFileFromSelector: converts a configuration file selector
1.411 foxr 589: # into a configuration file pathname.
1.472 raeburn 590: # Supports the following file selectors:
591: # hosts, domain, dns_hosts, dns_domain
1.411 foxr 592: #
1.169 foxr 593: #
594: # Parameters:
595: # selector - Configuration file selector.
596: # Returns:
597: # Full path to the file or undef if the selector is invalid.
598: #
599: sub ConfigFileFromSelector {
600: my $selector = shift;
601: my $tablefile;
602:
603: my $tabledir = $perlvar{'lonTabDir'}.'/';
1.472 raeburn 604: if (($selector eq "hosts") || ($selector eq "domain") ||
605: ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
1.411 foxr 606: $tablefile = $tabledir.$selector.'.tab';
1.169 foxr 607: }
608: return $tablefile;
609: }
1.143 foxr 610: #
1.141 foxr 611: # PushFile: Called to do an administrative push of a file.
612: # - Ensure the file being pushed is one we support.
613: # - Backup the old file to <filename.saved>
614: # - Separate the contents of the new file out from the
615: # rest of the request.
616: # - Write the new file.
617: # Parameter:
618: # Request - The entire user request. This consists of a : separated
619: # string pushfile:tablename:contents.
620: # NOTE: The contents may have :'s in it as well making things a bit
621: # more interesting... but not much.
622: # Returns:
623: # String to send to client ("ok" or "refused" if bad file).
624: #
625: sub PushFile {
1.489.2.15 raeburn 626: my $request = shift;
1.141 foxr 627: my ($command, $filename, $contents) = split(":", $request, 3);
1.412 foxr 628: &Debug("PushFile");
1.141 foxr 629:
630: # At this point in time, pushes for only the following tables are
631: # supported:
632: # hosts.tab ($filename eq host).
633: # domain.tab ($filename eq domain).
1.472 raeburn 634: # dns_hosts.tab ($filename eq dns_host).
635: # dns_domain.tab ($filename eq dns_domain).
1.141 foxr 636: # Construct the destination filename or reject the request.
637: #
638: # lonManage is supposed to ensure this, however this session could be
639: # part of some elaborate spoof that managed somehow to authenticate.
640: #
641:
1.169 foxr 642:
643: my $tablefile = ConfigFileFromSelector($filename);
644: if(! (defined $tablefile)) {
1.141 foxr 645: return "refused";
646: }
1.412 foxr 647:
1.157 foxr 648: # If the file being pushed is the host file, we adjust the entry for ourself so that the
649: # IP will be our current IP as looked up in dns. Note this is only 99% good as it's possible
650: # to conceive of conditions where we don't have a DNS entry locally. This is possible in a
651: # network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
652: # that possibilty.
653:
654: if($filename eq "host") {
655: $contents = AdjustHostContents($contents);
1.489.2.43.2. (raeburn 656:): } elsif (($filename eq 'dns_hosts') || ($filename eq 'dns_domain')) {
1.489.2.15 raeburn 657: if ($contents eq '') {
658: &logthis('<font color="red"> Pushfile: unable to install '
659: .$tablefile." - no data received from push. </font>");
660: return 'error: push had no data';
661: }
662: if (&Apache::lonnet::get_host_ip($clientname)) {
663: my $clienthost = &Apache::lonnet::hostname($clientname);
664: if ($managers{$clientip} eq $clientname) {
665: my $clientprotocol = $Apache::lonnet::protocol{$clientname};
666: $clientprotocol = 'http' if ($clientprotocol ne 'https');
667: my $url = '/adm/'.$filename;
668: $url =~ s{_}{/};
669: my $ua=new LWP::UserAgent;
670: $ua->timeout(60);
671: my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
672: my $response=$ua->request($request);
673: if ($response->is_error()) {
674: &logthis('<font color="red"> Pushfile: unable to install '
675: .$tablefile." - error attempting to pull data. </font>");
676: return 'error: pull failed';
677: } else {
678: my $result = $response->content;
679: chomp($result);
680: unless ($result eq $contents) {
681: &logthis('<font color="red"> Pushfile: unable to install '
682: .$tablefile." - pushed data and pulled data differ. </font>");
683: my $pushleng = length($contents);
684: my $pullleng = length($result);
685: if ($pushleng != $pullleng) {
686: return "error: $pushleng vs $pullleng bytes";
687: } else {
688: return "error: mismatch push and pull";
689: }
690: }
691: }
692: }
693: }
1.157 foxr 694: }
695:
1.141 foxr 696: # Install the new file:
697:
1.412 foxr 698: &logthis("Installing new $tablefile contents:\n$contents");
1.143 foxr 699: if(!InstallFile($tablefile, $contents)) {
700: &logthis('<font color="red"> Pushfile: unable to install '
1.145 foxr 701: .$tablefile." $! </font>");
1.143 foxr 702: return "error:$!";
1.224 foxr 703: } else {
1.143 foxr 704: &logthis('<font color="green"> Installed new '.$tablefile
1.473 raeburn 705: ." - transaction by: $clientname ($clientip)</font>");
1.472 raeburn 706: my $adminmail = $perlvar{'lonAdmEMail'};
707: my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
708: if ($admindom ne '') {
709: my %domconfig =
710: &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
711: if (ref($domconfig{'contacts'}) eq 'HASH') {
712: if ($domconfig{'contacts'}{'adminemail'} ne '') {
713: $adminmail = $domconfig{'contacts'}{'adminemail'};
714: }
715: }
716: }
717: if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
718: my $msg = new Mail::Send;
719: $msg->to($adminmail);
720: $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
721: $msg->add('Content-type','text/plain; charset=UTF-8');
722: if (my $fh = $msg->open()) {
723: print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473 raeburn 724: "$clientname ($clientip)\n";
1.472 raeburn 725: $fh->close;
726: }
727: }
1.143 foxr 728: }
729:
1.141 foxr 730: # Indicate success:
731:
732: return "ok";
733:
734: }
1.145 foxr 735:
736: #
737: # Called to re-init either lonc or lond.
738: #
739: # Parameters:
740: # request - The full request by the client. This is of the form
741: # reinit:<process>
742: # where <process> is allowed to be either of
743: # lonc or lond
744: #
745: # Returns:
746: # The string to be sent back to the client either:
747: # ok - Everything worked just fine.
748: # error:why - There was a failure and why describes the reason.
749: #
750: #
751: sub ReinitProcess {
752: my $request = shift;
753:
1.146 foxr 754:
755: # separate the request (reinit) from the process identifier and
756: # validate it producing the name of the .pid file for the process.
757: #
758: #
759: my ($junk, $process) = split(":", $request);
1.147 foxr 760: my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146 foxr 761: if($process eq 'lonc') {
762: $processpidfile = $processpidfile."lonc.pid";
1.147 foxr 763: if (!open(PIDFILE, "< $processpidfile")) {
764: return "error:Open failed for $processpidfile";
765: }
766: my $loncpid = <PIDFILE>;
767: close(PIDFILE);
768: logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
769: ."</font>");
770: kill("USR2", $loncpid);
1.146 foxr 771: } elsif ($process eq 'lond') {
1.147 foxr 772: logthis('<font color="red"> Reinitializing self (lond) </font>');
773: &UpdateHosts; # Lond is us!!
1.146 foxr 774: } else {
775: &logthis('<font color="yellow" Invalid reinit request for '.$process
776: ."</font>");
777: return "error:Invalid process identifier $process";
778: }
1.145 foxr 779: return 'ok';
780: }
1.168 foxr 781: # Validate a line in a configuration file edit script:
782: # Validation includes:
783: # - Ensuring the command is valid.
784: # - Ensuring the command has sufficient parameters
785: # Parameters:
786: # scriptline - A line to validate (\n has been stripped for what it's worth).
1.167 foxr 787: #
1.168 foxr 788: # Return:
789: # 0 - Invalid scriptline.
790: # 1 - Valid scriptline
791: # NOTE:
792: # Only the command syntax is checked, not the executability of the
793: # command.
794: #
795: sub isValidEditCommand {
796: my $scriptline = shift;
797:
798: # Line elements are pipe separated:
799:
800: my ($command, $key, $newline) = split(/\|/, $scriptline);
801: &logthis('<font color="green"> isValideditCommand checking: '.
802: "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
803:
804: if ($command eq "delete") {
805: #
806: # key with no newline.
807: #
808: if( ($key eq "") || ($newline ne "")) {
809: return 0; # Must have key but no newline.
810: } else {
811: return 1; # Valid syntax.
812: }
1.169 foxr 813: } elsif ($command eq "replace") {
1.168 foxr 814: #
815: # key and newline:
816: #
817: if (($key eq "") || ($newline eq "")) {
818: return 0;
819: } else {
820: return 1;
821: }
1.169 foxr 822: } elsif ($command eq "append") {
823: if (($key ne "") && ($newline eq "")) {
824: return 1;
825: } else {
826: return 0;
827: }
1.168 foxr 828: } else {
829: return 0; # Invalid command.
830: }
831: return 0; # Should not get here!!!
832: }
1.169 foxr 833: #
834: # ApplyEdit - Applies an edit command to a line in a configuration
835: # file. It is the caller's responsiblity to validate the
836: # edit line.
837: # Parameters:
838: # $directive - A single edit directive to apply.
839: # Edit directives are of the form:
840: # append|newline - Appends a new line to the file.
841: # replace|key|newline - Replaces the line with key value 'key'
842: # delete|key - Deletes the line with key value 'key'.
843: # $editor - A config file editor object that contains the
844: # file being edited.
845: #
846: sub ApplyEdit {
1.192 foxr 847:
848: my ($directive, $editor) = @_;
1.169 foxr 849:
850: # Break the directive down into its command and its parameters
851: # (at most two at this point. The meaning of the parameters, if in fact
852: # they exist depends on the command).
853:
854: my ($command, $p1, $p2) = split(/\|/, $directive);
855:
856: if($command eq "append") {
857: $editor->Append($p1); # p1 - key p2 null.
858: } elsif ($command eq "replace") {
859: $editor->ReplaceLine($p1, $p2); # p1 - key p2 = newline.
860: } elsif ($command eq "delete") {
861: $editor->DeleteLine($p1); # p1 - key p2 null.
862: } else { # Should not get here!!!
863: die "Invalid command given to ApplyEdit $command"
864: }
865: }
866: #
867: # AdjustOurHost:
868: # Adjusts a host file stored in a configuration file editor object
869: # for the true IP address of this host. This is necessary for hosts
870: # that live behind a firewall.
871: # Those hosts have a publicly distributed IP of the firewall, but
872: # internally must use their actual IP. We assume that a given
873: # host only has a single IP interface for now.
874: # Formal Parameters:
875: # editor - The configuration file editor to adjust. This
876: # editor is assumed to contain a hosts.tab file.
877: # Strategy:
878: # - Figure out our hostname.
879: # - Lookup the entry for this host.
880: # - Modify the line to contain our IP
881: # - Do a replace for this host.
882: sub AdjustOurHost {
883: my $editor = shift;
884:
885: # figure out who I am.
886:
887: my $myHostName = $perlvar{'lonHostID'}; # LonCAPA hostname.
888:
889: # Get my host file entry.
890:
891: my $ConfigLine = $editor->Find($myHostName);
892: if(! (defined $ConfigLine)) {
893: die "AdjustOurHost - no entry for me in hosts file $myHostName";
894: }
895: # figure out my IP:
896: # Use the config line to get my hostname.
897: # Use gethostbyname to translate that into an IP address.
898: #
1.338 albertel 899: my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169 foxr 900: #
901: # Reassemble the config line from the elements in the list.
902: # Note that if the loncnew items were not present before, they will
903: # be now even if they would be empty
904: #
905: my $newConfigLine = $id;
1.338 albertel 906: foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169 foxr 907: $newConfigLine .= ":".$item;
908: }
909: # Replace the line:
910:
911: $editor->ReplaceLine($id, $newConfigLine);
912:
913: }
914: #
915: # ReplaceConfigFile:
916: # Replaces a configuration file with the contents of a
917: # configuration file editor object.
918: # This is done by:
919: # - Copying the target file to <filename>.old
920: # - Writing the new file to <filename>.tmp
921: # - Moving <filename.tmp> -> <filename>
922: # This laborious process ensures that the system is never without
923: # a configuration file that's at least valid (even if the contents
924: # may be dated).
925: # Parameters:
926: # filename - Name of the file to modify... this is a full path.
927: # editor - Editor containing the file.
928: #
929: sub ReplaceConfigFile {
1.192 foxr 930:
931: my ($filename, $editor) = @_;
1.168 foxr 932:
1.169 foxr 933: CopyFile ($filename, $filename.".old");
934:
935: my $contents = $editor->Get(); # Get the contents of the file.
936:
937: InstallFile($filename, $contents);
938: }
1.168 foxr 939: #
940: #
941: # Called to edit a configuration table file
1.167 foxr 942: # Parameters:
943: # request - The entire command/request sent by lonc or lonManage
944: # Return:
945: # The reply to send to the client.
1.168 foxr 946: #
1.167 foxr 947: sub EditFile {
948: my $request = shift;
949:
950: # Split the command into it's pieces: edit:filetype:script
951:
1.339 albertel 952: my ($cmd, $filetype, $script) = split(/:/, $request,3); # : in script
1.167 foxr 953:
954: # Check the pre-coditions for success:
955:
1.339 albertel 956: if($cmd != "edit") { # Something is amiss afoot alack.
1.167 foxr 957: return "error:edit request detected, but request != 'edit'\n";
958: }
959: if( ($filetype ne "hosts") &&
960: ($filetype ne "domain")) {
961: return "error:edit requested with invalid file specifier: $filetype \n";
962: }
963:
964: # Split the edit script and check it's validity.
1.168 foxr 965:
966: my @scriptlines = split(/\n/, $script); # one line per element.
967: my $linecount = scalar(@scriptlines);
968: for(my $i = 0; $i < $linecount; $i++) {
969: chomp($scriptlines[$i]);
970: if(!isValidEditCommand($scriptlines[$i])) {
971: return "error:edit with bad script line: '$scriptlines[$i]' \n";
972: }
973: }
1.145 foxr 974:
1.167 foxr 975: # Execute the edit operation.
1.169 foxr 976: # - Create a config file editor for the appropriate file and
977: # - execute each command in the script:
978: #
979: my $configfile = ConfigFileFromSelector($filetype);
980: if (!(defined $configfile)) {
981: return "refused\n";
982: }
983: my $editor = ConfigFileEdit->new($configfile);
1.167 foxr 984:
1.169 foxr 985: for (my $i = 0; $i < $linecount; $i++) {
986: ApplyEdit($scriptlines[$i], $editor);
987: }
988: # If the file is the host file, ensure that our host is
989: # adjusted to have our ip:
990: #
991: if($filetype eq "host") {
992: AdjustOurHost($editor);
993: }
994: # Finally replace the current file with our file.
995: #
996: ReplaceConfigFile($configfile, $editor);
1.167 foxr 997:
998: return "ok\n";
999: }
1.207 foxr 1000:
1.255 foxr 1001: # read_profile
1002: #
1003: # Returns a set of specific entries from a user's profile file.
1004: # this is a utility function that is used by both get_profile_entry and
1005: # get_profile_entry_encrypted.
1006: #
1007: # Parameters:
1008: # udom - Domain in which the user exists.
1009: # uname - User's account name (loncapa account)
1010: # namespace - The profile namespace to open.
1011: # what - A set of & separated queries.
1012: # Returns:
1013: # If all ok: - The string that needs to be shipped back to the user.
1014: # If failure - A string that starts with error: followed by the failure
1015: # reason.. note that this probabyl gets shipped back to the
1016: # user as well.
1017: #
1018: sub read_profile {
1019: my ($udom, $uname, $namespace, $what) = @_;
1020:
1021: my $hashref = &tie_user_hash($udom, $uname, $namespace,
1022: &GDBM_READER());
1023: if ($hashref) {
1024: my @queries=split(/\&/,$what);
1.440 raeburn 1025: if ($namespace eq 'roles') {
1026: @queries = map { &unescape($_); } @queries;
1027: }
1.255 foxr 1028: my $qresult='';
1029:
1030: for (my $i=0;$i<=$#queries;$i++) {
1031: $qresult.="$hashref->{$queries[$i]}&"; # Presumably failure gives empty string.
1032: }
1033: $qresult=~s/\&$//; # Remove trailing & from last lookup.
1.311 albertel 1034: if (&untie_user_hash($hashref)) {
1.255 foxr 1035: return $qresult;
1036: } else {
1037: return "error: ".($!+0)." untie (GDBM) Failed";
1038: }
1039: } else {
1040: if ($!+0 == 2) {
1041: return "error:No such file or GDBM reported bad block error";
1042: } else {
1043: return "error: ".($!+0)." tie (GDBM) Failed";
1044: }
1045: }
1046:
1047: }
1.214 foxr 1048: #--------------------- Request Handlers --------------------------------------------
1049: #
1.215 foxr 1050: # By convention each request handler registers itself prior to the sub
1051: # declaration:
1.214 foxr 1052: #
1053:
1.216 foxr 1054: #++
1055: #
1.214 foxr 1056: # Handles ping requests.
1057: # Parameters:
1058: # $cmd - the actual keyword that invoked us.
1059: # $tail - the tail of the request that invoked us.
1060: # $replyfd- File descriptor connected to the client
1061: # Implicit Inputs:
1062: # $currenthostid - Global variable that carries the name of the host we are
1063: # known as.
1064: # Returns:
1065: # 1 - Ok to continue processing.
1066: # 0 - Program should exit.
1067: # Side effects:
1068: # Reply information is sent to the client.
1069: sub ping_handler {
1070: my ($cmd, $tail, $client) = @_;
1071: Debug("$cmd $tail $client .. $currenthostid:");
1072:
1.387 albertel 1073: Reply( $client,\$currenthostid,"$cmd:$tail");
1.214 foxr 1074:
1075: return 1;
1076: }
1077: ®ister_handler("ping", \&ping_handler, 0, 1, 1); # Ping unencoded, client or manager.
1078:
1.216 foxr 1079: #++
1.215 foxr 1080: #
1081: # Handles pong requests. Pong replies with our current host id, and
1082: # the results of a ping sent to us via our lonc.
1083: #
1084: # Parameters:
1085: # $cmd - the actual keyword that invoked us.
1086: # $tail - the tail of the request that invoked us.
1087: # $replyfd- File descriptor connected to the client
1088: # Implicit Inputs:
1089: # $currenthostid - Global variable that carries the name of the host we are
1090: # connected to.
1091: # Returns:
1092: # 1 - Ok to continue processing.
1093: # 0 - Program should exit.
1094: # Side effects:
1095: # Reply information is sent to the client.
1096: sub pong_handler {
1097: my ($cmd, $tail, $replyfd) = @_;
1098:
1.365 albertel 1099: my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215 foxr 1100: &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail");
1101: return 1;
1102: }
1103: ®ister_handler("pong", \&pong_handler, 0, 1, 1); # Pong unencoded, client or manager
1104:
1.216 foxr 1105: #++
1106: # Called to establish an encrypted session key with the remote client.
1107: # Note that with secure lond, in most cases this function is never
1108: # invoked. Instead, the secure session key is established either
1109: # via a local file that's locked down tight and only lives for a short
1110: # time, or via an ssl tunnel...and is generated from a bunch-o-random
1111: # bits from /dev/urandom, rather than the predictable pattern used by
1112: # by this sub. This sub is only used in the old-style insecure
1113: # key negotiation.
1114: # Parameters:
1115: # $cmd - the actual keyword that invoked us.
1116: # $tail - the tail of the request that invoked us.
1117: # $replyfd- File descriptor connected to the client
1118: # Implicit Inputs:
1119: # $currenthostid - Global variable that carries the name of the host
1120: # known as.
1.448 raeburn 1121: # $clientname - Global variable that carries the name of the host we're connected to.
1.216 foxr 1122: # Returns:
1123: # 1 - Ok to continue processing.
1124: # 0 - Program should exit.
1125: # Implicit Outputs:
1126: # Reply information is sent to the client.
1127: # $cipher is set with a reference to a new IDEA encryption object.
1128: #
1129: sub establish_key_handler {
1130: my ($cmd, $tail, $replyfd) = @_;
1131:
1132: my $buildkey=time.$$.int(rand 100000);
1133: $buildkey=~tr/1-6/A-F/;
1134: $buildkey=int(rand 100000).$buildkey.int(rand 100000);
1135: my $key=$currenthostid.$clientname;
1136: $key=~tr/a-z/A-Z/;
1137: $key=~tr/G-P/0-9/;
1138: $key=~tr/Q-Z/0-9/;
1139: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
1140: $key=substr($key,0,32);
1141: my $cipherkey=pack("H32",$key);
1142: $cipher=new IDEA $cipherkey;
1.387 albertel 1143: &Reply($replyfd, \$buildkey, "$cmd:$tail");
1.216 foxr 1144:
1145: return 1;
1146:
1147: }
1148: ®ister_handler("ekey", \&establish_key_handler, 0, 1,1);
1149:
1.217 foxr 1150: # Handler for the load command. Returns the current system load average
1151: # to the requestor.
1152: #
1153: # Parameters:
1154: # $cmd - the actual keyword that invoked us.
1155: # $tail - the tail of the request that invoked us.
1156: # $replyfd- File descriptor connected to the client
1157: # Implicit Inputs:
1158: # $currenthostid - Global variable that carries the name of the host
1159: # known as.
1.448 raeburn 1160: # $clientname - Global variable that carries the name of the host we're connected to.
1.217 foxr 1161: # Returns:
1162: # 1 - Ok to continue processing.
1163: # 0 - Program should exit.
1164: # Side effects:
1165: # Reply information is sent to the client.
1166: sub load_handler {
1167: my ($cmd, $tail, $replyfd) = @_;
1168:
1.463 foxr 1169:
1170:
1.217 foxr 1171: # Get the load average from /proc/loadavg and calculate it as a percentage of
1172: # the allowed load limit as set by the perl global variable lonLoadLim
1173:
1174: my $loadavg;
1175: my $loadfile=IO::File->new('/proc/loadavg');
1176:
1177: $loadavg=<$loadfile>;
1178: $loadavg =~ s/\s.*//g; # Extract the first field only.
1179:
1180: my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
1181:
1.387 albertel 1182: &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217 foxr 1183:
1184: return 1;
1185: }
1.263 albertel 1186: ®ister_handler("load", \&load_handler, 0, 1, 0);
1.217 foxr 1187:
1188: #
1189: # Process the userload request. This sub returns to the client the current
1190: # user load average. It can be invoked either by clients or managers.
1191: #
1192: # Parameters:
1193: # $cmd - the actual keyword that invoked us.
1194: # $tail - the tail of the request that invoked us.
1195: # $replyfd- File descriptor connected to the client
1196: # Implicit Inputs:
1197: # $currenthostid - Global variable that carries the name of the host
1198: # known as.
1.448 raeburn 1199: # $clientname - Global variable that carries the name of the host we're connected to.
1.217 foxr 1200: # Returns:
1201: # 1 - Ok to continue processing.
1202: # 0 - Program should exit
1203: # Implicit inputs:
1204: # whatever the userload() function requires.
1205: # Implicit outputs:
1206: # the reply is written to the client.
1207: #
1208: sub user_load_handler {
1209: my ($cmd, $tail, $replyfd) = @_;
1210:
1.365 albertel 1211: my $userloadpercent=&Apache::lonnet::userload();
1.387 albertel 1212: &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217 foxr 1213:
1214: return 1;
1215: }
1.263 albertel 1216: ®ister_handler("userload", \&user_load_handler, 0, 1, 0);
1.217 foxr 1217:
1.218 foxr 1218: # Process a request for the authorization type of a user:
1219: # (userauth).
1220: #
1221: # Parameters:
1222: # $cmd - the actual keyword that invoked us.
1223: # $tail - the tail of the request that invoked us.
1224: # $replyfd- File descriptor connected to the client
1225: # Returns:
1226: # 1 - Ok to continue processing.
1227: # 0 - Program should exit
1228: # Implicit outputs:
1229: # The user authorization type is written to the client.
1230: #
1231: sub user_authorization_type {
1232: my ($cmd, $tail, $replyfd) = @_;
1233:
1234: my $userinput = "$cmd:$tail";
1235:
1236: # Pull the domain and username out of the command tail.
1.222 foxr 1237: # and call get_auth_type to determine the authentication type.
1.218 foxr 1238:
1239: my ($udom,$uname)=split(/:/,$tail);
1.222 foxr 1240: my $result = &get_auth_type($udom, $uname);
1.218 foxr 1241: if($result eq "nouser") {
1242: &Failure( $replyfd, "unknown_user\n", $userinput);
1243: } else {
1244: #
1.222 foxr 1245: # We only want to pass the second field from get_auth_type
1.218 foxr 1246: # for ^krb.. otherwise we'll be handing out the encrypted
1247: # password for internals e.g.
1248: #
1249: my ($type,$otherinfo) = split(/:/,$result);
1250: if($type =~ /^krb/) {
1251: $type = $result;
1.269 raeburn 1252: } else {
1253: $type .= ':';
1254: }
1.387 albertel 1255: &Reply( $replyfd, \$type, $userinput);
1.218 foxr 1256: }
1257:
1258: return 1;
1259: }
1260: ®ister_handler("currentauth", \&user_authorization_type, 1, 1, 0);
1261:
1262: # Process a request by a manager to push a hosts or domain table
1263: # to us. We pick apart the command and pass it on to the subs
1264: # that already exist to do this.
1265: #
1266: # Parameters:
1267: # $cmd - the actual keyword that invoked us.
1268: # $tail - the tail of the request that invoked us.
1269: # $client - File descriptor connected to the client
1270: # Returns:
1271: # 1 - Ok to continue processing.
1272: # 0 - Program should exit
1273: # Implicit Output:
1274: # a reply is written to the client.
1275: sub push_file_handler {
1276: my ($cmd, $tail, $client) = @_;
1.412 foxr 1277: &Debug("In push file handler");
1.218 foxr 1278: my $userinput = "$cmd:$tail";
1279:
1280: # At this time we only know that the IP of our partner is a valid manager
1281: # the code below is a hook to do further authentication (e.g. to resolve
1282: # spoofing).
1283:
1284: my $cert = &GetCertificate($userinput);
1.412 foxr 1285: if(&ValidManager($cert)) {
1286: &Debug("Valid manager: $client");
1.218 foxr 1287:
1288: # Now presumably we have the bona fides of both the peer host and the
1289: # process making the request.
1290:
1291: my $reply = &PushFile($userinput);
1.387 albertel 1292: &Reply($client, \$reply, $userinput);
1.218 foxr 1293:
1294: } else {
1.412 foxr 1295: &logthis("push_file_handler $client is not valid");
1.218 foxr 1296: &Failure( $client, "refused\n", $userinput);
1297: }
1.219 foxr 1298: return 1;
1.218 foxr 1299: }
1300: ®ister_handler("pushfile", \&push_file_handler, 1, 0, 1);
1301:
1.399 raeburn 1302: # The du_handler routine should be considered obsolete and is retained
1303: # for communication with legacy servers. Please see the du2_handler.
1.243 banghart 1304: #
1.399 raeburn 1305: # du - list the disk usage of a directory recursively.
1.243 banghart 1306: #
1307: # note: stolen code from the ls file handler
1308: # under construction by Rick Banghart
1309: # .
1310: # Parameters:
1311: # $cmd - The command that dispatched us (du).
1312: # $ududir - The directory path to list... I'm not sure what this
1313: # is relative as things like ls:. return e.g.
1314: # no_such_dir.
1315: # $client - Socket open on the client.
1316: # Returns:
1317: # 1 - indicating that the daemon should not disconnect.
1318: # Side Effects:
1319: # The reply is written to $client.
1320: #
1321: sub du_handler {
1322: my ($cmd, $ududir, $client) = @_;
1.339 albertel 1323: ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251 foxr 1324: my $userinput = "$cmd:$ududir";
1325:
1.245 albertel 1326: if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
1327: &Failure($client,"refused\n","$cmd:$ududir");
1328: return 1;
1329: }
1.249 foxr 1330: # Since $ududir could have some nasties in it,
1331: # we will require that ududir is a valid
1332: # directory. Just in case someone tries to
1333: # slip us a line like .;(cd /home/httpd rm -rf*)
1334: # etc.
1335: #
1336: if (-d $ududir) {
1.292 albertel 1337: my $total_size=0;
1338: my $code=sub {
1339: if ($_=~/\.\d+\./) { return;}
1340: if ($_=~/\.meta$/) { return;}
1.362 albertel 1341: if (-d $_) { return;}
1.292 albertel 1342: $total_size+=(stat($_))[7];
1343: };
1.295 raeburn 1344: chdir($ududir);
1.292 albertel 1345: find($code,$ududir);
1346: $total_size=int($total_size/1024);
1.387 albertel 1347: &Reply($client,\$total_size,"$cmd:$ududir");
1.249 foxr 1348: } else {
1.251 foxr 1349: &Failure($client, "bad_directory:$ududir\n","$cmd:$ududir");
1.249 foxr 1350: }
1.243 banghart 1351: return 1;
1352: }
1353: ®ister_handler("du", \&du_handler, 0, 1, 0);
1.218 foxr 1354:
1.399 raeburn 1355: # Please also see the du_handler, which is obsoleted by du2.
1356: # du2_handler differs from du_handler in that required path to directory
1357: # provided by &propath() is prepended in the handler instead of on the
1358: # client side.
1.239 foxr 1359: #
1.399 raeburn 1360: # du2 - list the disk usage of a directory recursively.
1361: #
1362: # Parameters:
1363: # $cmd - The command that dispatched us (du).
1364: # $tail - The tail of the request that invoked us.
1365: # $tail is a : separated list of the following:
1366: # - $ududir - directory path to list (before prepending)
1367: # - $getpropath = 1 if &propath() should prepend
1368: # - $uname - username to use for &propath or user dir
1369: # - $udom - domain to use for &propath or user dir
1370: # All are escaped.
1371: # $client - Socket open on the client.
1372: # Returns:
1373: # 1 - indicating that the daemon should not disconnect.
1374: # Side Effects:
1375: # The reply is written to $client.
1376: #
1377:
1378: sub du2_handler {
1379: my ($cmd, $tail, $client) = @_;
1380: my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
1381: my $userinput = "$cmd:$tail";
1382: if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
1383: &Failure($client,"refused\n","$cmd:$tail");
1384: return 1;
1385: }
1386: if ($getpropath) {
1387: if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
1388: $ududir = &propath($udom,$uname).'/'.$ududir;
1389: } else {
1390: &Failure($client,"refused\n","$cmd:$tail");
1391: return 1;
1392: }
1393: }
1394: # Since $ududir could have some nasties in it,
1395: # we will require that ududir is a valid
1396: # directory. Just in case someone tries to
1397: # slip us a line like .;(cd /home/httpd rm -rf*)
1398: # etc.
1399: #
1400: if (-d $ududir) {
1401: my $total_size=0;
1402: my $code=sub {
1403: if ($_=~/\.\d+\./) { return;}
1404: if ($_=~/\.meta$/) { return;}
1405: if (-d $_) { return;}
1406: $total_size+=(stat($_))[7];
1407: };
1408: chdir($ududir);
1409: find($code,$ududir);
1410: $total_size=int($total_size/1024);
1411: &Reply($client,\$total_size,"$cmd:$ududir");
1412: } else {
1413: &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
1414: }
1415: return 1;
1416: }
1417: ®ister_handler("du2", \&du2_handler, 0, 1, 0);
1418:
1419: #
1420: # The ls_handler routine should be considered obsolete and is retained
1421: # for communication with legacy servers. Please see the ls3_handler.
1.280 matthew 1422: #
1.239 foxr 1423: # ls - list the contents of a directory. For each file in the
1424: # selected directory the filename followed by the full output of
1425: # the stat function is returned. The returned info for each
1426: # file are separated by ':'. The stat fields are separated by &'s.
1.489.2.23 raeburn 1427: #
1428: # If the requested path contains /../ or is:
1429: #
1430: # 1. for a directory, and the path does not begin with one of:
1.489.2.25 raeburn 1431: # (a) /home/httpd/html/res/<domain>
1.489.2.28 raeburn 1432: # (b) /home/httpd/html/userfiles/
1.489.2.23 raeburn 1433: # (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1434: # or is:
1435: #
1.489.2.28 raeburn 1436: # 2. for a file, and the path (after prepending) does not begin with one of:
1437: # (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
1438: # (b) /home/httpd/html/res/<domain>/<username>/
1439: # (c) /home/httpd/html/userfiles/<domain>/<username>/
1.489.2.23 raeburn 1440: #
1441: # the response will be "refused".
1442: #
1.239 foxr 1443: # Parameters:
1444: # $cmd - The command that dispatched us (ls).
1445: # $ulsdir - The directory path to list... I'm not sure what this
1446: # is relative as things like ls:. return e.g.
1447: # no_such_dir.
1448: # $client - Socket open on the client.
1449: # Returns:
1450: # 1 - indicating that the daemon should not disconnect.
1451: # Side Effects:
1452: # The reply is written to $client.
1453: #
1454: sub ls_handler {
1.280 matthew 1455: # obsoleted by ls2_handler
1.239 foxr 1456: my ($cmd, $ulsdir, $client) = @_;
1457:
1458: my $userinput = "$cmd:$ulsdir";
1459:
1460: my $obs;
1461: my $rights;
1462: my $ulsout='';
1463: my $ulsfn;
1.489.2.23 raeburn 1464: if ($ulsdir =~m{/\.\./}) {
1465: &Failure($client,"refused\n",$userinput);
1466: return 1;
1467: }
1.239 foxr 1468: if (-e $ulsdir) {
1469: if(-d $ulsdir) {
1.489.2.28 raeburn 1470: unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
1471: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.489.2.23 raeburn 1472: &Failure($client,"refused\n",$userinput);
1473: return 1;
1474: }
1.239 foxr 1475: if (opendir(LSDIR,$ulsdir)) {
1476: while ($ulsfn=readdir(LSDIR)) {
1.291 albertel 1477: undef($obs);
1478: undef($rights);
1.239 foxr 1479: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1480: #We do some obsolete checking here
1481: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1482: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1483: my @obsolete=<FILE>;
1484: foreach my $obsolete (@obsolete) {
1.301 www 1485: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1.239 foxr 1486: if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
1487: }
1488: }
1489: $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
1490: if($obs eq '1') { $ulsout.="&1"; }
1491: else { $ulsout.="&0"; }
1492: if($rights eq '1') { $ulsout.="&1:"; }
1493: else { $ulsout.="&0:"; }
1494: }
1495: closedir(LSDIR);
1496: }
1497: } else {
1.489.2.28 raeburn 1498: unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
1499: ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.489.2.23 raeburn 1500: &Failure($client,"refused\n",$userinput);
1501: return 1;
1502: }
1.239 foxr 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'; }
1.387 albertel 1510: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239 foxr 1511:
1512: return 1;
1513:
1514: }
1515: ®ister_handler("ls", \&ls_handler, 0, 1, 0);
1516:
1.399 raeburn 1517: # The ls2_handler routine should be considered obsolete and is retained
1518: # for communication with legacy servers. Please see the ls3_handler.
1519: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280 matthew 1520: # ls2_handler differs from ls_handler in that it escapes its return
1521: # values before concatenating them together with ':'s.
1522: #
1523: # ls2 - list the contents of a directory. For each file in the
1524: # selected directory the filename followed by the full output of
1525: # the stat function is returned. The returned info for each
1526: # file are separated by ':'. The stat fields are separated by &'s.
1.489.2.23 raeburn 1527: #
1528: # If the requested path contains /../ or is:
1529: #
1530: # 1. for a directory, and the path does not begin with one of:
1.489.2.25 raeburn 1531: # (a) /home/httpd/html/res/<domain>
1.489.2.28 raeburn 1532: # (b) /home/httpd/html/userfiles/
1.489.2.23 raeburn 1533: # (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1534: # or is:
1535: #
1.489.2.28 raeburn 1536: # 2. for a file, and the path (after prepending) does not begin with one of:
1537: # (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
1538: # (b) /home/httpd/html/res/<domain>/<username>/
1539: # (c) /home/httpd/html/userfiles/<domain>/<username>/
1.489.2.23 raeburn 1540: #
1541: # the response will be "refused".
1542: #
1.280 matthew 1543: # Parameters:
1544: # $cmd - The command that dispatched us (ls).
1545: # $ulsdir - The directory path to list... I'm not sure what this
1546: # is relative as things like ls:. return e.g.
1547: # no_such_dir.
1548: # $client - Socket open on the client.
1549: # Returns:
1550: # 1 - indicating that the daemon should not disconnect.
1551: # Side Effects:
1552: # The reply is written to $client.
1553: #
1554: sub ls2_handler {
1555: my ($cmd, $ulsdir, $client) = @_;
1556:
1557: my $userinput = "$cmd:$ulsdir";
1558:
1559: my $obs;
1560: my $rights;
1561: my $ulsout='';
1562: my $ulsfn;
1.489.2.23 raeburn 1563: if ($ulsdir =~m{/\.\./}) {
1564: &Failure($client,"refused\n",$userinput);
1565: return 1;
1566: }
1.280 matthew 1567: if (-e $ulsdir) {
1568: if(-d $ulsdir) {
1.489.2.28 raeburn 1569: unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
1570: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.489.2.23 raeburn 1571: &Failure($client,"refused\n","$userinput");
1572: return 1;
1573: }
1.280 matthew 1574: if (opendir(LSDIR,$ulsdir)) {
1575: while ($ulsfn=readdir(LSDIR)) {
1.291 albertel 1576: undef($obs);
1577: undef($rights);
1.280 matthew 1578: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1579: #We do some obsolete checking here
1580: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1581: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1582: my @obsolete=<FILE>;
1583: foreach my $obsolete (@obsolete) {
1.301 www 1584: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1.280 matthew 1585: if($obsolete =~ m|(<copyright>)(default)|) {
1586: $rights = 1;
1587: }
1588: }
1589: }
1590: my $tmp = $ulsfn.'&'.join('&',@ulsstats);
1591: if ($obs eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1592: if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1593: $ulsout.= &escape($tmp).':';
1594: }
1595: closedir(LSDIR);
1596: }
1597: } else {
1.489.2.28 raeburn 1598: unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
1599: ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.489.2.23 raeburn 1600: &Failure($client,"refused\n",$userinput);
1601: return 1;
1602: }
1.280 matthew 1603: my @ulsstats=stat($ulsdir);
1604: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1605: }
1606: } else {
1607: $ulsout='no_such_dir';
1608: }
1609: if ($ulsout eq '') { $ulsout='empty'; }
1.387 albertel 1610: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280 matthew 1611: return 1;
1612: }
1613: ®ister_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399 raeburn 1614: #
1615: # ls3 - list the contents of a directory. For each file in the
1616: # selected directory the filename followed by the full output of
1617: # the stat function is returned. The returned info for each
1618: # file are separated by ':'. The stat fields are separated by &'s.
1.489.2.23 raeburn 1619: #
1620: # If the requested path (after prepending) contains /../ or is:
1621: #
1622: # 1. for a directory, and the path does not begin with one of:
1.489.2.25 raeburn 1623: # (a) /home/httpd/html/res/<domain>
1.489.2.28 raeburn 1624: # (b) /home/httpd/html/userfiles/
1.489.2.23 raeburn 1625: # (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.489.2.28 raeburn 1626: # (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.489.2.23 raeburn 1627: #
1628: # or is:
1629: #
1.489.2.28 raeburn 1630: # 2. for a file, and the path (after prepending) does not begin with one of:
1631: # (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
1632: # (b) /home/httpd/html/res/<domain>/<username>/
1633: # (c) /home/httpd/html/userfiles/<domain>/<username>/
1634: # (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.489.2.23 raeburn 1635: #
1636: # the response will be "refused".
1637: #
1.399 raeburn 1638: # Parameters:
1639: # $cmd - The command that dispatched us (ls).
1640: # $tail - The tail of the request that invoked us.
1641: # $tail is a : separated list of the following:
1642: # - $ulsdir - directory path to list (before prepending)
1643: # - $getpropath = 1 if &propath() should prepend
1644: # - $getuserdir = 1 if path to user dir in lonUsers should
1645: # prepend
1646: # - $alternate_root - path to prepend
1647: # - $uname - username to use for &propath or user dir
1648: # - $udom - domain to use for &propath or user dir
1649: # All of these except $getpropath and &getuserdir are escaped.
1650: # no_such_dir.
1651: # $client - Socket open on the client.
1652: # Returns:
1653: # 1 - indicating that the daemon should not disconnect.
1654: # Side Effects:
1655: # The reply is written to $client.
1656: #
1657:
1658: sub ls3_handler {
1659: my ($cmd, $tail, $client) = @_;
1660: my $userinput = "$cmd:$tail";
1661: my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
1662: split(/:/,$tail);
1663: if (defined($ulsdir)) {
1664: $ulsdir = &unescape($ulsdir);
1665: }
1666: if (defined($alternate_root)) {
1667: $alternate_root = &unescape($alternate_root);
1668: }
1669: if (defined($uname)) {
1670: $uname = &unescape($uname);
1671: }
1672: if (defined($udom)) {
1673: $udom = &unescape($udom);
1674: }
1675:
1676: my $dir_root = $perlvar{'lonDocRoot'};
1.489.2.23 raeburn 1677: if (($getpropath) || ($getuserdir)) {
1.399 raeburn 1678: if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
1679: $dir_root = &propath($udom,$uname);
1680: $dir_root =~ s/\/$//;
1681: } else {
1.489.2.23 raeburn 1682: &Failure($client,"refused\n",$userinput);
1.399 raeburn 1683: return 1;
1684: }
1.400 raeburn 1685: } elsif ($alternate_root ne '') {
1.399 raeburn 1686: $dir_root = $alternate_root;
1687: }
1.408 raeburn 1688: if (($dir_root ne '') && ($dir_root ne '/')) {
1.400 raeburn 1689: if ($ulsdir =~ /^\//) {
1690: $ulsdir = $dir_root.$ulsdir;
1691: } else {
1692: $ulsdir = $dir_root.'/'.$ulsdir;
1693: }
1.399 raeburn 1694: }
1.489.2.23 raeburn 1695: if ($ulsdir =~m{/\.\./}) {
1696: &Failure($client,"refused\n",$userinput);
1697: return 1;
1698: }
1699: my $islocal;
1700: my @machine_ids = &Apache::lonnet::current_machine_ids();
1701: if (grep(/^\Q$clientname\E$/,@machine_ids)) {
1702: $islocal = 1;
1703: }
1.399 raeburn 1704: my $obs;
1705: my $rights;
1706: my $ulsout='';
1707: my $ulsfn;
1708: if (-e $ulsdir) {
1709: if(-d $ulsdir) {
1.489.2.23 raeburn 1710: unless (($getpropath) || ($getuserdir) ||
1.489.2.28 raeburn 1711: ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
1712: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
1713: (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.489.2.23 raeburn 1714: &Failure($client,"refused\n",$userinput);
1715: return 1;
1716: }
1.399 raeburn 1717: if (opendir(LSDIR,$ulsdir)) {
1718: while ($ulsfn=readdir(LSDIR)) {
1719: undef($obs);
1720: undef($rights);
1721: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1722: #We do some obsolete checking here
1723: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1724: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1725: my @obsolete=<FILE>;
1726: foreach my $obsolete (@obsolete) {
1727: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1728: if($obsolete =~ m|(<copyright>)(default)|) {
1729: $rights = 1;
1730: }
1731: }
1732: }
1733: my $tmp = $ulsfn.'&'.join('&',@ulsstats);
1734: if ($obs eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1735: if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1736: $ulsout.= &escape($tmp).':';
1737: }
1738: closedir(LSDIR);
1739: }
1740: } else {
1.489.2.23 raeburn 1741: unless (($getpropath) || ($getuserdir) ||
1.489.2.28 raeburn 1742: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
1743: ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
1744: (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.489.2.23 raeburn 1745: &Failure($client,"refused\n",$userinput);
1746: return 1;
1747: }
1.399 raeburn 1748: my @ulsstats=stat($ulsdir);
1749: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1750: }
1751: } else {
1752: $ulsout='no_such_dir';
1.400 raeburn 1753: }
1754: if ($ulsout eq '') { $ulsout='empty'; }
1755: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1756: return 1;
1.399 raeburn 1757: }
1758: ®ister_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280 matthew 1759:
1.477 raeburn 1760: sub read_lonnet_global {
1761: my ($cmd,$tail,$client) = @_;
1762: my $userinput = "$cmd:$tail";
1763: my $requested = &Apache::lonnet::thaw_unescape($tail);
1764: my $result;
1.480 raeburn 1765: my %packagevars = (
1766: spareid => \%Apache::lonnet::spareid,
1767: perlvar => \%Apache::lonnet::perlvar,
1768: );
1769: my %limit_to = (
1770: perlvar => {
1771: lonOtherAuthen => 1,
1772: lonBalancer => 1,
1773: lonVersion => 1,
1774: lonSysEMail => 1,
1775: lonHostID => 1,
1776: lonRole => 1,
1777: lonDefDomain => 1,
1778: lonLoadLim => 1,
1779: lonUserLoadLim => 1,
1780: }
1781: );
1.477 raeburn 1782: if (ref($requested) eq 'HASH') {
1783: foreach my $what (keys(%{$requested})) {
1784: my $response;
1.480 raeburn 1785: my $items = {};
1786: if (exists($packagevars{$what})) {
1787: if (ref($limit_to{$what}) eq 'HASH') {
1788: foreach my $varname (keys(%{$packagevars{$what}})) {
1789: if ($limit_to{$what}{$varname}) {
1790: $items->{$varname} = $packagevars{$what}{$varname};
1791: }
1792: }
1793: } else {
1794: $items = $packagevars{$what};
1.477 raeburn 1795: }
1.480 raeburn 1796: if ($what eq 'perlvar') {
1797: if (!exists($packagevars{$what}{'lonBalancer'})) {
1.489.2.43 raeburn 1798: if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
1.480 raeburn 1799: my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
1800: if (ref($othervarref) eq 'HASH') {
1801: $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
1802: }
1803: }
1804: }
1.477 raeburn 1805: }
1.480 raeburn 1806: $response = &Apache::lonnet::freeze_escape($items);
1.477 raeburn 1807: }
1.478 raeburn 1808: $result .= &escape($what).'='.$response.'&';
1.477 raeburn 1809: }
1810: }
1811: $result =~ s/\&$//;
1812: &Reply($client,\$result,$userinput);
1813: return 1;
1814: }
1815: ®ister_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
1816:
1.479 raeburn 1817: sub server_devalidatecache_handler {
1818: my ($cmd,$tail,$client) = @_;
1819: my $userinput = "$cmd:$tail";
1.489.2.9 raeburn 1820: my $items = &unescape($tail);
1821: my @cached = split(/\&/,$items);
1822: foreach my $key (@cached) {
1823: if ($key =~ /:/) {
1824: my ($name,$id) = map { &unescape($_); } split(/:/,$key);
1825: &Apache::lonnet::devalidate_cache_new($name,$id);
1826: }
1827: }
1.479 raeburn 1828: my $result = 'ok';
1829: &Reply($client,\$result,$userinput);
1830: return 1;
1831: }
1.481 raeburn 1832: ®ister_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479 raeburn 1833:
1.410 raeburn 1834: sub server_timezone_handler {
1835: my ($cmd,$tail,$client) = @_;
1836: my $userinput = "$cmd:$tail";
1837: my $timezone;
1838: my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
1839: my $tzfile = '/etc/timezone'; # Debian/Ubuntu
1840: if (-e $clockfile) {
1841: if (open(my $fh,"<$clockfile")) {
1842: while (<$fh>) {
1843: next if (/^[\#\s]/);
1844: if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
1845: $timezone = $1;
1846: last;
1847: }
1848: }
1849: close($fh);
1850: }
1851: } elsif (-e $tzfile) {
1852: if (open(my $fh,"<$tzfile")) {
1853: $timezone = <$fh>;
1854: close($fh);
1855: chomp($timezone);
1856: if ($timezone =~ m{^Etc/(\w+)$}) {
1857: $timezone = $1;
1858: }
1859: }
1860: }
1861: &Reply($client,\$timezone,$userinput); # This supports debug logging.
1862: return 1;
1863: }
1864: ®ister_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
1865:
1.413 raeburn 1866: sub server_loncaparev_handler {
1867: my ($cmd,$tail,$client) = @_;
1868: my $userinput = "$cmd:$tail";
1869: &Reply($client,\$perlvar{'lonVersion'},$userinput);
1870: return 1;
1871: }
1872: ®ister_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
1873:
1.448 raeburn 1874: sub server_homeID_handler {
1875: my ($cmd,$tail,$client) = @_;
1876: my $userinput = "$cmd:$tail";
1877: &Reply($client,\$perlvar{'lonHostID'},$userinput);
1878: return 1;
1879: }
1880: ®ister_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
1881:
1.471 raeburn 1882: sub server_distarch_handler {
1883: my ($cmd,$tail,$client) = @_;
1884: my $userinput = "$cmd:$tail";
1885: my $reply = &distro_and_arch();
1886: &Reply($client,\$reply,$userinput);
1887: return 1;
1888: }
1889: ®ister_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
1890:
1.218 foxr 1891: # Process a reinit request. Reinit requests that either
1892: # lonc or lond be reinitialized so that an updated
1893: # host.tab or domain.tab can be processed.
1894: #
1895: # Parameters:
1896: # $cmd - the actual keyword that invoked us.
1897: # $tail - the tail of the request that invoked us.
1898: # $client - File descriptor connected to the client
1899: # Returns:
1900: # 1 - Ok to continue processing.
1901: # 0 - Program should exit
1902: # Implicit output:
1903: # a reply is sent to the client.
1904: #
1905: sub reinit_process_handler {
1906: my ($cmd, $tail, $client) = @_;
1907:
1908: my $userinput = "$cmd:$tail";
1909:
1910: my $cert = &GetCertificate($userinput);
1911: if(&ValidManager($cert)) {
1912: chomp($userinput);
1913: my $reply = &ReinitProcess($userinput);
1.387 albertel 1914: &Reply( $client, \$reply, $userinput);
1.218 foxr 1915: } else {
1916: &Failure( $client, "refused\n", $userinput);
1917: }
1918: return 1;
1919: }
1920: ®ister_handler("reinit", \&reinit_process_handler, 1, 0, 1);
1921:
1922: # Process the editing script for a table edit operation.
1923: # the editing operation must be encrypted and requested by
1924: # a manager host.
1925: #
1926: # Parameters:
1927: # $cmd - the actual keyword that invoked us.
1928: # $tail - the tail of the request that invoked us.
1929: # $client - File descriptor connected to the client
1930: # Returns:
1931: # 1 - Ok to continue processing.
1932: # 0 - Program should exit
1933: # Implicit output:
1934: # a reply is sent to the client.
1935: #
1936: sub edit_table_handler {
1937: my ($command, $tail, $client) = @_;
1938:
1939: my $userinput = "$command:$tail";
1940:
1941: my $cert = &GetCertificate($userinput);
1942: if(&ValidManager($cert)) {
1943: my($filetype, $script) = split(/:/, $tail);
1944: if (($filetype eq "hosts") ||
1945: ($filetype eq "domain")) {
1946: if($script ne "") {
1947: &Reply($client, # BUGBUG - EditFile
1948: &EditFile($userinput), # could fail.
1949: $userinput);
1950: } else {
1951: &Failure($client,"refused\n",$userinput);
1952: }
1953: } else {
1954: &Failure($client,"refused\n",$userinput);
1955: }
1956: } else {
1957: &Failure($client,"refused\n",$userinput);
1958: }
1959: return 1;
1960: }
1.263 albertel 1961: ®ister_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218 foxr 1962:
1.220 foxr 1963: #
1964: # Authenticate a user against the LonCAPA authentication
1965: # database. Note that there are several authentication
1966: # possibilities:
1967: # - unix - The user can be authenticated against the unix
1968: # password file.
1969: # - internal - The user can be authenticated against a purely
1970: # internal per user password file.
1971: # - kerberos - The user can be authenticated against either a kerb4 or kerb5
1972: # ticket granting authority.
1973: # - user - The person tailoring LonCAPA can supply a user authentication
1974: # mechanism that is per system.
1975: #
1976: # Parameters:
1977: # $cmd - The command that got us here.
1978: # $tail - Tail of the command (remaining parameters).
1979: # $client - File descriptor connected to client.
1980: # Returns
1981: # 0 - Requested to exit, caller should shut down.
1982: # 1 - Continue processing.
1983: # Implicit inputs:
1984: # The authentication systems describe above have their own forms of implicit
1985: # input into the authentication process that are described above.
1986: #
1987: sub authenticate_handler {
1988: my ($cmd, $tail, $client) = @_;
1989:
1990:
1991: # Regenerate the full input line
1992:
1993: my $userinput = $cmd.":".$tail;
1994:
1995: # udom - User's domain.
1996: # uname - Username.
1997: # upass - User's password.
1.396 raeburn 1998: # checkdefauth - Pass to validate_user() to try authentication
1999: # with default auth type(s) if no user account.
1.447 raeburn 2000: # clientcancheckhost - Passed by clients with functionality in lonauth.pm
2001: # to check if session can be hosted.
1.220 foxr 2002:
1.447 raeburn 2003: my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399 raeburn 2004: &Debug(" Authenticate domain = $udom, user = $uname, password = $upass, checkdefauth = $checkdefauth");
1.220 foxr 2005: chomp($upass);
2006: $upass=&unescape($upass);
2007:
1.396 raeburn 2008: my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220 foxr 2009: if($pwdcorrect) {
1.447 raeburn 2010: my $canhost = 1;
2011: unless ($clientcancheckhost) {
1.448 raeburn 2012: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
2013: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452 raeburn 2014: my @intdoms;
2015: my $internet_names = &Apache::lonnet::get_internet_names($clientname);
2016: if (ref($internet_names) eq 'ARRAY') {
2017: @intdoms = @{$internet_names};
2018: }
1.448 raeburn 2019: unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447 raeburn 2020: my ($remote,$hosted);
2021: my $remotesession = &get_usersession_config($udom,'remotesession');
2022: if (ref($remotesession) eq 'HASH') {
1.489.2.32 raeburn 2023: $remote = $remotesession->{'remote'};
1.447 raeburn 2024: }
1.448 raeburn 2025: my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447 raeburn 2026: if (ref($hostedsession) eq 'HASH') {
2027: $hosted = $hostedsession->{'hosted'};
2028: }
1.449 raeburn 2029: my $loncaparev = $clientversion;
2030: if ($loncaparev eq '') {
2031: $loncaparev = $Apache::lonnet::loncaparevs{$clientname};
2032: }
1.448 raeburn 2033: $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.449 raeburn 2034: $loncaparev,
1.447 raeburn 2035: $remote,$hosted);
2036: }
2037: }
2038: if ($canhost) {
2039: &Reply( $client, "authorized\n", $userinput);
2040: } else {
2041: &Reply( $client, "not_allowed_to_host\n", $userinput);
2042: }
1.220 foxr 2043: #
2044: # Bad credentials: Failed to authorize
2045: #
2046: } else {
2047: &Failure( $client, "non_authorized\n", $userinput);
2048: }
2049:
2050: return 1;
2051: }
1.263 albertel 2052: ®ister_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214 foxr 2053:
1.222 foxr 2054: #
2055: # Change a user's password. Note that this function is complicated by
2056: # the fact that a user may be authenticated in more than one way:
2057: # At present, we are not able to change the password for all types of
2058: # authentication methods. Only for:
2059: # unix - unix password or shadow passoword style authentication.
2060: # local - Locally written authentication mechanism.
2061: # For now, kerb4 and kerb5 password changes are not supported and result
2062: # in an error.
2063: # FUTURE WORK:
2064: # Support kerberos passwd changes?
2065: # Parameters:
2066: # $cmd - The command that got us here.
2067: # $tail - Tail of the command (remaining parameters).
2068: # $client - File descriptor connected to client.
2069: # Returns
2070: # 0 - Requested to exit, caller should shut down.
2071: # 1 - Continue processing.
2072: # Implicit inputs:
2073: # The authentication systems describe above have their own forms of implicit
2074: # input into the authentication process that are described above.
2075: sub change_password_handler {
2076: my ($cmd, $tail, $client) = @_;
2077:
2078: my $userinput = $cmd.":".$tail; # Reconstruct client's string.
2079:
2080: #
2081: # udom - user's domain.
2082: # uname - Username.
2083: # upass - Current password.
2084: # npass - New password.
1.346 raeburn 2085: # context - Context in which this was called
2086: # (preferences or reset_by_email).
1.428 raeburn 2087: # lonhost - HostID of server where request originated
1.222 foxr 2088:
1.428 raeburn 2089: my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222 foxr 2090:
2091: $upass=&unescape($upass);
2092: $npass=&unescape($npass);
2093: &Debug("Trying to change password for $uname");
2094:
2095: # First require that the user can be authenticated with their
1.346 raeburn 2096: # old password unless context was 'reset_by_email':
2097:
1.428 raeburn 2098: my ($validated,$failure);
1.346 raeburn 2099: if ($context eq 'reset_by_email') {
1.428 raeburn 2100: if ($lonhost eq '') {
2101: $failure = 'invalid_client';
2102: } else {
2103: $validated = 1;
2104: }
1.346 raeburn 2105: } else {
2106: $validated = &validate_user($udom, $uname, $upass);
2107: }
1.222 foxr 2108: if($validated) {
2109: my $realpasswd = &get_auth_type($udom, $uname); # Defined since authd.
2110: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.489.2.33 raeburn 2111: my $notunique;
1.222 foxr 2112: if ($howpwd eq 'internal') {
2113: &Debug("internal auth");
1.489.2.21 raeburn 2114: my $ncpass = &hash_passwd($udom,$npass);
1.489.2.33 raeburn 2115: my (undef,$method,@rest) = split(/!/,$contentpwd);
2116: if ($method eq 'bcrypt') {
2117: my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
2118: if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
2119: my @oldpasswds;
2120: my $userpath = &propath($udom,$uname);
2121: my $fullpath = $userpath.'/oldpasswds';
2122: if (-d $userpath) {
2123: my @oldfiles;
2124: if (-e $fullpath) {
2125: if (opendir(my $dir,$fullpath)) {
2126: (@oldfiles) = grep(/^\d+$/,readdir($dir));
2127: closedir($dir);
2128: }
2129: if (@oldfiles) {
2130: @oldfiles = sort { $b <=> $a } (@oldfiles);
2131: my $numremoved = 0;
2132: for (my $i=0; $i<@oldfiles; $i++) {
2133: if ($i>=$passwdconf{'numsaved'}) {
2134: if (-f "$fullpath/$oldfiles[$i]") {
2135: if (unlink("$fullpath/$oldfiles[$i]")) {
2136: $numremoved ++;
2137: }
2138: }
2139: } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
2140: while (my $line = <$fh>) {
2141: push(@oldpasswds,$line);
2142: }
2143: close($fh);
2144: }
2145: }
2146: if ($numremoved) {
2147: &logthis("unlinked $numremoved old password files for $uname:$udom");
2148: }
2149: }
2150: }
2151: push(@oldpasswds,$contentpwd);
2152: foreach my $item (@oldpasswds) {
2153: my (undef,$method,@rest) = split(/!/,$item);
2154: if ($method eq 'bcrypt') {
2155: my $result = &hash_passwd($udom,$npass,@rest);
2156: if ($result eq $item) {
2157: $notunique = 1;
2158: last;
2159: }
2160: }
2161: }
2162: unless ($notunique) {
2163: unless (-e $fullpath) {
2164: if (&mkpath("$fullpath/")) {
2165: chmod(0700,$fullpath);
2166: }
2167: }
2168: if (-d $fullpath) {
2169: my $now = time;
2170: if (open(my $fh,'>',"$fullpath/$now")) {
2171: print $fh $contentpwd;
2172: close($fh);
2173: chmod(0400,"$fullpath/$now");
2174: }
2175: }
2176: }
2177: }
2178: }
2179: }
2180: if ($notunique) {
2181: my $msg="Result of password change for $uname:$udom - password matches one used before";
2182: if ($lonhost) {
2183: $msg .= " - request originated from: $lonhost";
2184: }
2185: &logthis($msg);
2186: &Reply($client, "prioruse\n", $userinput);
2187: } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428 raeburn 2188: my $msg="Result of password change for $uname: pwchange_success";
2189: if ($lonhost) {
2190: $msg .= " - request originated from: $lonhost";
2191: }
2192: &logthis($msg);
1.489.2.21 raeburn 2193: &update_passwd_history($uname,$udom,$howpwd,$context);
1.222 foxr 2194: &Reply($client, "ok\n", $userinput);
2195: } else {
2196: &logthis("Unable to open $uname passwd "
2197: ."to change password");
2198: &Failure( $client, "non_authorized\n",$userinput);
2199: }
1.346 raeburn 2200: } elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287 foxr 2201: my $result = &change_unix_password($uname, $npass);
1.489.2.21 raeburn 2202: if ($result eq 'ok') {
2203: &update_passwd_history($uname,$udom,$howpwd,$context);
2204: }
1.222 foxr 2205: &logthis("Result of password change for $uname: ".
1.287 foxr 2206: $result);
1.387 albertel 2207: &Reply($client, \$result, $userinput);
1.222 foxr 2208: } else {
2209: # this just means that the current password mode is not
2210: # one we know how to change (e.g the kerberos auth modes or
2211: # locally written auth handler).
2212: #
2213: &Failure( $client, "auth_mode_error\n", $userinput);
2214: }
1.224 foxr 2215: } else {
1.428 raeburn 2216: if ($failure eq '') {
2217: $failure = 'non_authorized';
2218: }
2219: &Failure( $client, "$failure\n", $userinput);
1.222 foxr 2220: }
2221:
2222: return 1;
2223: }
1.263 albertel 2224: ®ister_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222 foxr 2225:
1.489.2.21 raeburn 2226: sub hash_passwd {
2227: my ($domain,$plainpass,@rest) = @_;
2228: my ($salt,$cost);
2229: if (@rest) {
2230: $cost = $rest[0];
2231: # salt is first 22 characters, base-64 encoded by bcrypt
2232: my $plainsalt = substr($rest[1],0,22);
2233: $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
2234: } else {
1.489.2.26 raeburn 2235: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2236: my $defaultcost = $domdefaults{'intauth_cost'};
1.489.2.21 raeburn 2237: if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
2238: $cost = 10;
2239: } else {
2240: $cost = $defaultcost;
2241: }
2242: # Generate random 16-octet base64 salt
2243: $salt = "";
2244: $salt .= pack("C", int rand(256)) for 1..16;
2245: }
2246: my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
2247: key_nul => 1,
2248: cost => $cost,
2249: salt => $salt,
2250: }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
2251:
2252: my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
2253: &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
2254: &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
2255: return $result;
2256: }
2257:
1.225 foxr 2258: #
2259: # Create a new user. User in this case means a lon-capa user.
2260: # The user must either already exist in some authentication realm
2261: # like kerberos or the /etc/passwd. If not, a user completely local to
2262: # this loncapa system is created.
2263: #
2264: # Parameters:
2265: # $cmd - The command that got us here.
2266: # $tail - Tail of the command (remaining parameters).
2267: # $client - File descriptor connected to client.
2268: # Returns
2269: # 0 - Requested to exit, caller should shut down.
2270: # 1 - Continue processing.
2271: # Implicit inputs:
2272: # The authentication systems describe above have their own forms of implicit
2273: # input into the authentication process that are described above.
2274: sub add_user_handler {
2275:
2276: my ($cmd, $tail, $client) = @_;
2277:
2278:
2279: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
2280: my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
2281:
2282: &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
2283:
2284:
2285: if($udom eq $currentdomainid) { # Reject new users for other domains...
2286:
2287: my $oldumask=umask(0077);
2288: chomp($npass);
2289: $npass=&unescape($npass);
2290: my $passfilename = &password_path($udom, $uname);
2291: &Debug("Password file created will be:".$passfilename);
2292: if (-e $passfilename) {
2293: &Failure( $client, "already_exists\n", $userinput);
2294: } else {
2295: my $fperror='';
1.264 albertel 2296: if (!&mkpath($passfilename)) {
2297: $fperror="error: ".($!+0)." mkdir failed while attempting "
2298: ."makeuser";
1.225 foxr 2299: }
2300: unless ($fperror) {
1.489.2.21 raeburn 2301: my $result=&make_passwd_file($uname,$udom,$umode,$npass,
2302: $passfilename,'makeuser');
1.390 raeburn 2303: &Reply($client,\$result, $userinput); #BUGBUG - could be fail
1.225 foxr 2304: } else {
1.387 albertel 2305: &Failure($client, \$fperror, $userinput);
1.225 foxr 2306: }
2307: }
2308: umask($oldumask);
2309: } else {
2310: &Failure($client, "not_right_domain\n",
2311: $userinput); # Even if we are multihomed.
2312:
2313: }
2314: return 1;
2315:
2316: }
2317: ®ister_handler("makeuser", \&add_user_handler, 1, 1, 0);
2318:
2319: #
2320: # Change the authentication method of a user. Note that this may
2321: # also implicitly change the user's password if, for example, the user is
2322: # joining an existing authentication realm. Known authentication realms at
2323: # this time are:
2324: # internal - Purely internal password file (only loncapa knows this user)
2325: # local - Institutionally written authentication module.
2326: # unix - Unix user (/etc/passwd with or without /etc/shadow).
2327: # kerb4 - kerberos version 4
2328: # kerb5 - kerberos version 5
2329: #
2330: # Parameters:
2331: # $cmd - The command that got us here.
2332: # $tail - Tail of the command (remaining parameters).
2333: # $client - File descriptor connected to client.
2334: # Returns
2335: # 0 - Requested to exit, caller should shut down.
2336: # 1 - Continue processing.
2337: # Implicit inputs:
2338: # The authentication systems describe above have their own forms of implicit
2339: # input into the authentication process that are described above.
1.287 foxr 2340: # NOTE:
2341: # This is also used to change the authentication credential values (e.g. passwd).
2342: #
1.225 foxr 2343: #
2344: sub change_authentication_handler {
2345:
2346: my ($cmd, $tail, $client) = @_;
2347:
2348: my $userinput = "$cmd:$tail"; # Reconstruct user input.
2349:
2350: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
2351: &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
2352: if ($udom ne $currentdomainid) {
2353: &Failure( $client, "not_right_domain\n", $client);
2354: } else {
2355:
2356: chomp($npass);
2357:
2358: $npass=&unescape($npass);
1.261 foxr 2359: my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225 foxr 2360: my $passfilename = &password_path($udom, $uname);
2361: if ($passfilename) { # Not allowed to create a new user!!
1.287 foxr 2362: # If just changing the unix passwd. need to arrange to run
1.489.2.8 raeburn 2363: # passwd since otherwise make_passwd_file will fail as
2364: # creation of unix authenticated users is no longer supported
2365: # except from the command line, when running make_domain_coordinator.pl
1.287 foxr 2366:
2367: if(($oldauth =~/^unix/) && ($umode eq "unix")) {
2368: my $result = &change_unix_password($uname, $npass);
2369: &logthis("Result of password change for $uname: ".$result);
2370: if ($result eq "ok") {
1.489.2.21 raeburn 2371: &update_passwd_history($uname,$udom,$umode,'changeuserauth');
1.390 raeburn 2372: &Reply($client, \$result);
1.288 albertel 2373: } else {
1.387 albertel 2374: &Failure($client, \$result);
1.287 foxr 2375: }
1.288 albertel 2376: } else {
1.489.2.21 raeburn 2377: my $result=&make_passwd_file($uname,$udom,$umode,$npass,
2378: $passfilename,'changeuserauth');
1.287 foxr 2379: #
2380: # If the current auth mode is internal, and the old auth mode was
2381: # unix, or krb*, and the user is an author for this domain,
2382: # re-run manage_permissions for that role in order to be able
2383: # to take ownership of the construction space back to www:www
2384: #
1.489.2.8 raeburn 2385:
2386:
1.387 albertel 2387: &Reply($client, \$result, $userinput);
1.261 foxr 2388: }
2389:
2390:
1.225 foxr 2391: } else {
1.251 foxr 2392: &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225 foxr 2393: }
2394: }
2395: return 1;
2396: }
2397: ®ister_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
2398:
1.489.2.21 raeburn 2399: sub update_passwd_history {
2400: my ($uname,$udom,$umode,$context) = @_;
2401: my $proname=&propath($udom,$uname);
2402: my $now = time;
2403: if (open(my $fh,">>$proname/passwd.log")) {
2404: print $fh "$now:$umode:$context\n";
2405: close($fh);
2406: }
2407: return;
2408: }
2409:
1.489.2.43.2. (raeburn 2410:): sub inst_unamemap_check {
2411:): my ($cmd, $tail, $client) = @_;
2412:): my $userinput = "$cmd:$tail";
2413:): my %rulecheck;
2414:): my $outcome;
2415:): my ($udom,$uname,@rules) = split(/:/,$tail);
2416:): $udom = &unescape($udom);
2417:): $uname = &unescape($uname);
2418:): @rules = map {&unescape($_);} (@rules);
2419:): eval {
2420:): local($SIG{__DIE__})='DEFAULT';
2421:): $outcome = &localenroll::unamemap_check($udom,$uname,\@rules,\%rulecheck);
2422:): };
2423:): if (!$@) {
2424:): if ($outcome eq 'ok') {
2425:): my $result='';
2426:): foreach my $key (keys(%rulecheck)) {
2427:): $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
2428:): }
2429:): &Reply($client,\$result,$userinput);
2430:): } else {
2431:): &Reply($client,"error\n", $userinput);
2432:): }
2433:): } else {
2434:): &Failure($client,"unknown_cmd\n",$userinput);
2435:): }
2436:): }
2437:): ®ister_handler("instunamemapcheck",\&inst_unamemap_check,0,1,0);
2438:):
2439:):
1.225 foxr 2440: #
2441: # Determines if this is the home server for a user. The home server
2442: # for a user will have his/her lon-capa passwd file. Therefore all we need
2443: # to do is determine if this file exists.
2444: #
2445: # Parameters:
2446: # $cmd - The command that got us here.
2447: # $tail - Tail of the command (remaining parameters).
2448: # $client - File descriptor connected to client.
2449: # Returns
2450: # 0 - Requested to exit, caller should shut down.
2451: # 1 - Continue processing.
2452: # Implicit inputs:
2453: # The authentication systems describe above have their own forms of implicit
2454: # input into the authentication process that are described above.
2455: #
2456: sub is_home_handler {
2457: my ($cmd, $tail, $client) = @_;
2458:
2459: my $userinput = "$cmd:$tail";
2460:
2461: my ($udom,$uname)=split(/:/,$tail);
2462: chomp($uname);
2463: my $passfile = &password_filename($udom, $uname);
2464: if($passfile) {
2465: &Reply( $client, "found\n", $userinput);
2466: } else {
2467: &Failure($client, "not_found\n", $userinput);
2468: }
2469: return 1;
2470: }
2471: ®ister_handler("home", \&is_home_handler, 0,1,0);
2472:
2473: #
1.434 www 2474: # Process an update request for a resource.
2475: # A resource has been modified that we hold a subscription to.
1.225 foxr 2476: # If the resource is not local, then we must update, or at least invalidate our
2477: # cached copy of the resource.
2478: # Parameters:
2479: # $cmd - The command that got us here.
2480: # $tail - Tail of the command (remaining parameters).
2481: # $client - File descriptor connected to client.
2482: # Returns
2483: # 0 - Requested to exit, caller should shut down.
2484: # 1 - Continue processing.
2485: # Implicit inputs:
2486: # The authentication systems describe above have their own forms of implicit
2487: # input into the authentication process that are described above.
2488: #
2489: sub update_resource_handler {
2490:
2491: my ($cmd, $tail, $client) = @_;
2492:
2493: my $userinput = "$cmd:$tail";
2494:
2495: my $fname= $tail; # This allows interactive testing
2496:
2497:
2498: my $ownership=ishome($fname);
2499: if ($ownership eq 'not_owner') {
2500: if (-e $fname) {
1.434 www 2501: # Delete preview file, if exists
2502: unlink("$fname.tmp");
2503: # Get usage stats
1.225 foxr 2504: my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
2505: $atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
2506: my $now=time;
2507: my $since=$now-$atime;
1.434 www 2508: # If the file has not been used within lonExpire seconds,
2509: # unsubscribe from it and delete local copy
1.225 foxr 2510: if ($since>$perlvar{'lonExpire'}) {
1.365 albertel 2511: my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308 albertel 2512: &devalidate_meta_cache($fname);
1.225 foxr 2513: unlink("$fname");
1.334 albertel 2514: unlink("$fname.meta");
1.225 foxr 2515: } else {
1.434 www 2516: # Yes, this is in active use. Get a fresh copy. Since it might be in
2517: # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225 foxr 2518: my $transname="$fname.in.transfer";
1.365 albertel 2519: my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225 foxr 2520: my $response;
1.455 www 2521: # FIXME: cannot replicate files that take more than two minutes to transfer?
2522: # alarm(120);
2523: # FIXME: this should use the LWP mechanism, not internal alarms.
2524: alarm(1200);
1.225 foxr 2525: {
2526: my $ua=new LWP::UserAgent;
2527: my $request=new HTTP::Request('GET',"$remoteurl");
2528: $response=$ua->request($request,$transname);
2529: }
2530: alarm(0);
2531: if ($response->is_error()) {
1.489.2.30 raeburn 2532: my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
2533: &devalidate_meta_cache($fname);
2534: if (-e $transname) {
2535: unlink($transname);
2536: }
2537: unlink($fname);
1.225 foxr 2538: my $message=$response->status_line;
2539: &logthis("LWP GET: $message for $fname ($remoteurl)");
2540: } else {
2541: if ($remoteurl!~/\.meta$/) {
1.455 www 2542: # FIXME: isn't there an internal LWP mechanism for this?
1.225 foxr 2543: alarm(120);
2544: {
2545: my $ua=new LWP::UserAgent;
2546: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2547: my $mresponse=$ua->request($mrequest,$fname.'.meta');
2548: if ($mresponse->is_error()) {
2549: unlink($fname.'.meta');
2550: }
2551: }
2552: alarm(0);
2553: }
1.434 www 2554: # we successfully transfered, copy file over to real name
1.225 foxr 2555: rename($transname,$fname);
1.308 albertel 2556: &devalidate_meta_cache($fname);
1.225 foxr 2557: }
2558: }
2559: &Reply( $client, "ok\n", $userinput);
2560: } else {
2561: &Failure($client, "not_found\n", $userinput);
2562: }
2563: } else {
2564: &Failure($client, "rejected\n", $userinput);
2565: }
2566: return 1;
2567: }
2568: ®ister_handler("update", \&update_resource_handler, 0 ,1, 0);
2569:
1.308 albertel 2570: sub devalidate_meta_cache {
2571: my ($url) = @_;
2572: use Cache::Memcached;
2573: my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365 albertel 2574: $url = &Apache::lonnet::declutter($url);
1.308 albertel 2575: $url =~ s-\.meta$--;
2576: my $id = &escape('meta:'.$url);
2577: $memcache->delete($id);
2578: }
2579:
1.225 foxr 2580: #
1.226 foxr 2581: # Fetch a user file from a remote server to the user's home directory
2582: # userfiles subdir.
1.225 foxr 2583: # Parameters:
2584: # $cmd - The command that got us here.
2585: # $tail - Tail of the command (remaining parameters).
2586: # $client - File descriptor connected to client.
2587: # Returns
2588: # 0 - Requested to exit, caller should shut down.
2589: # 1 - Continue processing.
2590: #
2591: sub fetch_user_file_handler {
2592:
2593: my ($cmd, $tail, $client) = @_;
2594:
2595: my $userinput = "$cmd:$tail";
2596: my $fname = $tail;
1.232 foxr 2597: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225 foxr 2598: my $udir=&propath($udom,$uname).'/userfiles';
2599: unless (-e $udir) {
2600: mkdir($udir,0770);
2601: }
1.232 foxr 2602: Debug("fetch user file for $fname");
1.225 foxr 2603: if (-e $udir) {
2604: $ufile=~s/^[\.\~]+//;
1.232 foxr 2605:
2606: # IF necessary, create the path right down to the file.
2607: # Note that any regular files in the way of this path are
2608: # wiped out to deal with some earlier folly of mine.
2609:
1.267 raeburn 2610: if (!&mkpath($udir.'/'.$ufile)) {
1.264 albertel 2611: &Failure($client, "unable_to_create\n", $userinput);
1.232 foxr 2612: }
2613:
1.225 foxr 2614: my $destname=$udir.'/'.$ufile;
2615: my $transname=$udir.'/'.$ufile.'.in.transit';
1.476 raeburn 2616: my $clientprotocol=$Apache::lonnet::protocol{$clientname};
2617: $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486 raeburn 2618: my $clienthost = &Apache::lonnet::hostname($clientname);
2619: my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225 foxr 2620: my $response;
1.232 foxr 2621: Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.225 foxr 2622: alarm(120);
2623: {
2624: my $ua=new LWP::UserAgent;
2625: my $request=new HTTP::Request('GET',"$remoteurl");
2626: $response=$ua->request($request,$transname);
2627: }
2628: alarm(0);
2629: if ($response->is_error()) {
2630: unlink($transname);
2631: my $message=$response->status_line;
2632: &logthis("LWP GET: $message for $fname ($remoteurl)");
2633: &Failure($client, "failed\n", $userinput);
2634: } else {
1.232 foxr 2635: Debug("Renaming $transname to $destname");
1.225 foxr 2636: if (!rename($transname,$destname)) {
2637: &logthis("Unable to move $transname to $destname");
2638: unlink($transname);
2639: &Failure($client, "failed\n", $userinput);
2640: } else {
1.489.2.2 raeburn 2641: if ($fname =~ /^default.+\.(page|sequence)$/) {
2642: my ($major,$minor) = split(/\./,$clientversion);
2643: if (($major < 2) || ($major == 2 && $minor < 11)) {
2644: my $now = time;
2645: &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
2646: my $key = &escape('internal.contentchange');
2647: my $what = "$key=$now";
2648: my $hashref = &tie_user_hash($udom,$uname,'environment',
2649: &GDBM_WRCREAT(),"P",$what);
2650: if ($hashref) {
2651: $hashref->{$key}=$now;
2652: if (!&untie_user_hash($hashref)) {
2653: &logthis("error: ".($!+0)." untie (GDBM) failed ".
2654: "when updating internal.contentchange");
2655: }
2656: }
2657: }
2658: }
1.225 foxr 2659: &Reply($client, "ok\n", $userinput);
2660: }
2661: }
2662: } else {
2663: &Failure($client, "not_home\n", $userinput);
2664: }
2665: return 1;
2666: }
2667: ®ister_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
2668:
1.226 foxr 2669: #
2670: # Remove a file from a user's home directory userfiles subdirectory.
2671: # Parameters:
2672: # cmd - the Lond request keyword that got us here.
2673: # tail - the part of the command past the keyword.
2674: # client- File descriptor connected with the client.
2675: #
2676: # Returns:
2677: # 1 - Continue processing.
2678: sub remove_user_file_handler {
2679: my ($cmd, $tail, $client) = @_;
2680:
2681: my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2682:
2683: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2684: if ($ufile =~m|/\.\./|) {
2685: # any files paths with /../ in them refuse
2686: # to deal with
2687: &Failure($client, "refused\n", "$cmd:$tail");
2688: } else {
2689: my $udir = &propath($udom,$uname);
2690: if (-e $udir) {
2691: my $file=$udir.'/userfiles/'.$ufile;
2692: if (-e $file) {
1.253 foxr 2693: #
2694: # If the file is a regular file unlink is fine...
1.489.2.19 raeburn 2695: # However it's possible the client wants a dir
2696: # removed, in which case rmdir is more appropriate
2697: # Note: rmdir will only remove an empty directory.
1.253 foxr 2698: #
1.240 banghart 2699: if (-f $file){
1.241 albertel 2700: unlink($file);
1.489.2.19 raeburn 2701: # for html files remove the associated .bak file
2702: # which may have been created by the editor.
2703: if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
2704: my $path = $1;
2705: if (-e $file.'.bak') {
2706: unlink($file.'.bak');
2707: }
2708: }
1.241 albertel 2709: } elsif(-d $file) {
2710: rmdir($file);
1.240 banghart 2711: }
1.226 foxr 2712: if (-e $file) {
1.253 foxr 2713: # File is still there after we deleted it ?!?
2714:
1.226 foxr 2715: &Failure($client, "failed\n", "$cmd:$tail");
2716: } else {
2717: &Reply($client, "ok\n", "$cmd:$tail");
2718: }
2719: } else {
2720: &Failure($client, "not_found\n", "$cmd:$tail");
2721: }
2722: } else {
2723: &Failure($client, "not_home\n", "$cmd:$tail");
2724: }
2725: }
2726: return 1;
2727: }
2728: ®ister_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
2729:
1.236 albertel 2730: #
2731: # make a directory in a user's home directory userfiles subdirectory.
2732: # Parameters:
2733: # cmd - the Lond request keyword that got us here.
2734: # tail - the part of the command past the keyword.
2735: # client- File descriptor connected with the client.
2736: #
2737: # Returns:
2738: # 1 - Continue processing.
2739: sub mkdir_user_file_handler {
2740: my ($cmd, $tail, $client) = @_;
2741:
2742: my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2743: $dir=&unescape($dir);
2744: my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
2745: if ($ufile =~m|/\.\./|) {
2746: # any files paths with /../ in them refuse
2747: # to deal with
2748: &Failure($client, "refused\n", "$cmd:$tail");
2749: } else {
2750: my $udir = &propath($udom,$uname);
2751: if (-e $udir) {
1.264 albertel 2752: my $newdir=$udir.'/userfiles/'.$ufile.'/';
2753: if (!&mkpath($newdir)) {
2754: &Failure($client, "failed\n", "$cmd:$tail");
1.236 albertel 2755: }
1.264 albertel 2756: &Reply($client, "ok\n", "$cmd:$tail");
1.236 albertel 2757: } else {
2758: &Failure($client, "not_home\n", "$cmd:$tail");
2759: }
2760: }
2761: return 1;
2762: }
2763: ®ister_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
2764:
1.237 albertel 2765: #
2766: # rename a file in a user's home directory userfiles subdirectory.
2767: # Parameters:
2768: # cmd - the Lond request keyword that got us here.
2769: # tail - the part of the command past the keyword.
2770: # client- File descriptor connected with the client.
2771: #
2772: # Returns:
2773: # 1 - Continue processing.
2774: sub rename_user_file_handler {
2775: my ($cmd, $tail, $client) = @_;
2776:
2777: my ($udom,$uname,$old,$new) = split(/:/, $tail);
2778: $old=&unescape($old);
2779: $new=&unescape($new);
2780: if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
2781: # any files paths with /../ in them refuse to deal with
2782: &Failure($client, "refused\n", "$cmd:$tail");
2783: } else {
2784: my $udir = &propath($udom,$uname);
2785: if (-e $udir) {
2786: my $oldfile=$udir.'/userfiles/'.$old;
2787: my $newfile=$udir.'/userfiles/'.$new;
2788: if (-e $newfile) {
2789: &Failure($client, "exists\n", "$cmd:$tail");
2790: } elsif (! -e $oldfile) {
2791: &Failure($client, "not_found\n", "$cmd:$tail");
2792: } else {
2793: if (!rename($oldfile,$newfile)) {
2794: &Failure($client, "failed\n", "$cmd:$tail");
2795: } else {
2796: &Reply($client, "ok\n", "$cmd:$tail");
2797: }
2798: }
2799: } else {
2800: &Failure($client, "not_home\n", "$cmd:$tail");
2801: }
2802: }
2803: return 1;
2804: }
2805: ®ister_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
2806:
1.227 foxr 2807: #
1.382 albertel 2808: # Checks if the specified user has an active session on the server
2809: # return ok if so, not_found if not
2810: #
2811: # Parameters:
2812: # cmd - The request keyword that dispatched to tus.
2813: # tail - The tail of the request (colon separated parameters).
2814: # client - Filehandle open on the client.
2815: # Return:
2816: # 1.
2817: sub user_has_session_handler {
2818: my ($cmd, $tail, $client) = @_;
2819:
2820: my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
2821:
2822: opendir(DIR,$perlvar{'lonIDsDir'});
2823: my $filename;
2824: while ($filename=readdir(DIR)) {
2825: last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
2826: }
2827: if ($filename) {
2828: &Reply($client, "ok\n", "$cmd:$tail");
2829: } else {
2830: &Failure($client, "not_found\n", "$cmd:$tail");
2831: }
2832: return 1;
2833:
2834: }
2835: ®ister_handler("userhassession", \&user_has_session_handler, 0,1,0);
2836:
1.489.2.43.2. (raeburn 2837:): sub del_usersession_handler {
2838:): my ($cmd, $tail, $client) = @_;
2839:):
2840:): my $result;
2841:): my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
2842:): if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
2843:): my $lonidsdir = $perlvar{'lonIDsDir'};
2844:): if (-d $lonidsdir) {
2845:): if (opendir(DIR,$lonidsdir)) {
2846:): my $filename;
2847:): while ($filename=readdir(DIR)) {
2848:): if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
2849:): if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
2850:): &GDBM_READER(),0640)) {
2851:): my $linkedfile;
2852:): if (exists($oldenv{'user.linkedenv'})) {
2853:): $linkedfile = $oldenv{'user.linkedenv'};
2854:): }
2855:): untie(%oldenv);
2856:): $result = unlink("$lonidsdir/$filename");
2857:): if ($result) {
2858:): if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
2859:): if (-l "$lonidsdir/$linkedfile.id") {
2860:): unlink("$lonidsdir/$linkedfile.id");
2861:): }
2862:): }
2863:): }
2864:): } else {
2865:): $result = unlink("$lonidsdir/$filename");
2866:): }
2867:): last;
2868:): }
2869:): }
2870:): }
2871:): }
2872:): if ($result == 1) {
2873:): &Reply($client, "$result\n", "$cmd:$tail");
2874:): } else {
2875:): &Reply($client, "not_found\n", "$cmd:$tail");
2876:): }
2877:): } else {
2878:): &Failure($client, "invalid_user\n", "$cmd:$tail");
2879:): }
2880:): return 1;
2881:): }
2882:):
2883:): ®ister_handler("delusersession", \&del_usersession_handler, 0,1,0);
2884:):
1.382 albertel 2885: #
1.263 albertel 2886: # Authenticate access to a user file by checking that the token the user's
2887: # passed also exists in their session file
1.227 foxr 2888: #
2889: # Parameters:
2890: # cmd - The request keyword that dispatched to tus.
2891: # tail - The tail of the request (colon separated parameters).
2892: # client - Filehandle open on the client.
2893: # Return:
2894: # 1.
2895: sub token_auth_user_file_handler {
2896: my ($cmd, $tail, $client) = @_;
2897:
2898: my ($fname, $session) = split(/:/, $tail);
2899:
2900: chomp($session);
1.393 raeburn 2901: my $reply="non_auth";
1.343 albertel 2902: my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
2903: if (open(ENVIN,"$file")) {
1.332 albertel 2904: flock(ENVIN,LOCK_SH);
1.343 albertel 2905: tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
2906: if (exists($disk_env{"userfile.$fname"})) {
1.393 raeburn 2907: $reply="ok";
1.343 albertel 2908: } else {
2909: foreach my $envname (keys(%disk_env)) {
2910: if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393 raeburn 2911: $reply="ok";
1.343 albertel 2912: last;
2913: }
2914: }
1.227 foxr 2915: }
1.343 albertel 2916: untie(%disk_env);
1.227 foxr 2917: close(ENVIN);
1.387 albertel 2918: &Reply($client, \$reply, "$cmd:$tail");
1.227 foxr 2919: } else {
2920: &Failure($client, "invalid_token\n", "$cmd:$tail");
2921: }
2922: return 1;
2923:
2924: }
2925: ®ister_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229 foxr 2926:
2927: #
2928: # Unsubscribe from a resource.
2929: #
2930: # Parameters:
2931: # $cmd - The command that got us here.
2932: # $tail - Tail of the command (remaining parameters).
2933: # $client - File descriptor connected to client.
2934: # Returns
2935: # 0 - Requested to exit, caller should shut down.
2936: # 1 - Continue processing.
2937: #
2938: sub unsubscribe_handler {
2939: my ($cmd, $tail, $client) = @_;
2940:
2941: my $userinput= "$cmd:$tail";
2942:
2943: my ($fname) = split(/:/,$tail); # Split in case there's extrs.
2944:
2945: &Debug("Unsubscribing $fname");
2946: if (-e $fname) {
2947: &Debug("Exists");
2948: &Reply($client, &unsub($fname,$clientip), $userinput);
2949: } else {
2950: &Failure($client, "not_found\n", $userinput);
2951: }
2952: return 1;
2953: }
2954: ®ister_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263 albertel 2955:
1.230 foxr 2956: # Subscribe to a resource
2957: #
2958: # Parameters:
2959: # $cmd - The command that got us here.
2960: # $tail - Tail of the command (remaining parameters).
2961: # $client - File descriptor connected to client.
2962: # Returns
2963: # 0 - Requested to exit, caller should shut down.
2964: # 1 - Continue processing.
2965: #
2966: sub subscribe_handler {
2967: my ($cmd, $tail, $client)= @_;
2968:
2969: my $userinput = "$cmd:$tail";
2970:
2971: &Reply( $client, &subscribe($userinput,$clientip), $userinput);
2972:
2973: return 1;
2974: }
2975: ®ister_handler("sub", \&subscribe_handler, 0, 1, 0);
2976:
2977: #
1.379 albertel 2978: # Determine the latest version of a resource (it looks for the highest
2979: # past version and then returns that +1)
1.230 foxr 2980: #
2981: # Parameters:
2982: # $cmd - The command that got us here.
2983: # $tail - Tail of the command (remaining parameters).
1.379 albertel 2984: # (Should consist of an absolute path to a file)
1.230 foxr 2985: # $client - File descriptor connected to client.
2986: # Returns
2987: # 0 - Requested to exit, caller should shut down.
2988: # 1 - Continue processing.
2989: #
2990: sub current_version_handler {
2991: my ($cmd, $tail, $client) = @_;
2992:
2993: my $userinput= "$cmd:$tail";
2994:
2995: my $fname = $tail;
2996: &Reply( $client, ¤tversion($fname)."\n", $userinput);
2997: return 1;
2998:
2999: }
3000: ®ister_handler("currentversion", \¤t_version_handler, 0, 1, 0);
3001:
3002: # Make an entry in a user's activity log.
3003: #
3004: # Parameters:
3005: # $cmd - The command that got us here.
3006: # $tail - Tail of the command (remaining parameters).
3007: # $client - File descriptor connected to client.
3008: # Returns
3009: # 0 - Requested to exit, caller should shut down.
3010: # 1 - Continue processing.
3011: #
3012: sub activity_log_handler {
3013: my ($cmd, $tail, $client) = @_;
3014:
3015:
3016: my $userinput= "$cmd:$tail";
3017:
3018: my ($udom,$uname,$what)=split(/:/,$tail);
3019: chomp($what);
3020: my $proname=&propath($udom,$uname);
3021: my $now=time;
3022: my $hfh;
3023: if ($hfh=IO::File->new(">>$proname/activity.log")) {
3024: print $hfh "$now:$clientname:$what\n";
3025: &Reply( $client, "ok\n", $userinput);
3026: } else {
3027: &Failure($client, "error: ".($!+0)." IO::File->new Failed "
3028: ."while attempting log\n",
3029: $userinput);
3030: }
3031:
3032: return 1;
3033: }
1.263 albertel 3034: ®ister_handler("log", \&activity_log_handler, 0, 1, 0);
1.230 foxr 3035:
3036: #
3037: # Put a namespace entry in a user profile hash.
3038: # My druthers would be for this to be an encrypted interaction too.
3039: # anything that might be an inadvertent covert channel about either
3040: # user authentication or user personal information....
3041: #
3042: # Parameters:
3043: # $cmd - The command that got us here.
3044: # $tail - Tail of the command (remaining parameters).
3045: # $client - File descriptor connected to client.
3046: # Returns
3047: # 0 - Requested to exit, caller should shut down.
3048: # 1 - Continue processing.
3049: #
3050: sub put_user_profile_entry {
3051: my ($cmd, $tail, $client) = @_;
1.229 foxr 3052:
1.230 foxr 3053: my $userinput = "$cmd:$tail";
3054:
1.242 raeburn 3055: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230 foxr 3056: if ($namespace ne 'roles') {
3057: chomp($what);
3058: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3059: &GDBM_WRCREAT(),"P",$what);
3060: if($hashref) {
3061: my @pairs=split(/\&/,$what);
3062: foreach my $pair (@pairs) {
3063: my ($key,$value)=split(/=/,$pair);
3064: $hashref->{$key}=$value;
3065: }
1.311 albertel 3066: if (&untie_user_hash($hashref)) {
1.230 foxr 3067: &Reply( $client, "ok\n", $userinput);
3068: } else {
3069: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3070: "while attempting put\n",
3071: $userinput);
3072: }
3073: } else {
1.316 albertel 3074: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230 foxr 3075: "while attempting put\n", $userinput);
3076: }
3077: } else {
3078: &Failure( $client, "refused\n", $userinput);
3079: }
3080:
3081: return 1;
3082: }
3083: ®ister_handler("put", \&put_user_profile_entry, 0, 1, 0);
3084:
1.283 albertel 3085: # Put a piece of new data in hash, returns error if entry already exists
3086: # Parameters:
3087: # $cmd - The command that got us here.
3088: # $tail - Tail of the command (remaining parameters).
3089: # $client - File descriptor connected to client.
3090: # Returns
3091: # 0 - Requested to exit, caller should shut down.
3092: # 1 - Continue processing.
3093: #
3094: sub newput_user_profile_entry {
3095: my ($cmd, $tail, $client) = @_;
3096:
3097: my $userinput = "$cmd:$tail";
3098:
3099: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
3100: if ($namespace eq 'roles') {
3101: &Failure( $client, "refused\n", $userinput);
3102: return 1;
3103: }
3104:
3105: chomp($what);
3106:
3107: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3108: &GDBM_WRCREAT(),"N",$what);
3109: if(!$hashref) {
1.316 albertel 3110: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283 albertel 3111: "while attempting put\n", $userinput);
3112: return 1;
3113: }
3114:
3115: my @pairs=split(/\&/,$what);
3116: foreach my $pair (@pairs) {
3117: my ($key,$value)=split(/=/,$pair);
3118: if (exists($hashref->{$key})) {
1.489.2.17 raeburn 3119: if (!&untie_user_hash($hashref)) {
3120: &logthis("error: ".($!+0)." untie (GDBM) failed ".
3121: "while attempting newput - early out as key exists");
3122: }
1.283 albertel 3123: &Failure($client, "key_exists: ".$key."\n",$userinput);
3124: return 1;
3125: }
3126: }
3127:
3128: foreach my $pair (@pairs) {
3129: my ($key,$value)=split(/=/,$pair);
3130: $hashref->{$key}=$value;
3131: }
3132:
1.311 albertel 3133: if (&untie_user_hash($hashref)) {
1.283 albertel 3134: &Reply( $client, "ok\n", $userinput);
3135: } else {
3136: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3137: "while attempting put\n",
3138: $userinput);
3139: }
3140: return 1;
3141: }
3142: ®ister_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
3143:
1.230 foxr 3144: #
3145: # Increment a profile entry in the user history file.
3146: # The history contains keyword value pairs. In this case,
3147: # The value itself is a pair of numbers. The first, the current value
3148: # the second an increment that this function applies to the current
3149: # value.
3150: #
3151: # Parameters:
3152: # $cmd - The command that got us here.
3153: # $tail - Tail of the command (remaining parameters).
3154: # $client - File descriptor connected to client.
3155: # Returns
3156: # 0 - Requested to exit, caller should shut down.
3157: # 1 - Continue processing.
3158: #
3159: sub increment_user_value_handler {
3160: my ($cmd, $tail, $client) = @_;
3161:
3162: my $userinput = "$cmd:$tail";
3163:
3164: my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
3165: if ($namespace ne 'roles') {
3166: chomp($what);
3167: my $hashref = &tie_user_hash($udom, $uname,
3168: $namespace, &GDBM_WRCREAT(),
3169: "P",$what);
3170: if ($hashref) {
3171: my @pairs=split(/\&/,$what);
3172: foreach my $pair (@pairs) {
3173: my ($key,$value)=split(/=/,$pair);
1.284 raeburn 3174: $value = &unescape($value);
1.230 foxr 3175: # We could check that we have a number...
3176: if (! defined($value) || $value eq '') {
3177: $value = 1;
3178: }
3179: $hashref->{$key}+=$value;
1.284 raeburn 3180: if ($namespace eq 'nohist_resourcetracker') {
3181: if ($hashref->{$key} < 0) {
3182: $hashref->{$key} = 0;
3183: }
3184: }
1.230 foxr 3185: }
1.311 albertel 3186: if (&untie_user_hash($hashref)) {
1.230 foxr 3187: &Reply( $client, "ok\n", $userinput);
3188: } else {
3189: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3190: "while attempting inc\n", $userinput);
3191: }
3192: } else {
3193: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3194: "while attempting inc\n", $userinput);
3195: }
3196: } else {
3197: &Failure($client, "refused\n", $userinput);
3198: }
3199:
3200: return 1;
3201: }
3202: ®ister_handler("inc", \&increment_user_value_handler, 0, 1, 0);
3203:
3204: #
3205: # Put a new role for a user. Roles are LonCAPA's packaging of permissions.
3206: # Each 'role' a user has implies a set of permissions. Adding a new role
3207: # for a person grants the permissions packaged with that role
3208: # to that user when the role is selected.
3209: #
3210: # Parameters:
3211: # $cmd - The command string (rolesput).
3212: # $tail - The remainder of the request line. For rolesput this
3213: # consists of a colon separated list that contains:
3214: # The domain and user that is granting the role (logged).
3215: # The domain and user that is getting the role.
3216: # The roles being granted as a set of & separated pairs.
3217: # each pair a key value pair.
3218: # $client - File descriptor connected to the client.
3219: # Returns:
3220: # 0 - If the daemon should exit
3221: # 1 - To continue processing.
3222: #
3223: #
3224: sub roles_put_handler {
3225: my ($cmd, $tail, $client) = @_;
3226:
3227: my $userinput = "$cmd:$tail";
3228:
3229: my ( $exedom, $exeuser, $udom, $uname, $what) = split(/:/,$tail);
3230:
3231:
3232: my $namespace='roles';
3233: chomp($what);
3234: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3235: &GDBM_WRCREAT(), "P",
3236: "$exedom:$exeuser:$what");
3237: #
3238: # Log the attempt to set a role. The {}'s here ensure that the file
3239: # handle is open for the minimal amount of time. Since the flush
3240: # is done on close this improves the chances the log will be an un-
3241: # corrupted ordered thing.
3242: if ($hashref) {
1.261 foxr 3243: my $pass_entry = &get_auth_type($udom, $uname);
3244: my ($auth_type,$pwd) = split(/:/, $pass_entry);
3245: $auth_type = $auth_type.":";
1.230 foxr 3246: my @pairs=split(/\&/,$what);
3247: foreach my $pair (@pairs) {
3248: my ($key,$value)=split(/=/,$pair);
3249: &manage_permissions($key, $udom, $uname,
1.260 foxr 3250: $auth_type);
1.230 foxr 3251: $hashref->{$key}=$value;
3252: }
1.311 albertel 3253: if (&untie_user_hash($hashref)) {
1.230 foxr 3254: &Reply($client, "ok\n", $userinput);
3255: } else {
3256: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3257: "while attempting rolesput\n", $userinput);
3258: }
3259: } else {
3260: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3261: "while attempting rolesput\n", $userinput);
3262: }
3263: return 1;
3264: }
3265: ®ister_handler("rolesput", \&roles_put_handler, 1,1,0); # Encoded client only.
3266:
3267: #
1.231 foxr 3268: # Deletes (removes) a role for a user. This is equivalent to removing
3269: # a permissions package associated with the role from the user's profile.
3270: #
3271: # Parameters:
3272: # $cmd - The command (rolesdel)
3273: # $tail - The remainder of the request line. This consists
3274: # of:
3275: # The domain and user requesting the change (logged)
3276: # The domain and user being changed.
3277: # The roles being revoked. These are shipped to us
3278: # as a bunch of & separated role name keywords.
3279: # $client - The file handle open on the client.
3280: # Returns:
3281: # 1 - Continue processing
3282: # 0 - Exit.
3283: #
3284: sub roles_delete_handler {
3285: my ($cmd, $tail, $client) = @_;
3286:
3287: my $userinput = "$cmd:$tail";
3288:
3289: my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
3290: &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
3291: "what = ".$what);
3292: my $namespace='roles';
3293: chomp($what);
3294: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3295: &GDBM_WRCREAT(), "D",
3296: "$exedom:$exeuser:$what");
3297:
3298: if ($hashref) {
3299: my @rolekeys=split(/\&/,$what);
3300:
3301: foreach my $key (@rolekeys) {
3302: delete $hashref->{$key};
3303: }
1.315 albertel 3304: if (&untie_user_hash($hashref)) {
1.231 foxr 3305: &Reply($client, "ok\n", $userinput);
3306: } else {
3307: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3308: "while attempting rolesdel\n", $userinput);
3309: }
3310: } else {
3311: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3312: "while attempting rolesdel\n", $userinput);
3313: }
3314:
3315: return 1;
3316: }
3317: ®ister_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
3318:
3319: # Unencrypted get from a user's profile database. See
3320: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
3321: # This function retrieves a keyed item from a specific named database in the
3322: # user's directory.
3323: #
3324: # Parameters:
3325: # $cmd - Command request keyword (get).
3326: # $tail - Tail of the command. This is a colon separated list
3327: # consisting of the domain and username that uniquely
3328: # identifies the profile,
3329: # The 'namespace' which selects the gdbm file to
3330: # do the lookup in,
3331: # & separated list of keys to lookup. Note that
3332: # the values are returned as an & separated list too.
3333: # $client - File descriptor open on the client.
3334: # Returns:
3335: # 1 - Continue processing.
3336: # 0 - Exit.
3337: #
3338: sub get_profile_entry {
3339: my ($cmd, $tail, $client) = @_;
3340:
3341: my $userinput= "$cmd:$tail";
3342:
3343: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
3344: chomp($what);
1.255 foxr 3345:
1.390 raeburn 3346:
1.255 foxr 3347: my $replystring = read_profile($udom, $uname, $namespace, $what);
3348: my ($first) = split(/:/,$replystring);
3349: if($first ne "error") {
1.387 albertel 3350: &Reply($client, \$replystring, $userinput);
1.231 foxr 3351: } else {
1.255 foxr 3352: &Failure($client, $replystring." while attempting get\n", $userinput);
1.231 foxr 3353: }
3354: return 1;
1.255 foxr 3355:
3356:
1.231 foxr 3357: }
3358: ®ister_handler("get", \&get_profile_entry, 0,1,0);
3359:
3360: #
3361: # Process the encrypted get request. Note that the request is sent
3362: # in clear, but the reply is encrypted. This is a small covert channel:
3363: # information about the sensitive keys is given to the snooper. Just not
3364: # information about the values of the sensitive key. Hmm if I wanted to
3365: # know these I'd snoop for the egets. Get the profile item names from them
3366: # and then issue a get for them since there's no enforcement of the
3367: # requirement of an encrypted get for particular profile items. If I
3368: # were re-doing this, I'd force the request to be encrypted as well as the
3369: # reply. I'd also just enforce encrypted transactions for all gets since
3370: # that would prevent any covert channel snooping.
3371: #
3372: # Parameters:
3373: # $cmd - Command keyword of request (eget).
1.489.2.32 raeburn 3374: # $tail - Tail of the command. See GetProfileEntry
3375: # for more information about this.
1.231 foxr 3376: # $client - File open on the client.
3377: # Returns:
3378: # 1 - Continue processing
3379: # 0 - server should exit.
3380: sub get_profile_entry_encrypted {
3381: my ($cmd, $tail, $client) = @_;
3382:
3383: my $userinput = "$cmd:$tail";
3384:
1.339 albertel 3385: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231 foxr 3386: chomp($what);
1.255 foxr 3387: my $qresult = read_profile($udom, $uname, $namespace, $what);
3388: my ($first) = split(/:/, $qresult);
3389: if($first ne "error") {
3390:
3391: if ($cipher) {
3392: my $cmdlength=length($qresult);
3393: $qresult.=" ";
3394: my $encqresult='';
3395: for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
3396: $encqresult.= unpack("H16",
3397: $cipher->encrypt(substr($qresult,
3398: $encidx,
3399: 8)));
3400: }
3401: &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
3402: } else {
1.231 foxr 3403: &Failure( $client, "error:no_key\n", $userinput);
3404: }
3405: } else {
1.255 foxr 3406: &Failure($client, "$qresult while attempting eget\n", $userinput);
3407:
1.231 foxr 3408: }
3409:
3410: return 1;
3411: }
1.255 foxr 3412: ®ister_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263 albertel 3413:
1.231 foxr 3414: #
3415: # Deletes a key in a user profile database.
3416: #
3417: # Parameters:
3418: # $cmd - Command keyword (del).
3419: # $tail - Command tail. IN this case a colon
3420: # separated list containing:
3421: # The domain and user that identifies uniquely
3422: # the identity of the user.
3423: # The profile namespace (name of the profile
3424: # database file).
3425: # & separated list of keywords to delete.
3426: # $client - File open on client socket.
3427: # Returns:
3428: # 1 - Continue processing
3429: # 0 - Exit server.
3430: #
3431: #
3432: sub delete_profile_entry {
3433: my ($cmd, $tail, $client) = @_;
3434:
3435: my $userinput = "cmd:$tail";
3436:
3437: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
3438: chomp($what);
3439: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3440: &GDBM_WRCREAT(),
3441: "D",$what);
3442: if ($hashref) {
3443: my @keys=split(/\&/,$what);
3444: foreach my $key (@keys) {
3445: delete($hashref->{$key});
3446: }
1.315 albertel 3447: if (&untie_user_hash($hashref)) {
1.231 foxr 3448: &Reply($client, "ok\n", $userinput);
3449: } else {
3450: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3451: "while attempting del\n", $userinput);
3452: }
3453: } else {
3454: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3455: "while attempting del\n", $userinput);
3456: }
3457: return 1;
3458: }
3459: ®ister_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263 albertel 3460:
1.231 foxr 3461: #
3462: # List the set of keys that are defined in a profile database file.
3463: # A successful reply from this will contain an & separated list of
3464: # the keys.
3465: # Parameters:
3466: # $cmd - Command request (keys).
3467: # $tail - Remainder of the request, a colon separated
3468: # list containing domain/user that identifies the
3469: # user being queried, and the database namespace
3470: # (database filename essentially).
3471: # $client - File open on the client.
3472: # Returns:
3473: # 1 - Continue processing.
3474: # 0 - Exit the server.
3475: #
3476: sub get_profile_keys {
3477: my ($cmd, $tail, $client) = @_;
3478:
3479: my $userinput = "$cmd:$tail";
3480:
3481: my ($udom,$uname,$namespace)=split(/:/,$tail);
3482: my $qresult='';
3483: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3484: &GDBM_READER());
3485: if ($hashref) {
3486: foreach my $key (keys %$hashref) {
3487: $qresult.="$key&";
3488: }
1.315 albertel 3489: if (&untie_user_hash($hashref)) {
1.231 foxr 3490: $qresult=~s/\&$//;
1.387 albertel 3491: &Reply($client, \$qresult, $userinput);
1.231 foxr 3492: } else {
3493: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3494: "while attempting keys\n", $userinput);
3495: }
3496: } else {
3497: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3498: "while attempting keys\n", $userinput);
3499: }
3500:
3501: return 1;
3502: }
3503: ®ister_handler("keys", \&get_profile_keys, 0, 1, 0);
3504:
3505: #
3506: # Dump the contents of a user profile database.
3507: # Note that this constitutes a very large covert channel too since
3508: # the dump will return sensitive information that is not encrypted.
3509: # The naive security assumption is that the session negotiation ensures
3510: # our client is trusted and I don't believe that's assured at present.
3511: # Sure want badly to go to ssl or tls. Of course if my peer isn't really
3512: # a LonCAPA node they could have negotiated an encryption key too so >sigh<.
3513: #
3514: # Parameters:
3515: # $cmd - The command request keyword (currentdump).
3516: # $tail - Remainder of the request, consisting of a colon
3517: # separated list that has the domain/username and
3518: # the namespace to dump (database file).
3519: # $client - file open on the remote client.
3520: # Returns:
3521: # 1 - Continue processing.
3522: # 0 - Exit the server.
3523: #
3524: sub dump_profile_database {
3525: my ($cmd, $tail, $client) = @_;
3526:
3527: my $userinput = "$cmd:$tail";
3528:
3529: my ($udom,$uname,$namespace) = split(/:/,$tail);
3530: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3531: &GDBM_READER());
3532: if ($hashref) {
3533: # Structure of %data:
3534: # $data{$symb}->{$parameter}=$value;
3535: # $data{$symb}->{'v.'.$parameter}=$version;
3536: # since $parameter will be unescaped, we do not
3537: # have to worry about silly parameter names...
3538:
3539: my $qresult='';
3540: my %data = (); # A hash of anonymous hashes..
3541: while (my ($key,$value) = each(%$hashref)) {
3542: my ($v,$symb,$param) = split(/:/,$key);
3543: next if ($v eq 'version' || $symb eq 'keys');
3544: next if (exists($data{$symb}) &&
3545: exists($data{$symb}->{$param}) &&
3546: $data{$symb}->{'v.'.$param} > $v);
3547: $data{$symb}->{$param}=$value;
3548: $data{$symb}->{'v.'.$param}=$v;
3549: }
1.311 albertel 3550: if (&untie_user_hash($hashref)) {
1.231 foxr 3551: while (my ($symb,$param_hash) = each(%data)) {
3552: while(my ($param,$value) = each (%$param_hash)){
3553: next if ($param =~ /^v\./); # Ignore versions...
3554: #
3555: # Just dump the symb=value pairs separated by &
3556: #
3557: $qresult.=$symb.':'.$param.'='.$value.'&';
3558: }
3559: }
3560: chop($qresult);
1.387 albertel 3561: &Reply($client , \$qresult, $userinput);
1.231 foxr 3562: } else {
3563: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3564: "while attempting currentdump\n", $userinput);
3565: }
3566: } else {
3567: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3568: "while attempting currentdump\n", $userinput);
3569: }
3570:
3571: return 1;
3572: }
3573: ®ister_handler("currentdump", \&dump_profile_database, 0, 1, 0);
3574:
3575: #
3576: # Dump a profile database with an optional regular expression
3577: # to match against the keys. In this dump, no effort is made
3578: # to separate symb from version information. Presumably the
3579: # databases that are dumped by this command are of a different
3580: # structure. Need to look at this and improve the documentation of
3581: # both this and the currentdump handler.
3582: # Parameters:
3583: # $cmd - The command keyword.
3584: # $tail - All of the characters after the $cmd:
3585: # These are expected to be a colon
3586: # separated list containing:
3587: # domain/user - identifying the user.
3588: # namespace - identifying the database.
3589: # regexp - optional regular expression
3590: # that is matched against
3591: # database keywords to do
3592: # selective dumps.
1.488 raeburn 3593: # range - optional range of entries
3594: # e.g., 10-20 would return the
3595: # 10th to 19th items, etc.
1.231 foxr 3596: # $client - Channel open on the client.
3597: # Returns:
3598: # 1 - Continue processing.
3599: # Side effects:
3600: # response is written to $client.
3601: #
3602: sub dump_with_regexp {
3603: my ($cmd, $tail, $client) = @_;
3604:
1.489.2.4 raeburn 3605: my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.231 foxr 3606:
1.489.2.4 raeburn 3607: if ($res =~ /^error:/) {
3608: &Failure($client, \$res, "$cmd:$tail");
1.231 foxr 3609: } else {
1.489.2.4 raeburn 3610: &Reply($client, \$res, "$cmd:$tail");
1.231 foxr 3611: }
3612:
3613: return 1;
3614: }
3615: ®ister_handler("dump", \&dump_with_regexp, 0, 1, 0);
3616:
1.489.2.43.2. (raeburn 3617:): #
3618:): # Process the encrypted dump request. Original call should
3619:): # be from lonnet::dump() with seventh arg ($encrypt) set to
3620:): # 1, to ensure that both request and response are encrypted.
3621:): #
3622:): # Parameters:
3623:): # $cmd - Command keyword of request (edump).
3624:): # $tail - Tail of the command.
3625:): # See &dump_with_regexp for more
3626:): # information about this.
3627:): # $client - File open on the client.
3628:): # Returns:
3629:): # 1 - Continue processing
3630:): # 0 - server should exit.
3631:): #
3632:):
3633:): sub encrypted_dump_with_regexp {
3634:): my ($cmd, $tail, $client) = @_;
3635:): my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
3636:):
3637:): if ($res =~ /^error:/) {
3638:): Failure($client, \$res, "$cmd:$tail");
3639:): } else {
3640:): if ($cipher) {
3641:): my $cmdlength=length($res);
3642:): $res.=" ";
3643:): my $encres='';
3644:): for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
3645:): $encres.= unpack("H16",
3646:): $cipher->encrypt(substr($res,
3647:): $encidx,
3648:): 8)));
3649:): }
3650:): &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
3651:): } else {
3652:): &Failure( $client, "error:no_key\n","$cmd:$tail");
3653:): }
3654:): }
3655:): }
3656:): ®ister_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
3657:):
1.231 foxr 3658: # Store a set of key=value pairs associated with a versioned name.
3659: #
3660: # Parameters:
3661: # $cmd - Request command keyword.
3662: # $tail - Tail of the request. This is a colon
3663: # separated list containing:
3664: # domain/user - User and authentication domain.
3665: # namespace - Name of the database being modified
3666: # rid - Resource keyword to modify.
3667: # what - new value associated with rid.
1.489.2.17 raeburn 3668: # laststore - (optional) version=timestamp
3669: # for most recent transaction for rid
3670: # in namespace, when cstore was called
1.231 foxr 3671: #
3672: # $client - Socket open on the client.
3673: #
3674: #
3675: # Returns:
3676: # 1 (keep on processing).
3677: # Side-Effects:
3678: # Writes to the client
1.489.2.17 raeburn 3679: # Successful storage will cause either 'ok', or, if $laststore was included
3680: # in the tail of the request, and the version number for the last transaction
3681: # is larger than the version in $laststore, delay:$numtrans , where $numtrans
3682: # is the number of store evevnts recorded for rid in namespace since
3683: # lonnet::store() was called by the client.
3684: #
1.231 foxr 3685: sub store_handler {
3686: my ($cmd, $tail, $client) = @_;
3687:
3688: my $userinput = "$cmd:$tail";
3689:
1.489.2.17 raeburn 3690: chomp($tail);
3691: my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231 foxr 3692: if ($namespace ne 'roles') {
3693:
3694: my @pairs=split(/\&/,$what);
3695: my $hashref = &tie_user_hash($udom, $uname, $namespace,
1.268 albertel 3696: &GDBM_WRCREAT(), "S",
1.231 foxr 3697: "$rid:$what");
3698: if ($hashref) {
3699: my $now = time;
1.489.2.17 raeburn 3700: my $numtrans;
3701: if ($laststore) {
3702: my ($previousversion,$previoustime) = split(/\=/,$laststore);
3703: my ($lastversion,$lasttime) = (0,0);
3704: $lastversion = $hashref->{"version:$rid"};
3705: if ($lastversion) {
3706: $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
3707: }
3708: if (($previousversion) && ($previousversion !~ /\D/)) {
3709: if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
3710: $numtrans = $lastversion - $previousversion;
3711: }
3712: } elsif ($lastversion) {
3713: $numtrans = $lastversion;
3714: }
3715: if ($numtrans) {
3716: $numtrans =~ s/D//g;
3717: }
3718: }
3719:
1.231 foxr 3720: $hashref->{"version:$rid"}++;
3721: my $version=$hashref->{"version:$rid"};
3722: my $allkeys='';
3723: foreach my $pair (@pairs) {
3724: my ($key,$value)=split(/=/,$pair);
3725: $allkeys.=$key.':';
3726: $hashref->{"$version:$rid:$key"}=$value;
3727: }
3728: $hashref->{"$version:$rid:timestamp"}=$now;
3729: $allkeys.='timestamp';
3730: $hashref->{"$version:keys:$rid"}=$allkeys;
1.311 albertel 3731: if (&untie_user_hash($hashref)) {
1.489.2.17 raeburn 3732: my $msg = 'ok';
3733: if ($numtrans) {
3734: $msg = 'delay:'.$numtrans;
3735: }
3736: &Reply($client, "$msg\n", $userinput);
1.231 foxr 3737: } else {
3738: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3739: "while attempting store\n", $userinput);
3740: }
3741: } else {
3742: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3743: "while attempting store\n", $userinput);
3744: }
3745: } else {
3746: &Failure($client, "refused\n", $userinput);
3747: }
3748:
3749: return 1;
3750: }
3751: ®ister_handler("store", \&store_handler, 0, 1, 0);
1.263 albertel 3752:
1.323 albertel 3753: # Modify a set of key=value pairs associated with a versioned name.
3754: #
3755: # Parameters:
3756: # $cmd - Request command keyword.
3757: # $tail - Tail of the request. This is a colon
3758: # separated list containing:
3759: # domain/user - User and authentication domain.
3760: # namespace - Name of the database being modified
3761: # rid - Resource keyword to modify.
3762: # v - Version item to modify
3763: # what - new value associated with rid.
3764: #
3765: # $client - Socket open on the client.
3766: #
3767: #
3768: # Returns:
3769: # 1 (keep on processing).
3770: # Side-Effects:
3771: # Writes to the client
3772: sub putstore_handler {
3773: my ($cmd, $tail, $client) = @_;
3774:
3775: my $userinput = "$cmd:$tail";
3776:
3777: my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
3778: if ($namespace ne 'roles') {
3779:
3780: chomp($what);
3781: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3782: &GDBM_WRCREAT(), "M",
3783: "$rid:$v:$what");
3784: if ($hashref) {
3785: my $now = time;
3786: my %data = &hash_extract($what);
3787: my @allkeys;
3788: while (my($key,$value) = each(%data)) {
3789: push(@allkeys,$key);
3790: $hashref->{"$v:$rid:$key"} = $value;
3791: }
3792: my $allkeys = join(':',@allkeys);
3793: $hashref->{"$v:keys:$rid"}=$allkeys;
3794:
3795: if (&untie_user_hash($hashref)) {
3796: &Reply($client, "ok\n", $userinput);
3797: } else {
3798: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3799: "while attempting store\n", $userinput);
3800: }
3801: } else {
3802: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3803: "while attempting store\n", $userinput);
3804: }
3805: } else {
3806: &Failure($client, "refused\n", $userinput);
3807: }
3808:
3809: return 1;
3810: }
3811: ®ister_handler("putstore", \&putstore_handler, 0, 1, 0);
3812:
3813: sub hash_extract {
3814: my ($str)=@_;
3815: my %hash;
3816: foreach my $pair (split(/\&/,$str)) {
3817: my ($key,$value)=split(/=/,$pair);
3818: $hash{$key}=$value;
3819: }
3820: return (%hash);
3821: }
3822: sub hash_to_str {
3823: my ($hash_ref)=@_;
3824: my $str;
3825: foreach my $key (keys(%$hash_ref)) {
3826: $str.=$key.'='.$hash_ref->{$key}.'&';
3827: }
3828: $str=~s/\&$//;
3829: return $str;
3830: }
3831:
1.231 foxr 3832: #
3833: # Dump out all versions of a resource that has key=value pairs associated
3834: # with it for each version. These resources are built up via the store
3835: # command.
3836: #
3837: # Parameters:
3838: # $cmd - Command keyword.
3839: # $tail - Remainder of the request which consists of:
3840: # domain/user - User and auth. domain.
3841: # namespace - name of resource database.
3842: # rid - Resource id.
3843: # $client - socket open on the client.
3844: #
3845: # Returns:
3846: # 1 indicating the caller should not yet exit.
3847: # Side-effects:
3848: # Writes a reply to the client.
3849: # The reply is a string of the following shape:
3850: # version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
3851: # Where the 1 above represents version 1.
3852: # this continues for all pairs of keys in all versions.
3853: #
3854: #
3855: #
3856: #
3857: sub restore_handler {
3858: my ($cmd, $tail, $client) = @_;
3859:
3860: my $userinput = "$cmd:$tail"; # Only used for logging purposes.
1.351 banghart 3861: my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352 albertel 3862: $namespace=~s/\//\_/g;
1.350 albertel 3863: $namespace = &LONCAPA::clean_username($namespace);
1.349 albertel 3864:
1.231 foxr 3865: chomp($rid);
3866: my $qresult='';
1.309 albertel 3867: my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
3868: if ($hashref) {
3869: my $version=$hashref->{"version:$rid"};
1.231 foxr 3870: $qresult.="version=$version&";
3871: my $scope;
3872: for ($scope=1;$scope<=$version;$scope++) {
1.309 albertel 3873: my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231 foxr 3874: my @keys=split(/:/,$vkeys);
3875: my $key;
3876: $qresult.="$scope:keys=$vkeys&";
3877: foreach $key (@keys) {
1.309 albertel 3878: $qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231 foxr 3879: }
3880: }
1.311 albertel 3881: if (&untie_user_hash($hashref)) {
1.231 foxr 3882: $qresult=~s/\&$//;
1.387 albertel 3883: &Reply( $client, \$qresult, $userinput);
1.231 foxr 3884: } else {
3885: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3886: "while attempting restore\n", $userinput);
3887: }
3888: } else {
3889: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3890: "while attempting restore\n", $userinput);
3891: }
3892:
3893: return 1;
3894:
3895:
3896: }
3897: ®ister_handler("restore", \&restore_handler, 0,1,0);
1.234 foxr 3898:
3899: #
1.324 raeburn 3900: # Add a chat message to a synchronous discussion board.
1.234 foxr 3901: #
3902: # Parameters:
3903: # $cmd - Request keyword.
3904: # $tail - Tail of the command. A colon separated list
3905: # containing:
3906: # cdom - Domain on which the chat board lives
1.324 raeburn 3907: # cnum - Course containing the chat board.
3908: # newpost - Body of the posting.
3909: # group - Optional group, if chat board is only
3910: # accessible in a group within the course
1.234 foxr 3911: # $client - Socket open on the client.
3912: # Returns:
3913: # 1 - Indicating caller should keep on processing.
3914: #
3915: # Side-effects:
3916: # writes a reply to the client.
3917: #
3918: #
3919: sub send_chat_handler {
3920: my ($cmd, $tail, $client) = @_;
3921:
3922:
3923: my $userinput = "$cmd:$tail";
3924:
1.324 raeburn 3925: my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
3926: &chat_add($cdom,$cnum,$newpost,$group);
1.234 foxr 3927: &Reply($client, "ok\n", $userinput);
3928:
3929: return 1;
3930: }
3931: ®ister_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263 albertel 3932:
1.234 foxr 3933: #
1.324 raeburn 3934: # Retrieve the set of chat messages from a discussion board.
1.234 foxr 3935: #
3936: # Parameters:
3937: # $cmd - Command keyword that initiated the request.
3938: # $tail - Remainder of the request after the command
3939: # keyword. In this case a colon separated list of
3940: # chat domain - Which discussion board.
3941: # chat id - Discussion thread(?)
3942: # domain/user - Authentication domain and username
3943: # of the requesting person.
1.324 raeburn 3944: # group - Optional course group containing
3945: # the board.
1.234 foxr 3946: # $client - Socket open on the client program.
3947: # Returns:
3948: # 1 - continue processing
3949: # Side effects:
3950: # Response is written to the client.
3951: #
3952: sub retrieve_chat_handler {
3953: my ($cmd, $tail, $client) = @_;
3954:
3955:
3956: my $userinput = "$cmd:$tail";
3957:
1.324 raeburn 3958: my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234 foxr 3959: my $reply='';
1.324 raeburn 3960: foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234 foxr 3961: $reply.=&escape($_).':';
3962: }
3963: $reply=~s/\:$//;
1.387 albertel 3964: &Reply($client, \$reply, $userinput);
1.234 foxr 3965:
3966:
3967: return 1;
3968: }
3969: ®ister_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
3970:
3971: #
3972: # Initiate a query of an sql database. SQL query repsonses get put in
3973: # a file for later retrieval. This prevents sql query results from
3974: # bottlenecking the system. Note that with loncnew, perhaps this is
3975: # less of an issue since multiple outstanding requests can be concurrently
3976: # serviced.
3977: #
3978: # Parameters:
3979: # $cmd - COmmand keyword that initiated the request.
3980: # $tail - Remainder of the command after the keyword.
3981: # For this function, this consists of a query and
3982: # 3 arguments that are self-documentingly labelled
3983: # in the original arg1, arg2, arg3.
3984: # $client - Socket open on the client.
3985: # Return:
3986: # 1 - Indicating processing should continue.
3987: # Side-effects:
3988: # a reply is written to $client.
3989: #
3990: sub send_query_handler {
3991: my ($cmd, $tail, $client) = @_;
3992:
3993:
3994: my $userinput = "$cmd:$tail";
3995:
3996: my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
3997: $query=~s/\n*$//g;
1.489.2.27 raeburn 3998: if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
3999: my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
4000: my $earlyout;
4001: if (ref($usersearchconf) eq 'HASH') {
4002: if ($currentdomainid eq $clienthomedom) {
4003: if ($query eq 'usersearch') {
4004: if ($usersearchconf->{'lcavailable'} eq '0') {
4005: $earlyout = 1;
4006: }
4007: } else {
4008: if ($usersearchconf->{'available'} eq '0') {
4009: $earlyout = 1;
4010: }
4011: }
4012: } else {
4013: if ($query eq 'usersearch') {
4014: if ($usersearchconf->{'lclocalonly'}) {
4015: $earlyout = 1;
4016: }
4017: } else {
4018: if ($usersearchconf->{'localonly'}) {
4019: $earlyout = 1;
4020: }
4021: }
4022: }
4023: }
4024: if ($earlyout) {
4025: &Reply($client, "query_not_authorized\n");
4026: return 1;
4027: }
4028: }
1.234 foxr 4029: &Reply($client, "". &sql_reply("$clientname\&$query".
4030: "\&$arg1"."\&$arg2"."\&$arg3")."\n",
4031: $userinput);
4032:
4033: return 1;
4034: }
4035: ®ister_handler("querysend", \&send_query_handler, 0, 1, 0);
4036:
4037: #
4038: # Add a reply to an sql query. SQL queries are done asyncrhonously.
4039: # The query is submitted via a "querysend" transaction.
4040: # There it is passed on to the lonsql daemon, queued and issued to
4041: # mysql.
4042: # This transaction is invoked when the sql transaction is complete
4043: # it stores the query results in flie and indicates query completion.
4044: # presumably local software then fetches this response... I'm guessing
4045: # the sequence is: lonc does a querysend, we ask lonsql to do it.
4046: # lonsql on completion of the query interacts with the lond of our
4047: # client to do a query reply storing two files:
4048: # - id - The results of the query.
4049: # - id.end - Indicating the transaction completed.
4050: # NOTE: id is a unique id assigned to the query and querysend time.
4051: # Parameters:
4052: # $cmd - Command keyword that initiated this request.
4053: # $tail - Remainder of the tail. In this case that's a colon
4054: # separated list containing the query Id and the
4055: # results of the query.
4056: # $client - Socket open on the client.
4057: # Return:
4058: # 1 - Indicating that we should continue processing.
4059: # Side effects:
4060: # ok written to the client.
4061: #
4062: sub reply_query_handler {
4063: my ($cmd, $tail, $client) = @_;
4064:
4065:
4066: my $userinput = "$cmd:$tail";
4067:
1.339 albertel 4068: my ($id,$reply)=split(/:/,$tail);
1.234 foxr 4069: my $store;
4070: my $execdir=$perlvar{'lonDaemons'};
4071: if ($store=IO::File->new(">$execdir/tmp/$id")) {
4072: $reply=~s/\&/\n/g;
4073: print $store $reply;
4074: close $store;
4075: my $store2=IO::File->new(">$execdir/tmp/$id.end");
4076: print $store2 "done\n";
4077: close $store2;
4078: &Reply($client, "ok\n", $userinput);
4079: } else {
4080: &Failure($client, "error: ".($!+0)
4081: ." IO::File->new Failed ".
4082: "while attempting queryreply\n", $userinput);
4083: }
4084:
4085:
4086: return 1;
4087: }
4088: ®ister_handler("queryreply", \&reply_query_handler, 0, 1, 0);
4089:
4090: #
4091: # Process the courseidput request. Not quite sure what this means
4092: # at the system level sense. It appears a gdbm file in the
4093: # /home/httpd/lonUsers/$domain/nohist_courseids is tied and
4094: # a set of entries made in that database.
4095: #
4096: # Parameters:
4097: # $cmd - The command keyword that initiated this request.
4098: # $tail - Tail of the command. In this case consists of a colon
4099: # separated list contaning the domain to apply this to and
4100: # an ampersand separated list of keyword=value pairs.
1.272 raeburn 4101: # Each value is a colon separated list that includes:
4102: # description, institutional code and course owner.
4103: # For backward compatibility with versions included
4104: # in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
4105: # code and/or course owner are preserved from the existing
4106: # record when writing a new record in response to 1.1 or
4107: # 1.2 implementations of lonnet::flushcourselogs().
4108: #
1.234 foxr 4109: # $client - Socket open on the client.
4110: # Returns:
4111: # 1 - indicating that processing should continue
4112: #
4113: # Side effects:
4114: # reply is written to the client.
4115: #
4116: sub put_course_id_handler {
4117: my ($cmd, $tail, $client) = @_;
4118:
4119:
4120: my $userinput = "$cmd:$tail";
4121:
1.266 raeburn 4122: my ($udom, $what) = split(/:/, $tail,2);
1.234 foxr 4123: chomp($what);
4124: my $now=time;
4125: my @pairs=split(/\&/,$what);
4126:
4127: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
4128: if ($hashref) {
4129: foreach my $pair (@pairs) {
1.271 raeburn 4130: my ($key,$courseinfo) = split(/=/,$pair,2);
4131: $courseinfo =~ s/=/:/g;
1.384 raeburn 4132: if (defined($hashref->{$key})) {
4133: my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
4134: if (ref($value) eq 'HASH') {
4135: my @items = ('description','inst_code','owner','type');
4136: my @new_items = split(/:/,$courseinfo,-1);
4137: my %storehash;
4138: for (my $i=0; $i<@new_items; $i++) {
1.391 raeburn 4139: $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384 raeburn 4140: }
4141: $hashref->{$key} =
4142: &Apache::lonnet::freeze_escape(\%storehash);
4143: my $unesc_key = &unescape($key);
4144: $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
4145: next;
1.383 raeburn 4146: }
1.384 raeburn 4147: }
4148: my @current_items = split(/:/,$hashref->{$key},-1);
4149: shift(@current_items); # remove description
4150: pop(@current_items); # remove last access
4151: my $numcurrent = scalar(@current_items);
4152: if ($numcurrent > 3) {
4153: $numcurrent = 3;
4154: }
4155: my @new_items = split(/:/,$courseinfo,-1);
4156: my $numnew = scalar(@new_items);
4157: if ($numcurrent > 0) {
4158: if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2
4159: for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
4160: $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333 raeburn 4161: }
1.272 raeburn 4162: }
4163: }
1.384 raeburn 4164: $hashref->{$key}=$courseinfo.':'.$now;
1.234 foxr 4165: }
1.311 albertel 4166: if (&untie_domain_hash($hashref)) {
1.253 foxr 4167: &Reply( $client, "ok\n", $userinput);
1.234 foxr 4168: } else {
1.253 foxr 4169: &Failure($client, "error: ".($!+0)
1.234 foxr 4170: ." untie(GDBM) Failed ".
4171: "while attempting courseidput\n", $userinput);
4172: }
4173: } else {
1.253 foxr 4174: &Failure($client, "error: ".($!+0)
1.234 foxr 4175: ." tie(GDBM) Failed ".
4176: "while attempting courseidput\n", $userinput);
4177: }
4178:
4179: return 1;
4180: }
4181: ®ister_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
4182:
1.383 raeburn 4183: sub put_course_id_hash_handler {
4184: my ($cmd, $tail, $client) = @_;
4185: my $userinput = "$cmd:$tail";
1.384 raeburn 4186: my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383 raeburn 4187: chomp($what);
4188: my $now=time;
4189: my @pairs=split(/\&/,$what);
1.384 raeburn 4190: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383 raeburn 4191: if ($hashref) {
4192: foreach my $pair (@pairs) {
4193: my ($key,$value)=split(/=/,$pair);
1.384 raeburn 4194: my $unesc_key = &unescape($key);
4195: if ($mode ne 'timeonly') {
4196: if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
4197: my $curritems = &Apache::lonnet::thaw_unescape($key);
4198: if (ref($curritems) ne 'HASH') {
4199: my @current_items = split(/:/,$hashref->{$key},-1);
4200: my $lasttime = pop(@current_items);
4201: $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
4202: } else {
4203: $hashref->{&escape('lasttime:'.$unesc_key)} = '';
4204: }
4205: }
4206: $hashref->{$key} = $value;
4207: }
4208: if ($mode ne 'notime') {
4209: $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
4210: }
1.383 raeburn 4211: }
4212: if (&untie_domain_hash($hashref)) {
4213: &Reply($client, "ok\n", $userinput);
4214: } else {
4215: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4216: "while attempting courseidputhash\n", $userinput);
4217: }
4218: } else {
4219: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4220: "while attempting courseidputhash\n", $userinput);
4221: }
4222: return 1;
4223: }
4224: ®ister_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
4225:
1.234 foxr 4226: # Retrieves the value of a course id resource keyword pattern
4227: # defined since a starting date. Both the starting date and the
4228: # keyword pattern are optional. If the starting date is not supplied it
4229: # is treated as the beginning of time. If the pattern is not found,
4230: # it is treatred as "." matching everything.
4231: #
4232: # Parameters:
4233: # $cmd - Command keyword that resulted in us being dispatched.
4234: # $tail - The remainder of the command that, in this case, consists
4235: # of a colon separated list of:
4236: # domain - The domain in which the course database is
4237: # defined.
4238: # since - Optional parameter describing the minimum
4239: # time of definition(?) of the resources that
4240: # will match the dump.
4241: # description - regular expression that is used to filter
4242: # the dump. Only keywords matching this regexp
4243: # will be used.
1.272 raeburn 4244: # institutional code - optional supplied code to filter
4245: # the dump. Only courses with an institutional code
4246: # that match the supplied code will be returned.
1.336 raeburn 4247: # owner - optional supplied username and domain of owner to
4248: # filter the dump. Only courses for which the course
4249: # owner matches the supplied username and/or domain
4250: # will be returned. Pre-2.2.0 legacy entries from
4251: # nohist_courseiddump will only contain usernames.
1.384 raeburn 4252: # type - optional parameter for selection
1.418 raeburn 4253: # regexp_ok - if 1 or -1 allow the supplied institutional code
4254: # filter to behave as a regular expression:
4255: # 1 will not exclude the course if the instcode matches the RE
4256: # -1 will exclude the course if the instcode matches the RE
1.384 raeburn 4257: # rtn_as_hash - whether to return the information available for
4258: # each matched item as a frozen hash of all
4259: # key, value pairs in the item's hash, or as a
4260: # colon-separated list of (in order) description,
4261: # institutional code, and course owner.
1.404 raeburn 4262: # selfenrollonly - filter by courses allowing self-enrollment
4263: # now or in the future (selfenrollonly = 1).
4264: # catfilter - filter by course category, assigned to a course
4265: # using manually defined categories (i.e., not
1.407 raeburn 4266: # self-cataloging based on on institutional code).
1.404 raeburn 4267: # showhidden - include course in results even if course
1.407 raeburn 4268: # was set to be excluded from course catalog (DC only).
1.404 raeburn 4269: # caller - if set to 'coursecatalog', courses set to be hidden
4270: # from course catalog will be excluded from results (unless
4271: # overridden by "showhidden".
1.427 raeburn 4272: # cloner - escaped username:domain of course cloner (if picking course to
1.419 raeburn 4273: # clone).
4274: # cc_clone_list - escaped comma separated list of courses for which
4275: # course cloner has active CC role (and so can clone
4276: # automatically).
1.427 raeburn 4277: # cloneonly - filter by courses for which cloner has rights to clone.
4278: # createdbefore - include courses for which creation date preceeded this date.
4279: # createdafter - include courses for which creation date followed this date.
4280: # creationcontext - include courses created in specified context
1.404 raeburn 4281: #
1.445 raeburn 4282: # domcloner - flag to indicate if user can create CCs in course's domain.
1.489.2.11 raeburn 4283: # If so, ability to clone course is automatic.
4284: # hasuniquecode - filter by courses for which a six character unique code has
4285: # been set.
1.445 raeburn 4286: #
1.234 foxr 4287: # $client - The socket open on the client.
4288: # Returns:
4289: # 1 - Continue processing.
4290: # Side Effects:
4291: # a reply is written to $client.
4292: sub dump_course_id_handler {
4293: my ($cmd, $tail, $client) = @_;
4294: my $userinput = "$cmd:$tail";
4295:
1.333 raeburn 4296: my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404 raeburn 4297: $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427 raeburn 4298: $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.489.2.11 raeburn 4299: $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397 raeburn 4300: my $now = time;
1.419 raeburn 4301: my ($cloneruname,$clonerudom,%cc_clone);
1.234 foxr 4302: if (defined($description)) {
4303: $description=&unescape($description);
4304: } else {
4305: $description='.';
4306: }
1.266 raeburn 4307: if (defined($instcodefilter)) {
4308: $instcodefilter=&unescape($instcodefilter);
4309: } else {
4310: $instcodefilter='.';
4311: }
1.336 raeburn 4312: my ($ownerunamefilter,$ownerdomfilter);
1.266 raeburn 4313: if (defined($ownerfilter)) {
4314: $ownerfilter=&unescape($ownerfilter);
1.336 raeburn 4315: if ($ownerfilter ne '.' && defined($ownerfilter)) {
4316: if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
4317: $ownerunamefilter = $1;
4318: $ownerdomfilter = $2;
4319: } else {
4320: $ownerunamefilter = $ownerfilter;
4321: $ownerdomfilter = '';
4322: }
4323: }
1.266 raeburn 4324: } else {
4325: $ownerfilter='.';
4326: }
1.336 raeburn 4327:
1.282 raeburn 4328: if (defined($coursefilter)) {
4329: $coursefilter=&unescape($coursefilter);
4330: } else {
4331: $coursefilter='.';
4332: }
1.333 raeburn 4333: if (defined($typefilter)) {
4334: $typefilter=&unescape($typefilter);
4335: } else {
4336: $typefilter='.';
4337: }
1.344 raeburn 4338: if (defined($regexp_ok)) {
4339: $regexp_ok=&unescape($regexp_ok);
4340: }
1.401 raeburn 4341: if (defined($catfilter)) {
4342: $catfilter=&unescape($catfilter);
4343: }
1.419 raeburn 4344: if (defined($cloner)) {
4345: $cloner = &unescape($cloner);
4346: ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/);
4347: }
4348: if (defined($cc_clone_list)) {
4349: $cc_clone_list = &unescape($cc_clone_list);
4350: my @cc_cloners = split('&',$cc_clone_list);
4351: foreach my $cid (@cc_cloners) {
4352: my ($clonedom,$clonenum) = split(':',$cid);
4353: next if ($clonedom ne $udom);
4354: $cc_clone{$clonedom.'_'.$clonenum} = 1;
4355: }
4356: }
1.431 raeburn 4357: if ($createdbefore ne '') {
1.427 raeburn 4358: $createdbefore = &unescape($createdbefore);
4359: } else {
4360: $createdbefore = 0;
4361: }
1.431 raeburn 4362: if ($createdafter ne '') {
1.427 raeburn 4363: $createdafter = &unescape($createdafter);
4364: } else {
4365: $createdafter = 0;
4366: }
1.431 raeburn 4367: if ($creationcontext ne '') {
1.427 raeburn 4368: $creationcontext = &unescape($creationcontext);
4369: } else {
4370: $creationcontext = '.';
4371: }
1.489.2.11 raeburn 4372: unless ($hasuniquecode) {
4373: $hasuniquecode = '.';
4374: }
1.384 raeburn 4375: my $unpack = 1;
1.485 raeburn 4376: if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' &&
1.384 raeburn 4377: $typefilter eq '.') {
4378: $unpack = 0;
4379: }
4380: if (!defined($since)) { $since=0; }
1.234 foxr 4381: my $qresult='';
4382: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
4383: if ($hashref) {
1.384 raeburn 4384: while (my ($key,$value) = each(%$hashref)) {
1.397 raeburn 4385: my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427 raeburn 4386: %unesc_val,$selfenroll_end,$selfenroll_types,$created,
4387: $context);
1.384 raeburn 4388: $unesc_key = &unescape($key);
4389: if ($unesc_key =~ /^lasttime:/) {
4390: next;
4391: } else {
4392: $lasttime_key = &escape('lasttime:'.$unesc_key);
4393: }
4394: if ($hashref->{$lasttime_key} ne '') {
4395: $lasttime = $hashref->{$lasttime_key};
4396: next if ($lasttime<$since);
4397: }
1.419 raeburn 4398: my ($canclone,$valchange);
1.384 raeburn 4399: my $items = &Apache::lonnet::thaw_unescape($value);
4400: if (ref($items) eq 'HASH') {
1.429 raeburn 4401: if ($hashref->{$lasttime_key} eq '') {
1.430 raeburn 4402: next if ($since > 1);
1.429 raeburn 4403: }
1.384 raeburn 4404: $is_hash = 1;
1.445 raeburn 4405: if ($domcloner) {
4406: $canclone = 1;
4407: } elsif (defined($clonerudom)) {
1.419 raeburn 4408: if ($items->{'cloners'}) {
4409: my @cloneable = split(',',$items->{'cloners'});
4410: if (@cloneable) {
4411: if (grep(/^\*$/,@cloneable)) {
4412: $canclone = 1;
4413: } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
4414: $canclone = 1;
4415: } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
4416: $canclone = 1;
4417: }
4418: }
4419: unless ($canclone) {
4420: if ($cloneruname ne '' && $clonerudom ne '') {
4421: if ($cc_clone{$unesc_key}) {
4422: $canclone = 1;
4423: $items->{'cloners'} .= ','.$cloneruname.':'.
4424: $clonerudom;
4425: $valchange = 1;
4426: }
4427: }
4428: }
4429: } elsif (defined($cloneruname)) {
4430: if ($cc_clone{$unesc_key}) {
4431: $canclone = 1;
4432: $items->{'cloners'} = $cloneruname.':'.$clonerudom;
4433: $valchange = 1;
4434: }
1.437 raeburn 4435: unless ($canclone) {
4436: if ($items->{'owner'} =~ /:/) {
4437: if ($items->{'owner'} eq $cloner) {
4438: $canclone = 1;
4439: }
1.444 raeburn 4440: } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437 raeburn 4441: $canclone = 1;
4442: }
4443: if ($canclone) {
4444: $items->{'cloners'} = $cloneruname.':'.$clonerudom;
4445: $valchange = 1;
4446: }
4447: }
1.419 raeburn 4448: }
4449: }
1.384 raeburn 4450: if ($unpack || !$rtn_as_hash) {
4451: $unesc_val{'descr'} = $items->{'description'};
4452: $unesc_val{'inst_code'} = $items->{'inst_code'};
4453: $unesc_val{'owner'} = $items->{'owner'};
4454: $unesc_val{'type'} = $items->{'type'};
1.419 raeburn 4455: $unesc_val{'cloners'} = $items->{'cloners'};
1.427 raeburn 4456: $unesc_val{'created'} = $items->{'created'};
4457: $unesc_val{'context'} = $items->{'context'};
1.404 raeburn 4458: }
4459: $selfenroll_types = $items->{'selfenroll_types'};
4460: $selfenroll_end = $items->{'selfenroll_end_date'};
1.427 raeburn 4461: $created = $items->{'created'};
4462: $context = $items->{'context'};
1.489.2.11 raeburn 4463: if ($hasuniquecode ne '.') {
4464: next unless ($items->{'uniquecode'});
4465: }
1.404 raeburn 4466: if ($selfenrollonly) {
4467: next if (!$selfenroll_types);
4468: if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
4469: next;
1.397 raeburn 4470: }
1.404 raeburn 4471: }
1.427 raeburn 4472: if ($creationcontext ne '.') {
4473: next if (($context ne '') && ($context ne $creationcontext));
4474: }
4475: if ($createdbefore > 0) {
4476: next if (($created eq '') || ($created > $createdbefore));
4477: }
4478: if ($createdafter > 0) {
4479: next if (($created eq '') || ($created <= $createdafter));
4480: }
1.404 raeburn 4481: if ($catfilter ne '') {
1.406 raeburn 4482: next if ($items->{'categories'} eq '');
4483: my @categories = split('&',$items->{'categories'});
1.407 raeburn 4484: next if (@categories == 0);
4485: my @subcats = split('&',$catfilter);
4486: my $matchcat = 0;
4487: foreach my $cat (@categories) {
4488: if (grep(/^\Q$cat\E$/,@subcats)) {
4489: $matchcat = 1;
4490: last;
4491: }
4492: }
4493: next if (!$matchcat);
1.404 raeburn 4494: }
4495: if ($caller eq 'coursecatalog') {
1.405 raeburn 4496: if ($items->{'hidefromcat'} eq 'yes') {
4497: next if !$showhidden;
1.401 raeburn 4498: }
1.384 raeburn 4499: }
1.383 raeburn 4500: } else {
1.401 raeburn 4501: next if ($catfilter ne '');
1.419 raeburn 4502: next if ($selfenrollonly);
1.427 raeburn 4503: next if ($createdbefore || $createdafter);
4504: next if ($creationcontext ne '.');
1.419 raeburn 4505: if ((defined($clonerudom)) && (defined($cloneruname))) {
4506: if ($cc_clone{$unesc_key}) {
4507: $canclone = 1;
4508: $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
4509: }
4510: }
1.384 raeburn 4511: $is_hash = 0;
1.388 raeburn 4512: my @courseitems = split(/:/,$value);
1.403 raeburn 4513: $lasttime = pop(@courseitems);
1.402 raeburn 4514: if ($hashref->{$lasttime_key} eq '') {
4515: next if ($lasttime<$since);
4516: }
1.384 raeburn 4517: ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383 raeburn 4518: }
1.419 raeburn 4519: if ($cloneonly) {
4520: next unless ($canclone);
4521: }
1.266 raeburn 4522: my $match = 1;
1.384 raeburn 4523: if ($description ne '.') {
4524: if (!$is_hash) {
4525: $unesc_val{'descr'} = &unescape($val{'descr'});
4526: }
4527: if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266 raeburn 4528: $match = 0;
1.384 raeburn 4529: }
1.266 raeburn 4530: }
1.384 raeburn 4531: if ($instcodefilter ne '.') {
4532: if (!$is_hash) {
4533: $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
4534: }
1.418 raeburn 4535: if ($regexp_ok == 1) {
1.384 raeburn 4536: if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344 raeburn 4537: $match = 0;
4538: }
1.418 raeburn 4539: } elsif ($regexp_ok == -1) {
4540: if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
4541: $match = 0;
4542: }
1.344 raeburn 4543: } else {
1.384 raeburn 4544: if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344 raeburn 4545: $match = 0;
4546: }
1.266 raeburn 4547: }
1.234 foxr 4548: }
1.384 raeburn 4549: if ($ownerfilter ne '.') {
4550: if (!$is_hash) {
4551: $unesc_val{'owner'} = &unescape($val{'owner'});
4552: }
1.336 raeburn 4553: if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384 raeburn 4554: if ($unesc_val{'owner'} =~ /:/) {
4555: if (eval{$unesc_val{'owner'} !~
4556: /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336 raeburn 4557: $match = 0;
4558: }
4559: } else {
1.384 raeburn 4560: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336 raeburn 4561: $match = 0;
4562: }
4563: }
4564: } elsif ($ownerunamefilter ne '') {
1.384 raeburn 4565: if ($unesc_val{'owner'} =~ /:/) {
4566: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336 raeburn 4567: $match = 0;
4568: }
4569: } else {
1.384 raeburn 4570: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336 raeburn 4571: $match = 0;
4572: }
4573: }
4574: } elsif ($ownerdomfilter ne '') {
1.384 raeburn 4575: if ($unesc_val{'owner'} =~ /:/) {
4576: if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336 raeburn 4577: $match = 0;
4578: }
4579: } else {
4580: if ($ownerdomfilter ne $udom) {
4581: $match = 0;
4582: }
4583: }
1.266 raeburn 4584: }
4585: }
1.384 raeburn 4586: if ($coursefilter ne '.') {
4587: if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282 raeburn 4588: $match = 0;
4589: }
4590: }
1.384 raeburn 4591: if ($typefilter ne '.') {
4592: if (!$is_hash) {
4593: $unesc_val{'type'} = &unescape($val{'type'});
4594: }
4595: if ($unesc_val{'type'} eq '') {
1.333 raeburn 4596: if ($typefilter ne 'Course') {
4597: $match = 0;
4598: }
1.383 raeburn 4599: } else {
1.384 raeburn 4600: if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333 raeburn 4601: $match = 0;
4602: }
4603: }
4604: }
1.266 raeburn 4605: if ($match == 1) {
1.384 raeburn 4606: if ($rtn_as_hash) {
4607: if ($is_hash) {
1.419 raeburn 4608: if ($valchange) {
4609: my $newvalue = &Apache::lonnet::freeze_escape($items);
4610: $qresult.=$key.'='.$newvalue.'&';
4611: } else {
4612: $qresult.=$key.'='.$value.'&';
4613: }
1.384 raeburn 4614: } else {
1.388 raeburn 4615: my %rtnhash = ( 'description' => &unescape($val{'descr'}),
4616: 'inst_code' => &unescape($val{'inst_code'}),
4617: 'owner' => &unescape($val{'owner'}),
4618: 'type' => &unescape($val{'type'}),
1.419 raeburn 4619: 'cloners' => &unescape($val{'cloners'}),
1.384 raeburn 4620: );
4621: my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
4622: $qresult.=$key.'='.$items.'&';
4623: }
1.383 raeburn 4624: } else {
1.384 raeburn 4625: if ($is_hash) {
4626: $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
4627: &escape($unesc_val{'inst_code'}).':'.
4628: &escape($unesc_val{'owner'}).'&';
4629: } else {
4630: $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
4631: ':'.$val{'owner'}.'&';
4632: }
1.383 raeburn 4633: }
1.266 raeburn 4634: }
1.234 foxr 4635: }
1.311 albertel 4636: if (&untie_domain_hash($hashref)) {
1.234 foxr 4637: chop($qresult);
1.387 albertel 4638: &Reply($client, \$qresult, $userinput);
1.234 foxr 4639: } else {
4640: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4641: "while attempting courseiddump\n", $userinput);
4642: }
4643: } else {
4644: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4645: "while attempting courseiddump\n", $userinput);
4646: }
4647: return 1;
4648: }
4649: ®ister_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238 foxr 4650:
1.438 raeburn 4651: sub course_lastaccess_handler {
4652: my ($cmd, $tail, $client) = @_;
4653: my $userinput = "$cmd:$tail";
4654: my ($cdom,$cnum) = split(':',$tail);
4655: my (%lastaccess,$qresult);
4656: my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
4657: if ($hashref) {
4658: while (my ($key,$value) = each(%$hashref)) {
4659: my ($unesc_key,$lasttime);
4660: $unesc_key = &unescape($key);
4661: if ($cnum) {
4662: next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
4663: }
4664: if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
4665: $lastaccess{$1} = $value;
4666: } else {
4667: my $items = &Apache::lonnet::thaw_unescape($value);
4668: if (ref($items) eq 'HASH') {
4669: unless ($lastaccess{$unesc_key}) {
4670: $lastaccess{$unesc_key} = '';
4671: }
4672: } else {
4673: my @courseitems = split(':',$value);
4674: $lastaccess{$unesc_key} = pop(@courseitems);
4675: }
4676: }
4677: }
4678: foreach my $cid (sort(keys(%lastaccess))) {
4679: $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&';
4680: }
4681: if (&untie_domain_hash($hashref)) {
4682: if ($qresult) {
4683: chop($qresult);
4684: }
4685: &Reply($client, \$qresult, $userinput);
4686: } else {
4687: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4688: "while attempting lastacourseaccess\n", $userinput);
4689: }
4690: } else {
4691: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4692: "while attempting lastcourseaccess\n", $userinput);
4693: }
4694: return 1;
4695: }
4696: ®ister_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
4697:
1.489.2.36 raeburn 4698: sub course_sessions_handler {
4699: my ($cmd, $tail, $client) = @_;
4700: my $userinput = "$cmd:$tail";
4701: my ($cdom,$cnum,$lastactivity) = split(':',$tail);
4702: my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
4703: my (%sessions,$qresult);
4704: my $now=time;
4705: if (opendir(DIR,$perlvar{'lonIDsDir'})) {
4706: my $filename;
4707: while ($filename=readdir(DIR)) {
4708: next if ($filename=~/^\./);
4709: next if ($filename=~/^publicuser_/);
4710: next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.489.2.37 raeburn 4711: if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.489.2.36 raeburn 4712: my ($uname,$udom) = ($1,$2);
1.489.2.37 raeburn 4713: next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.489.2.36 raeburn 4714: my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
4715: if ($lastactivity < 0) {
1.489.2.38 raeburn 4716: next if ($mtime-$now > $lastactivity);
1.489.2.36 raeburn 4717: } else {
1.489.2.38 raeburn 4718: next if ($now-$mtime > $lastactivity);
1.489.2.36 raeburn 4719: }
4720: $sessions{$uname.':'.$udom} = $mtime;
4721: }
4722: }
4723: closedir(DIR);
4724: }
4725: foreach my $user (keys(%sessions)) {
4726: $qresult.=&escape($user).'='.$sessions{$user}.'&';
4727: }
4728: if ($qresult) {
4729: chop($qresult);
4730: }
4731: &Reply($client, \$qresult, $userinput);
4732: return 1;
4733: }
4734: ®ister_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
4735:
1.238 foxr 4736: #
1.348 raeburn 4737: # Puts an unencrypted entry in a namespace db file at the domain level
4738: #
4739: # Parameters:
4740: # $cmd - The command that got us here.
4741: # $tail - Tail of the command (remaining parameters).
4742: # $client - File descriptor connected to client.
4743: # Returns
4744: # 0 - Requested to exit, caller should shut down.
4745: # 1 - Continue processing.
4746: # Side effects:
4747: # reply is written to $client.
4748: #
4749: sub put_domain_handler {
4750: my ($cmd,$tail,$client) = @_;
4751:
4752: my $userinput = "$cmd:$tail";
4753:
4754: my ($udom,$namespace,$what) =split(/:/,$tail,3);
4755: chomp($what);
4756: my @pairs=split(/\&/,$what);
4757: my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
4758: "P", $what);
4759: if ($hashref) {
4760: foreach my $pair (@pairs) {
4761: my ($key,$value)=split(/=/,$pair);
4762: $hashref->{$key}=$value;
4763: }
4764: if (&untie_domain_hash($hashref)) {
4765: &Reply($client, "ok\n", $userinput);
4766: } else {
4767: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4768: "while attempting putdom\n", $userinput);
4769: }
4770: } else {
4771: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4772: "while attempting putdom\n", $userinput);
4773: }
4774:
4775: return 1;
4776: }
4777: ®ister_handler("putdom", \&put_domain_handler, 0, 1, 0);
4778:
4779: # Unencrypted get from the namespace database file at the domain level.
4780: # This function retrieves a keyed item from a specific named database in the
4781: # domain directory.
4782: #
4783: # Parameters:
1.489.2.40 raeburn 4784: # $cmd - Command request keyword (getdom).
1.348 raeburn 4785: # $tail - Tail of the command. This is a colon separated list
4786: # consisting of the domain and the 'namespace'
4787: # which selects the gdbm file to do the lookup in,
4788: # & separated list of keys to lookup. Note that
4789: # the values are returned as an & separated list too.
4790: # $client - File descriptor open on the client.
4791: # Returns:
4792: # 1 - Continue processing.
4793: # 0 - Exit.
4794: # Side effects:
4795: # reply is written to $client.
4796: #
4797:
4798: sub get_domain_handler {
4799: my ($cmd, $tail, $client) = @_;
4800:
1.489.2.34 raeburn 4801: my $userinput = "$cmd:$tail";
1.348 raeburn 4802:
4803: my ($udom,$namespace,$what)=split(/:/,$tail,3);
1.489.2.43.2. (raeburn 4804:): if (($namespace =~ /^enc/) || ($namespace eq 'private')) {
4805:): &Failure( $client, "refused\n", $userinput);
4806:): } else {
4807:): my $res = LONCAPA::Lond::get_dom($userinput);
4808:): if ($res =~ /^error:/) {
4809:): &Failure($client, \$res, $userinput);
4810:): } else {
4811:): &Reply($client, \$res, $userinput);
4812:): }
4813:): }
4814:):
4815:): return 1;
4816:): }
4817:): ®ister_handler("getdom", \&get_domain_handler, 0, 1, 0);
4818:):
4819:): sub encrypted_get_domain_handler {
4820:): my ($cmd, $tail, $client) = @_;
4821:):
4822:): my $userinput = "$cmd:$tail";
4823:):
4824:): my ($udom,$namespace,$what) = split(/:/,$tail,3);
4825:): if ($namespace eq 'private') {
4826:): &Failure( $client, "refused\n", $userinput);
1.348 raeburn 4827: } else {
1.489.2.43.2. (raeburn 4828:): my $res = LONCAPA::Lond::get_dom($userinput);
4829:): if ($res =~ /^error:/) {
4830:): &Failure($client, \$res, $userinput);
4831:): } else {
4832:): if ($cipher) {
4833:): my $cmdlength=length($res);
4834:): $res.=" ";
4835:): my $encres='';
4836:): for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
4837:): $encres.= unpack("H16",
4838:): $cipher->encrypt(substr($res,
4839:): $encidx,
4840:): 8)));
4841:): }
4842:): &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
4843:): } else {
4844:): &Failure( $client, "error:no_key\n",$userinput);
4845:): }
4846:): }
1.348 raeburn 4847: }
4848: return 1;
4849: }
1.489.2.43.2. (raeburn 4850:): ®ister_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348 raeburn 4851:
1.420 raeburn 4852: #
1.489.2.43.2. (raeburn 4853:): # Encrypted get from the namespace database file at the domain level.
4854:): # This function retrieves a keyed item from a specific named database in the
4855:): # domain directory.
4856:): #
4857:): # Parameters:
4858:): # $cmd - Command request keyword (lti).
4859:): # $tail - Tail of the command. This is a colon-separated list
4860:): # consisting of the domain, coursenum, if for LTI-
4861:): # enabled deep-linking to course content using
4862:): # link protection configured within a course,
4863:): # context (=deeplink) if for LTI-enabled deep-linking
4864:): # to course content using LTI Provider settings
4865:): # configured within a course's domain, the (escaped)
4866:): # launch URL, the (escaped) method (typically POST),
4867:): # and a frozen hash of the LTI launch parameters
4868:): # from the LTI payload.
4869:): # $client - File descriptor open on the client.
4870:): # Returns:
4871:): # 1 - Continue processing.
4872:): # 0 - Exit.
4873:): # Side effects:
4874:): # The reply will contain an LTI itemID, if the signed LTI payload
4875:): # could be verified using the consumer key and the shared secret
4876:): # available for that key (for the itemID) for either the course or domain,
4877:): # depending on values for cnum and context. The reply is encrypted before
4878:): # being written to $client.
4879:): #
4880:): sub lti_handler {
4881:): my ($cmd, $tail, $client) = @_;
4882:):
4883:): my $userinput = "$cmd:$tail";
4884:):
4885:): my ($cdom,$cnum,$context,$escurl,$escmethod,$items) = split(/:/,$tail);
4886:): my $url = &unescape($escurl);
4887:): my $method = &unescape($escmethod);
4888:): my $params = &Apache::lonnet::thaw_unescape($items);
4889:): my $res;
4890:): if ($cnum ne '') {
4891:): $res = &LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
4892:): } else {
4893:): $res = &LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
4894:): }
4895:): if ($res =~ /^error:/) {
4896:): &Failure($client, \$res, $userinput);
4897:): } else {
4898:): if ($cipher) {
4899:): my $cmdlength=length($res);
4900:): $res.=" ";
4901:): my $encres='';
4902:): for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
4903:): $encres.= unpack("H16",
4904:): $cipher->encrypt(substr($res,
4905:): $encidx,
4906:): 8)));
4907:): }
4908:): &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
4909:): } else {
4910:): &Failure( $client, "error:no_key\n",$userinput);
4911:): }
4912:): }
4913:): return 1;
4914:): }
4915:): ®ister_handler("lti", \<i_handler, 1, 1, 0);
4916:):
4917:): #
4918:): # Data for LTI payload (received encrypted) are unencrypted and
4919:): # then signed with the appropriate key and secret, before re-encrypting
4920:): # the signed payload which is sent to the client for unencryption by
4921:): # the caller: lonnet::sign_lti()) before dispatch either to a web browser
4922:): # (launch) or to a remote web service (roster, logout, or grade).
4923:): #
4924:): # Parameters:
4925:): # $cmd - Command request keyword (signlti).
4926:): # $tail - Tail of the command. This is a colon-separated list
4927:): # consisting of the domain, coursenum (if for an External
4928:): # Tool defined in a course), crsdef (true if defined in
4929:): # a course), type (linkprot or lti),
4930:): # context (launch, roster, logout, or grade),
4931:): # escaped launch URL, numeric ID of external tool,
4932:): # version number for encryption key (if tool's LTI secret was
4933:): # encrypted before storing), a frozen hash of LTI launch
4934:): # parameters, and a frozen hash of LTI information,
4935:): # (e.g., method => 'HMAC-SHA1',
4936:): # respfmt => 'to_authorization_header').
4937:): # $client - File descriptor open on the client.
4938:): # Returns:
4939:): # 1 - Continue processing.
4940:): # 0 - Exit.
4941:): # Side effects:
4942:): # The reply will contain the LTI payload, as & separated key=value pairs,
4943:): # where value is itself a frozen hash, if the required key and secret
4944:): # for the specific tool ID are available. The payload data are retrieved from
4945:): # a call to Lond::sign_lti_payload(), and the reply is encrypted before being
4946:): # written to $client.
4947:): #
4948:): sub sign_lti_handler {
4949:): my ($cmd, $tail, $client) = @_;
4950:):
4951:): my $userinput = "$cmd:$tail";
4952:):
4953:): my ($cdom,$cnum,$crsdef,$type,$context,$escurl,
4954:): $ltinum,$keynum,$paramsref,$inforef) = split(/:/,$tail);
4955:): my $url = &unescape($escurl);
4956:): my $params = &Apache::lonnet::thaw_unescape($paramsref);
4957:): my $info = &Apache::lonnet::thaw_unescape($inforef);
4958:): my $res =
4959:): &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,
4960:): $keynum,$perlvar{'lonVersion'},$params,$info);
4961:): my $result;
4962:): if (ref($res) eq 'HASH') {
4963:): foreach my $key (keys(%{$res})) {
4964:): $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($res->{$key}).'&';
4965:): }
4966:): $result =~ s/\&$//;
4967:): } else {
4968:): $result = $res;
4969:): }
4970:): if ($result =~ /^error:/) {
4971:): &Failure($client, \$result, $userinput);
4972:): } else {
4973:): if ($cipher) {
4974:): my $cmdlength=length($result);
4975:): $result.=" ";
4976:): my $encres='';
4977:): for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
4978:): $encres.= unpack("H16",
4979:): $cipher->encrypt(substr($result,
4980:): $encidx,
4981:): 8)));
4982:): }
4983:): &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
4984:): } else {
4985:): &Failure( $client, "error:no_key\n",$userinput);
4986:): }
4987:): }
4988:): return 1;
4989:): }
4990:): ®ister_handler("signlti", \&sign_lti_handler, 1, 1, 0);
4991:):
4992:): #
1.238 foxr 4993: # Puts an id to a domains id database.
4994: #
4995: # Parameters:
4996: # $cmd - The command that triggered us.
4997: # $tail - Remainder of the request other than the command. This is a
4998: # colon separated list containing:
4999: # $domain - The domain for which we are writing the id.
5000: # $pairs - The id info to write... this is and & separated list
5001: # of keyword=value.
5002: # $client - Socket open on the client.
5003: # Returns:
5004: # 1 - Continue processing.
5005: # Side effects:
5006: # reply is written to $client.
5007: #
5008: sub put_id_handler {
5009: my ($cmd,$tail,$client) = @_;
5010:
5011:
5012: my $userinput = "$cmd:$tail";
5013:
5014: my ($udom,$what)=split(/:/,$tail);
5015: chomp($what);
5016: my @pairs=split(/\&/,$what);
5017: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
5018: "P", $what);
5019: if ($hashref) {
5020: foreach my $pair (@pairs) {
5021: my ($key,$value)=split(/=/,$pair);
5022: $hashref->{$key}=$value;
5023: }
1.311 albertel 5024: if (&untie_domain_hash($hashref)) {
1.238 foxr 5025: &Reply($client, "ok\n", $userinput);
5026: } else {
5027: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5028: "while attempting idput\n", $userinput);
5029: }
5030: } else {
5031: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5032: "while attempting idput\n", $userinput);
5033: }
5034:
5035: return 1;
5036: }
1.263 albertel 5037: ®ister_handler("idput", \&put_id_handler, 0, 1, 0);
1.238 foxr 5038:
5039: #
5040: # Retrieves a set of id values from the id database.
5041: # Returns an & separated list of results, one for each requested id to the
5042: # client.
5043: #
5044: # Parameters:
5045: # $cmd - Command keyword that caused us to be dispatched.
5046: # $tail - Tail of the command. Consists of a colon separated:
5047: # domain - the domain whose id table we dump
5048: # ids Consists of an & separated list of
5049: # id keywords whose values will be fetched.
5050: # nonexisting keywords will have an empty value.
5051: # $client - Socket open on the client.
5052: #
5053: # Returns:
5054: # 1 - indicating processing should continue.
5055: # Side effects:
5056: # An & separated list of results is written to $client.
5057: #
5058: sub get_id_handler {
5059: my ($cmd, $tail, $client) = @_;
5060:
5061:
5062: my $userinput = "$client:$tail";
5063:
5064: my ($udom,$what)=split(/:/,$tail);
5065: chomp($what);
5066: my @queries=split(/\&/,$what);
5067: my $qresult='';
5068: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
5069: if ($hashref) {
5070: for (my $i=0;$i<=$#queries;$i++) {
5071: $qresult.="$hashref->{$queries[$i]}&";
5072: }
1.311 albertel 5073: if (&untie_domain_hash($hashref)) {
1.238 foxr 5074: $qresult=~s/\&$//;
1.387 albertel 5075: &Reply($client, \$qresult, $userinput);
1.238 foxr 5076: } else {
5077: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
5078: "while attempting idget\n",$userinput);
5079: }
5080: } else {
5081: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5082: "while attempting idget\n",$userinput);
5083: }
5084:
5085: return 1;
5086: }
1.263 albertel 5087: ®ister_handler("idget", \&get_id_handler, 0, 1, 0);
1.238 foxr 5088:
1.489.2.7 raeburn 5089: # Deletes one or more ids in a domain's id database.
1.489.2.6 raeburn 5090: #
5091: # Parameters:
5092: # $cmd - Command keyword (iddel).
5093: # $tail - Command tail. In this case a colon
5094: # separated list containing:
5095: # The domain for which we are deleting the id(s).
5096: # &-separated list of id(s) to delete.
5097: # $client - File open on client socket.
5098: # Returns:
5099: # 1 - Continue processing
5100: # 0 - Exit server.
5101: #
5102: #
5103:
5104: sub del_id_handler {
5105: my ($cmd,$tail,$client) = @_;
5106:
5107: my $userinput = "$cmd:$tail";
5108:
5109: my ($udom,$what)=split(/:/,$tail);
5110: chomp($what);
5111: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
5112: "D", $what);
5113: if ($hashref) {
5114: my @keys=split(/\&/,$what);
5115: foreach my $key (@keys) {
5116: delete($hashref->{$key});
5117: }
5118: if (&untie_user_hash($hashref)) {
5119: &Reply($client, "ok\n", $userinput);
5120: } else {
5121: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5122: "while attempting iddel\n", $userinput);
5123: }
5124: } else {
5125: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5126: "while attempting iddel\n", $userinput);
5127: }
5128: return 1;
5129: }
5130: ®ister_handler("iddel", \&del_id_handler, 0, 1, 0);
5131:
1.238 foxr 5132: #
1.299 raeburn 5133: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database
5134: #
5135: # Parameters
5136: # $cmd - Command keyword that caused us to be dispatched.
5137: # $tail - Tail of the command. Consists of a colon separated:
5138: # domain - the domain whose dcmail we are recording
5139: # email Consists of key=value pair
5140: # where key is unique msgid
5141: # and value is message (in XML)
5142: # $client - Socket open on the client.
5143: #
5144: # Returns:
5145: # 1 - indicating processing should continue.
5146: # Side effects
5147: # reply is written to $client.
5148: #
5149: sub put_dcmail_handler {
5150: my ($cmd,$tail,$client) = @_;
5151: my $userinput = "$cmd:$tail";
1.463 foxr 5152:
5153:
1.299 raeburn 5154: my ($udom,$what)=split(/:/,$tail);
5155: chomp($what);
5156: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
5157: if ($hashref) {
5158: my ($key,$value)=split(/=/,$what);
5159: $hashref->{$key}=$value;
5160: }
1.311 albertel 5161: if (&untie_domain_hash($hashref)) {
1.299 raeburn 5162: &Reply($client, "ok\n", $userinput);
5163: } else {
5164: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5165: "while attempting dcmailput\n", $userinput);
5166: }
5167: return 1;
5168: }
5169: ®ister_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
5170:
5171: #
5172: # Retrieves broadcast e-mail from nohist_dcmail database
5173: # Returns to client an & separated list of key=value pairs,
5174: # where key is msgid and value is message information.
5175: #
5176: # Parameters
5177: # $cmd - Command keyword that caused us to be dispatched.
5178: # $tail - Tail of the command. Consists of a colon separated:
5179: # domain - the domain whose dcmail table we dump
5180: # startfilter - beginning of time window
5181: # endfilter - end of time window
5182: # sendersfilter - & separated list of username:domain
5183: # for senders to search for.
5184: # $client - Socket open on the client.
5185: #
5186: # Returns:
5187: # 1 - indicating processing should continue.
5188: # Side effects
5189: # reply (& separated list of msgid=messageinfo pairs) is
5190: # written to $client.
5191: #
5192: sub dump_dcmail_handler {
5193: my ($cmd, $tail, $client) = @_;
5194:
5195: my $userinput = "$cmd:$tail";
5196: my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
5197: chomp($sendersfilter);
5198: my @senders = ();
5199: if (defined($startfilter)) {
5200: $startfilter=&unescape($startfilter);
5201: } else {
5202: $startfilter='.';
5203: }
5204: if (defined($endfilter)) {
5205: $endfilter=&unescape($endfilter);
5206: } else {
5207: $endfilter='.';
5208: }
5209: if (defined($sendersfilter)) {
5210: $sendersfilter=&unescape($sendersfilter);
1.300 albertel 5211: @senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299 raeburn 5212: }
5213:
5214: my $qresult='';
5215: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
5216: if ($hashref) {
5217: while (my ($key,$value) = each(%$hashref)) {
5218: my $match = 1;
1.303 albertel 5219: my ($timestamp,$subj,$uname,$udom) =
5220: split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299 raeburn 5221: $subj = &unescape($subj);
5222: unless ($startfilter eq '.' || !defined($startfilter)) {
5223: if ($timestamp < $startfilter) {
5224: $match = 0;
5225: }
5226: }
5227: unless ($endfilter eq '.' || !defined($endfilter)) {
5228: if ($timestamp > $endfilter) {
5229: $match = 0;
5230: }
5231: }
5232: unless (@senders < 1) {
5233: unless (grep/^$uname:$udom$/,@senders) {
5234: $match = 0;
5235: }
5236: }
5237: if ($match == 1) {
5238: $qresult.=$key.'='.$value.'&';
5239: }
5240: }
1.311 albertel 5241: if (&untie_domain_hash($hashref)) {
1.299 raeburn 5242: chop($qresult);
1.387 albertel 5243: &Reply($client, \$qresult, $userinput);
1.299 raeburn 5244: } else {
5245: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5246: "while attempting dcmaildump\n", $userinput);
5247: }
5248: } else {
5249: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5250: "while attempting dcmaildump\n", $userinput);
5251: }
5252: return 1;
5253: }
5254:
5255: ®ister_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
5256:
5257: #
5258: # Puts domain roles in nohist_domainroles database
5259: #
5260: # Parameters
5261: # $cmd - Command keyword that caused us to be dispatched.
5262: # $tail - Tail of the command. Consists of a colon separated:
5263: # domain - the domain whose roles we are recording
5264: # role - Consists of key=value pair
5265: # where key is unique role
5266: # and value is start/end date information
5267: # $client - Socket open on the client.
5268: #
5269: # Returns:
5270: # 1 - indicating processing should continue.
5271: # Side effects
5272: # reply is written to $client.
5273: #
5274:
5275: sub put_domainroles_handler {
5276: my ($cmd,$tail,$client) = @_;
5277:
5278: my $userinput = "$cmd:$tail";
5279: my ($udom,$what)=split(/:/,$tail);
5280: chomp($what);
5281: my @pairs=split(/\&/,$what);
5282: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
5283: if ($hashref) {
5284: foreach my $pair (@pairs) {
5285: my ($key,$value)=split(/=/,$pair);
5286: $hashref->{$key}=$value;
5287: }
1.311 albertel 5288: if (&untie_domain_hash($hashref)) {
1.299 raeburn 5289: &Reply($client, "ok\n", $userinput);
5290: } else {
5291: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5292: "while attempting domroleput\n", $userinput);
5293: }
5294: } else {
5295: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5296: "while attempting domroleput\n", $userinput);
5297: }
5298:
5299: return 1;
5300: }
5301:
5302: ®ister_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
5303:
5304: #
5305: # Retrieves domain roles from nohist_domainroles database
5306: # Returns to client an & separated list of key=value pairs,
5307: # where key is role and value is start and end date information.
5308: #
5309: # Parameters
5310: # $cmd - Command keyword that caused us to be dispatched.
5311: # $tail - Tail of the command. Consists of a colon separated:
5312: # domain - the domain whose domain roles table we dump
5313: # $client - Socket open on the client.
5314: #
5315: # Returns:
5316: # 1 - indicating processing should continue.
5317: # Side effects
5318: # reply (& separated list of role=start/end info pairs) is
5319: # written to $client.
5320: #
5321: sub dump_domainroles_handler {
5322: my ($cmd, $tail, $client) = @_;
5323:
5324: my $userinput = "$cmd:$tail";
5325: my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
5326: chomp($rolesfilter);
5327: my @roles = ();
5328: if (defined($startfilter)) {
5329: $startfilter=&unescape($startfilter);
5330: } else {
5331: $startfilter='.';
5332: }
5333: if (defined($endfilter)) {
5334: $endfilter=&unescape($endfilter);
5335: } else {
5336: $endfilter='.';
5337: }
5338: if (defined($rolesfilter)) {
5339: $rolesfilter=&unescape($rolesfilter);
1.300 albertel 5340: @roles = split(/\&/,$rolesfilter);
1.299 raeburn 5341: }
1.421 raeburn 5342:
1.299 raeburn 5343: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
5344: if ($hashref) {
5345: my $qresult = '';
5346: while (my ($key,$value) = each(%$hashref)) {
5347: my $match = 1;
1.421 raeburn 5348: my ($end,$start) = split(/:/,&unescape($value));
1.299 raeburn 5349: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421 raeburn 5350: unless (@roles < 1) {
5351: unless (grep/^\Q$trole\E$/,@roles) {
5352: $match = 0;
5353: next;
5354: }
5355: }
1.299 raeburn 5356: unless ($startfilter eq '.' || !defined($startfilter)) {
1.415 raeburn 5357: if ((defined($start)) && ($start >= $startfilter)) {
1.299 raeburn 5358: $match = 0;
1.421 raeburn 5359: next;
1.299 raeburn 5360: }
5361: }
5362: unless ($endfilter eq '.' || !defined($endfilter)) {
1.421 raeburn 5363: if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299 raeburn 5364: $match = 0;
1.421 raeburn 5365: next;
1.299 raeburn 5366: }
5367: }
5368: if ($match == 1) {
5369: $qresult.=$key.'='.$value.'&';
5370: }
5371: }
1.311 albertel 5372: if (&untie_domain_hash($hashref)) {
1.299 raeburn 5373: chop($qresult);
1.387 albertel 5374: &Reply($client, \$qresult, $userinput);
1.299 raeburn 5375: } else {
5376: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5377: "while attempting domrolesdump\n", $userinput);
5378: }
5379: } else {
5380: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5381: "while attempting domrolesdump\n", $userinput);
5382: }
5383: return 1;
5384: }
5385:
5386: ®ister_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
5387:
5388:
1.238 foxr 5389: # Process the tmpput command I'm not sure what this does.. Seems to
5390: # create a file in the lonDaemons/tmp directory of the form $id.tmp
5391: # where Id is the client's ip concatenated with a sequence number.
5392: # The file will contain some value that is passed in. Is this e.g.
5393: # a login token?
5394: #
5395: # Parameters:
5396: # $cmd - The command that got us dispatched.
5397: # $tail - The remainder of the request following $cmd:
5398: # In this case this will be the contents of the file.
5399: # $client - Socket connected to the client.
5400: # Returns:
5401: # 1 indicating processing can continue.
5402: # Side effects:
5403: # A file is created in the local filesystem.
5404: # A reply is sent to the client.
5405: sub tmp_put_handler {
5406: my ($cmd, $what, $client) = @_;
5407:
5408: my $userinput = "$cmd:$what"; # Reconstruct for logging.
5409:
1.347 raeburn 5410: my ($record,$context) = split(/:/,$what);
5411: if ($context ne '') {
5412: chomp($context);
5413: $context = &unescape($context);
5414: }
5415: my ($id,$store);
1.238 foxr 5416: $tmpsnum++;
1.489.2.42 raeburn 5417: my $numtries = 0;
5418: my $execdir=$perlvar{'lonDaemons'};
5419: if (($context eq 'resetpw') || ($context eq 'createaccount') ||
5420: ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
5421: $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
5422: while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
5423: undef($id);
5424: $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
5425: $numtries ++;
5426: }
1.347 raeburn 5427: } else {
5428: $id = $$.'_'.$clientip.'_'.$tmpsnum;
5429: }
1.238 foxr 5430: $id=~s/\W/\_/g;
1.347 raeburn 5431: $record=~s/\n//g;
1.489.2.42 raeburn 5432: if (($id ne '') &&
5433: ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
1.347 raeburn 5434: print $store $record;
1.238 foxr 5435: close $store;
1.387 albertel 5436: &Reply($client, \$id, $userinput);
1.238 foxr 5437: } else {
5438: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
5439: "while attempting tmpput\n", $userinput);
5440: }
5441: return 1;
5442:
5443: }
5444: ®ister_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263 albertel 5445:
1.238 foxr 5446: # Processes the tmpget command. This command returns the contents
5447: # of a temporary resource file(?) created via tmpput.
5448: #
5449: # Paramters:
5450: # $cmd - Command that got us dispatched.
5451: # $id - Tail of the command, contain the id of the resource
5452: # we want to fetch.
5453: # $client - socket open on the client.
5454: # Return:
5455: # 1 - Inidcating processing can continue.
5456: # Side effects:
5457: # A reply is sent to the client.
5458: #
5459: sub tmp_get_handler {
5460: my ($cmd, $id, $client) = @_;
5461:
5462: my $userinput = "$cmd:$id";
5463:
5464:
5465: $id=~s/\W/\_/g;
5466: my $store;
5467: my $execdir=$perlvar{'lonDaemons'};
5468: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
5469: my $reply=<$store>;
1.387 albertel 5470: &Reply( $client, \$reply, $userinput);
1.238 foxr 5471: close $store;
5472: } else {
5473: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
5474: "while attempting tmpget\n", $userinput);
5475: }
5476:
5477: return 1;
5478: }
5479: ®ister_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263 albertel 5480:
1.238 foxr 5481: #
5482: # Process the tmpdel command. This command deletes a temp resource
5483: # created by the tmpput command.
5484: #
5485: # Parameters:
5486: # $cmd - Command that got us here.
5487: # $id - Id of the temporary resource created.
5488: # $client - socket open on the client process.
5489: #
5490: # Returns:
5491: # 1 - Indicating processing should continue.
5492: # Side Effects:
5493: # A file is deleted
5494: # A reply is sent to the client.
5495: sub tmp_del_handler {
5496: my ($cmd, $id, $client) = @_;
5497:
5498: my $userinput= "$cmd:$id";
5499:
5500: chomp($id);
5501: $id=~s/\W/\_/g;
5502: my $execdir=$perlvar{'lonDaemons'};
5503: if (unlink("$execdir/tmp/$id.tmp")) {
5504: &Reply($client, "ok\n", $userinput);
5505: } else {
5506: &Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
5507: "while attempting tmpdel\n", $userinput);
5508: }
5509:
5510: return 1;
5511:
5512: }
5513: ®ister_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263 albertel 5514:
1.238 foxr 5515: #
1.489.2.39 raeburn 5516: # Process the updatebalcookie command. This command updates a
5517: # cookie in the lonBalancedir directory on a load balancer node.
5518: #
5519: # Parameters:
5520: # $cmd - Command that got us here.
5521: # $tail - Tail of the request (escaped cookie: escaped current entry)
5522: #
5523: # $client - socket open on the client process.
5524: #
5525: # Returns:
5526: # 1 - Indicating processing should continue.
5527: # Side Effects:
5528: # A cookie file is updated from the lonBalancedir directory
5529: # A reply is sent to the client.
5530: #
5531: sub update_balcookie_handler {
5532: my ($cmd, $tail, $client) = @_;
5533:
5534: my $userinput= "$cmd:$tail";
5535: chomp($tail);
5536: my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
5537:
5538: my $updatedone;
5539: if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
5540: my $execdir=$perlvar{'lonBalanceDir'};
5541: if (-e "$execdir/$cookie.id") {
5542: my $doupdate;
5543: if (open(my $fh,'<',"$execdir/$cookie.id")) {
5544: while (my $line = <$fh>) {
5545: chomp($line);
5546: if ($line eq $lastentry) {
5547: $doupdate = 1;
5548: last;
5549: }
5550: }
5551: close($fh);
5552: }
5553: if ($doupdate) {
5554: if (open(my $fh,'>',"$execdir/$cookie.id")) {
5555: print $fh $clientname;
5556: close($fh);
5557: $updatedone = 1;
5558: }
5559: }
5560: }
5561: }
5562: if ($updatedone) {
5563: &Reply($client, "ok\n", $userinput);
5564: } else {
5565: &Failure( $client, "error: ".($!+0)."file update failed ".
5566: "while attempting updatebalcookie\n", $userinput);
5567: }
5568: return 1;
5569: }
5570: ®ister_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
5571:
5572: #
1.489.2.32 raeburn 5573: # Process the delbalcookie command. This command deletes a balancer
1.489.2.39 raeburn 5574: # cookie in the lonBalancedir directory on a load balancer node.
1.489.2.32 raeburn 5575: #
5576: # Parameters:
5577: # $cmd - Command that got us here.
5578: # $cookie - Cookie to be deleted.
5579: # $client - socket open on the client process.
5580: #
5581: # Returns:
5582: # 1 - Indicating processing should continue.
5583: # Side Effects:
5584: # A cookie file is deleted from the lonBalancedir directory
5585: # A reply is sent to the client.
5586: sub del_balcookie_handler {
5587: my ($cmd, $cookie, $client) = @_;
5588:
5589: my $userinput= "$cmd:$cookie";
5590:
5591: chomp($cookie);
1.489.2.39 raeburn 5592: $cookie = &unescape($cookie);
1.489.2.32 raeburn 5593: my $deleted = '';
5594: if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
5595: my $execdir=$perlvar{'lonBalanceDir'};
5596: if (-e "$execdir/$cookie.id") {
5597: if (open(my $fh,'<',"$execdir/$cookie.id")) {
5598: my $dodelete;
5599: while (my $line = <$fh>) {
5600: chomp($line);
5601: if ($line eq $clientname) {
5602: $dodelete = 1;
5603: last;
5604: }
5605: }
5606: close($fh);
5607: if ($dodelete) {
5608: if (unlink("$execdir/$cookie.id")) {
5609: $deleted = 1;
5610: }
5611: }
5612: }
5613: }
5614: }
5615: if ($deleted) {
5616: &Reply($client, "ok\n", $userinput);
5617: } else {
5618: &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
5619: "while attempting delbalcookie\n", $userinput);
5620: }
5621: return 1;
5622: }
5623: ®ister_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
5624:
5625: #
1.246 foxr 5626: # Processes the setannounce command. This command
5627: # creates a file named announce.txt in the top directory of
5628: # the documentn root and sets its contents. The announce.txt file is
5629: # printed in its entirety at the LonCAPA login page. Note:
5630: # once the announcement.txt fileis created it cannot be deleted.
5631: # However, setting the contents of the file to empty removes the
5632: # announcement from the login page of loncapa so who cares.
5633: #
5634: # Parameters:
5635: # $cmd - The command that got us dispatched.
5636: # $announcement - The text of the announcement.
5637: # $client - Socket open on the client process.
5638: # Retunrns:
5639: # 1 - Indicating request processing should continue
5640: # Side Effects:
5641: # The file {DocRoot}/announcement.txt is created.
5642: # A reply is sent to $client.
5643: #
5644: sub set_announce_handler {
5645: my ($cmd, $announcement, $client) = @_;
5646:
5647: my $userinput = "$cmd:$announcement";
5648:
5649: chomp($announcement);
5650: $announcement=&unescape($announcement);
5651: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
5652: '/announcement.txt')) {
5653: print $store $announcement;
5654: close $store;
5655: &Reply($client, "ok\n", $userinput);
5656: } else {
5657: &Failure($client, "error: ".($!+0)."\n", $userinput);
5658: }
5659:
5660: return 1;
5661: }
5662: ®ister_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263 albertel 5663:
1.246 foxr 5664: #
5665: # Return the version of the daemon. This can be used to determine
5666: # the compatibility of cross version installations or, alternatively to
5667: # simply know who's out of date and who isn't. Note that the version
5668: # is returned concatenated with the tail.
5669: # Parameters:
5670: # $cmd - the request that dispatched to us.
5671: # $tail - Tail of the request (client's version?).
5672: # $client - Socket open on the client.
5673: #Returns:
5674: # 1 - continue processing requests.
5675: # Side Effects:
5676: # Replies with version to $client.
5677: sub get_version_handler {
5678: my ($cmd, $tail, $client) = @_;
5679:
5680: my $userinput = $cmd.$tail;
5681:
5682: &Reply($client, &version($userinput)."\n", $userinput);
5683:
5684:
5685: return 1;
5686: }
5687: ®ister_handler("version", \&get_version_handler, 0, 1, 0);
1.263 albertel 5688:
1.246 foxr 5689: # Set the current host and domain. This is used to support
5690: # multihomed systems. Each IP of the system, or even separate daemons
5691: # on the same IP can be treated as handling a separate lonCAPA virtual
5692: # machine. This command selects the virtual lonCAPA. The client always
5693: # knows the right one since it is lonc and it is selecting the domain/system
5694: # from the hosts.tab file.
5695: # Parameters:
5696: # $cmd - Command that dispatched us.
5697: # $tail - Tail of the command (domain/host requested).
5698: # $socket - Socket open on the client.
5699: #
5700: # Returns:
5701: # 1 - Indicates the program should continue to process requests.
5702: # Side-effects:
5703: # The default domain/system context is modified for this daemon.
5704: # a reply is sent to the client.
5705: #
5706: sub set_virtual_host_handler {
5707: my ($cmd, $tail, $socket) = @_;
5708:
5709: my $userinput ="$cmd:$tail";
5710:
5711: &Reply($client, &sethost($userinput)."\n", $userinput);
5712:
5713:
5714: return 1;
5715: }
1.247 albertel 5716: ®ister_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246 foxr 5717:
5718: # Process a request to exit:
5719: # - "bye" is sent to the client.
5720: # - The client socket is shutdown and closed.
5721: # - We indicate to the caller that we should exit.
5722: # Formal Parameters:
5723: # $cmd - The command that got us here.
5724: # $tail - Tail of the command (empty).
5725: # $client - Socket open on the tail.
5726: # Returns:
5727: # 0 - Indicating the program should exit!!
5728: #
5729: sub exit_handler {
5730: my ($cmd, $tail, $client) = @_;
5731:
5732: my $userinput = "$cmd:$tail";
5733:
5734: &logthis("Client $clientip ($clientname) hanging up: $userinput");
5735: &Reply($client, "bye\n", $userinput);
5736: $client->shutdown(2); # shutdown the socket forcibly.
5737: $client->close();
5738:
5739: return 0;
5740: }
1.248 foxr 5741: ®ister_handler("exit", \&exit_handler, 0,1,1);
5742: ®ister_handler("init", \&exit_handler, 0,1,1);
5743: ®ister_handler("quit", \&exit_handler, 0,1,1);
5744:
5745: # Determine if auto-enrollment is enabled.
5746: # Note that the original had what I believe to be a defect.
5747: # The original returned 0 if the requestor was not a registerd client.
5748: # It should return "refused".
5749: # Formal Parameters:
5750: # $cmd - The command that invoked us.
5751: # $tail - The tail of the command (Extra command parameters.
5752: # $client - The socket open on the client that issued the request.
5753: # Returns:
5754: # 1 - Indicating processing should continue.
5755: #
5756: sub enrollment_enabled_handler {
5757: my ($cmd, $tail, $client) = @_;
5758: my $userinput = $cmd.":".$tail; # For logging purposes.
5759:
1.337 albertel 5760: my ($cdom) = split(/:/, $tail, 2); # Domain we're asking about.
1.489.2.43.2. 2(raebur 5761:5): my $outcome;
5762:5): eval {
5763:5): local($SIG{__DIE__})='DEFAULT';
5764:5): $outcome = &localenroll::run($cdom);
5765:5): };
1.387 albertel 5766: &Reply($client, \$outcome, $userinput);
1.248 foxr 5767: return 1;
5768: }
5769: ®ister_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
5770:
1.417 raeburn 5771: #
1.423 raeburn 5772: # Validate an institutional code used for a LON-CAPA course.
1.417 raeburn 5773: #
5774: # Formal Parameters:
5775: # $cmd - The command request that got us dispatched.
5776: # $tail - The tail of the command. In this case,
5777: # this is a colon separated set of words that will be split
5778: # into:
1.424 raeburn 5779: # $dom - The domain for which the check of
5780: # institutional course code will occur.
5781: #
5782: # $instcode - The institutional code for the course
5783: # being requested, or validated for rights
5784: # to request.
5785: #
5786: # $owner - The course requestor (who will be the
5787: # course owner, in the form username:domain
5788: #
1.417 raeburn 5789: # $client - Socket open on the client.
5790: # Returns:
5791: # 1 - Indicating processing should continue.
5792: #
5793: sub validate_instcode_handler {
5794: my ($cmd, $tail, $client) = @_;
5795: my $userinput = "$cmd:$tail";
1.423 raeburn 5796: my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422 raeburn 5797: $instcode = &unescape($instcode);
5798: $owner = &unescape($owner);
1.489.2.43.2. 2(raebur 5799:5): my ($outcome,$description,$credits);
5800:5): eval {
5801:5): local($SIG{__DIE__})='DEFAULT';
5802:5): ($outcome,$description,$credits) =
5803:5): &localenroll::validate_instcode($dom,$instcode,$owner);
5804:5): };
1.489.2.3 raeburn 5805: my $result = &escape($outcome).'&'.&escape($description).'&'.
5806: &escape($credits);
1.426 raeburn 5807: &Reply($client, \$result, $userinput);
1.417 raeburn 5808:
5809: return 1;
5810: }
5811: ®ister_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
5812:
1.489.2.41 raeburn 5813: #
5814: # Validate co-owner for cross-listed institutional code and
5815: # institutional course code itself used for a LON-CAPA course.
5816: #
5817: # Formal Parameters:
5818: # $cmd - The command request that got us dispatched.
5819: # $tail - The tail of the command. In this case,
5820: # this is a colon separated string containing:
5821: # $dom - Course's LON-CAPA domain
5822: # $instcode - Institutional course code for the course
5823: # $inst_xlist - Institutional course Id for the crosslisting
5824: # $coowner - Username of co-owner
5825: # (values for all but $dom have been escaped).
5826: #
5827: # $client - Socket open on the client.
5828: # Returns:
5829: # 1 - Indicating processing should continue.
5830: #
5831: sub validate_instcrosslist_handler {
5832: my ($cmd, $tail, $client) = @_;
5833: my $userinput = "$cmd:$tail";
5834: my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
5835: $instcode = &unescape($instcode);
5836: $inst_xlist = &unescape($inst_xlist);
5837: $coowner = &unescape($coowner);
1.489.2.43.2. 2(raebur 5838:5): my $outcome;
5839:5): eval {
5840:5): local($SIG{__DIE__})='DEFAULT';
5841:5): $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
5842:5): $inst_xlist,$coowner);
5843:5): };
1.489.2.41 raeburn 5844:
1.489.2.43.2. 2(raebur 5845:5): &Reply($client, \$outcome, $userinput);
1.489.2.41 raeburn 5846: return 1;
5847: }
5848: ®ister_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
5849:
1.248 foxr 5850: # Get the official sections for which auto-enrollment is possible.
5851: # Since the admin people won't know about 'unofficial sections'
5852: # we cannot auto-enroll on them.
5853: # Formal Parameters:
5854: # $cmd - The command request that got us dispatched here.
5855: # $tail - The remainder of the request. In our case this
5856: # will be split into:
5857: # $coursecode - The course name from the admin point of view.
5858: # $cdom - The course's domain(?).
5859: # $client - Socket open on the client.
5860: # Returns:
5861: # 1 - Indiciting processing should continue.
5862: #
5863: sub get_sections_handler {
5864: my ($cmd, $tail, $client) = @_;
5865: my $userinput = "$cmd:$tail";
5866:
5867: my ($coursecode, $cdom) = split(/:/, $tail);
1.489.2.43.2. 2(raebur 5868:5): my $seclist;
5869:5): eval {
5870:5): local($SIG{__DIE__})='DEFAULT';
5871:5): my @secs = &localenroll::get_sections($coursecode,$cdom);
5872:5): $seclist = &escape(join(':',@secs));
5873:5): };
1.387 albertel 5874: &Reply($client, \$seclist, $userinput);
1.248 foxr 5875: return 1;
5876: }
5877: ®ister_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
5878:
5879: # Validate the owner of a new course section.
5880: #
5881: # Formal Parameters:
5882: # $cmd - Command that got us dispatched.
5883: # $tail - the remainder of the command. For us this consists of a
5884: # colon separated string containing:
5885: # $inst - Course Id from the institutions point of view.
5886: # $owner - Proposed owner of the course.
5887: # $cdom - Domain of the course (from the institutions
5888: # point of view?)..
5889: # $client - Socket open on the client.
5890: #
5891: # Returns:
5892: # 1 - Processing should continue.
5893: #
1.489.2.43.2. 2(raebur 5894:5):
1.248 foxr 5895: sub validate_course_owner_handler {
5896: my ($cmd, $tail, $client) = @_;
5897: my $userinput = "$cmd:$tail";
1.470 raeburn 5898: my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
5899:
1.336 raeburn 5900: $owner = &unescape($owner);
1.470 raeburn 5901: $coowners = &unescape($coowners);
1.489.2.43.2. 2(raebur 5902:5): my $outcome;
5903:5): eval {
5904:5): local($SIG{__DIE__})='DEFAULT';
5905:5): $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
5906:5): };
1.387 albertel 5907: &Reply($client, \$outcome, $userinput);
1.248 foxr 5908: return 1;
5909: }
5910: ®ister_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263 albertel 5911:
1.248 foxr 5912: #
5913: # Validate a course section in the official schedule of classes
5914: # from the institutions point of view (part of autoenrollment).
5915: #
5916: # Formal Parameters:
5917: # $cmd - The command request that got us dispatched.
5918: # $tail - The tail of the command. In this case,
5919: # this is a colon separated set of words that will be split
5920: # into:
5921: # $inst_course_id - The course/section id from the
5922: # institutions point of view.
5923: # $cdom - The domain from the institutions
5924: # point of view.
5925: # $client - Socket open on the client.
5926: # Returns:
5927: # 1 - Indicating processing should continue.
5928: #
5929: sub validate_course_section_handler {
5930: my ($cmd, $tail, $client) = @_;
5931: my $userinput = "$cmd:$tail";
5932: my ($inst_course_id, $cdom) = split(/:/, $tail);
1.489.2.43.2. 2(raebur 5933:5): my $outcome;
5934:5): eval {
5935:5): local($SIG{__DIE__})='DEFAULT';
5936:5): $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
5937:5): };
1.387 albertel 5938: &Reply($client, \$outcome, $userinput);
1.248 foxr 5939: return 1;
5940: }
5941: ®ister_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
5942:
5943: #
1.340 raeburn 5944: # Validate course owner's access to enrollment data for specific class section.
5945: #
5946: #
5947: # Formal Parameters:
5948: # $cmd - The command request that got us dispatched.
5949: # $tail - The tail of the command. In this case this is a colon separated
1.489.2.29 raeburn 5950: # set of values that will be split into:
1.340 raeburn 5951: # $inst_class - Institutional code for the specific class section
1.489.2.29 raeburn 5952: # $ownerlist - An escaped comma-separated list of username:domain
5953: # of the course owner, and co-owner(s).
1.340 raeburn 5954: # $cdom - The domain of the course from the institution's
5955: # point of view.
5956: # $client - The socket open on the client.
5957: # Returns:
5958: # 1 - continue processing.
5959: #
5960:
5961: sub validate_class_access_handler {
5962: my ($cmd, $tail, $client) = @_;
5963: my $userinput = "$cmd:$tail";
1.383 raeburn 5964: my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392 raeburn 5965: my $owners = &unescape($ownerlist);
1.341 albertel 5966: my $outcome;
5967: eval {
5968: local($SIG{__DIE__})='DEFAULT';
1.392 raeburn 5969: $outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341 albertel 5970: };
1.387 albertel 5971: &Reply($client,\$outcome, $userinput);
1.340 raeburn 5972: return 1;
5973: }
5974: ®ister_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
5975:
5976: #
1.489.2.41 raeburn 5977: # Modify institutional sections (using customized &instsec_reformat()
5978: # routine in localenroll.pm), to either clutter or declutter, for
5979: # purposes of ensuring an institutional course section (string) can
5980: # be unambiguously separated into institutional course and section.
5981: #
5982: # Formal Parameters:
5983: # $cmd - The command request that got us dispatched.
5984: # $tail - The tail of the command. In this case this is a colon separated
5985: # set of values that will be split into:
5986: # $cdom - The LON-CAPA domain of the course.
5987: # $action - Either: clutter or declutter
5988: # clutter adds character(s) to eliminate ambiguity
5989: # declutter removes the added characters (e.g., for
5990: # display of the institutional course section string.
5991: # $info - A frozen hash in which keys are:
5992: # LON-CAPA course number:Institutional course code
5993: # and values are a reference to an array of the
5994: # items to modify -- either institutional sections,
5995: # or institutional course sections (for crosslistings).
5996: # $client - The socket open on the client.
5997: # Returns:
5998: # 1 - continue processing.
5999: #
6000:
6001: sub instsec_reformat_handler {
6002: my ($cmd, $tail, $client) = @_;
6003: my $userinput = "$cmd:$tail";
6004: my ($cdom,$action,$info) = split(/:/,$tail);
6005: my $instsecref = &Apache::lonnet::thaw_unescape($info);
6006: my ($outcome,$result);
6007: eval {
6008: local($SIG{__DIE__})='DEFAULT';
6009: $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
6010: if ($outcome eq 'ok') {
6011: if (ref($instsecref) eq 'HASH') {
6012: foreach my $key (keys(%{$instsecref})) {
6013: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
6014: }
6015: $result =~ s/\&$//;
6016: }
6017: }
6018: };
6019: if (!$@) {
6020: if ($outcome eq 'ok') {
6021: &Reply( $client, \$result, $userinput);
6022: } else {
6023: &Reply($client,\$outcome, $userinput);
6024: }
6025: } else {
6026: &Failure($client,"unknown_cmd\n",$userinput);
6027: }
6028: return 1;
6029: }
6030: ®ister_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
6031:
6032: #
1.489.2.29 raeburn 6033: # Validate course owner or co-owners(s) access to enrollment data for all sections
6034: # and crosslistings for a particular course.
6035: #
6036: #
6037: # Formal Parameters:
6038: # $cmd - The command request that got us dispatched.
6039: # $tail - The tail of the command. In this case this is a colon separated
6040: # set of values that will be split into:
6041: # $ownerlist - An escaped comma-separated list of username:domain
6042: # of the course owner, and co-owner(s).
6043: # $cdom - The domain of the course from the institution's
6044: # point of view.
6045: # $classes - Frozen hash of institutional course sections and
6046: # crosslistings.
6047: # $client - The socket open on the client.
6048: # Returns:
6049: # 1 - continue processing.
6050: #
6051:
6052: sub validate_classes_handler {
6053: my ($cmd, $tail, $client) = @_;
6054: my $userinput = "$cmd:$tail";
6055: my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
6056: my $classesref = &Apache::lonnet::thaw_unescape($classes);
6057: my $owners = &unescape($ownerlist);
6058: my $result;
6059: eval {
6060: local($SIG{__DIE__})='DEFAULT';
6061: my %validations;
6062: my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
6063: \%validations);
6064: if ($response eq 'ok') {
6065: foreach my $key (keys(%validations)) {
6066: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
6067: }
6068: $result =~ s/\&$//;
6069: } else {
6070: $result = 'error';
6071: }
6072: };
6073: if (!$@) {
6074: &Reply($client, \$result, $userinput);
6075: } else {
6076: &Failure($client,"unknown_cmd\n",$userinput);
6077: }
6078: return 1;
6079: }
6080: ®ister_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
6081:
6082: #
1.340 raeburn 6083: # Create a password for a new LON-CAPA user added by auto-enrollment.
6084: # Only used for case where authentication method for new user is localauth
1.248 foxr 6085: #
6086: # Formal Parameters:
6087: # $cmd - The command request that got us dispatched.
6088: # $tail - The tail of the command. In this case this is a colon separated
6089: # set of words that will be split into:
1.340 raeburn 6090: # $authparam - An authentication parameter (localauth parameter).
1.248 foxr 6091: # $cdom - The domain of the course from the institution's
6092: # point of view.
6093: # $client - The socket open on the client.
6094: # Returns:
6095: # 1 - continue processing.
6096: #
6097: sub create_auto_enroll_password_handler {
6098: my ($cmd, $tail, $client) = @_;
6099: my $userinput = "$cmd:$tail";
6100:
6101: my ($authparam, $cdom) = split(/:/, $userinput);
6102:
6103: my ($create_passwd,$authchk);
1.489.2.43.2. 2(raebur 6104:5): eval {
6105:5): local($SIG{__DIE__})='DEFAULT';
6106:5): ($authparam,$create_passwd,$create_passwd,$authchk) =
6107:5): &localenroll::create_password($authparam,$cdom);
6108:5): };
1.248 foxr 6109: &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
6110: $userinput);
6111:
6112:
6113: return 1;
6114: }
6115: ®ister_handler("autocreatepassword", \&create_auto_enroll_password_handler,
6116: 0, 1, 0);
6117:
1.489.2.22 raeburn 6118: sub auto_export_grades_handler {
6119: my ($cmd, $tail, $client) = @_;
6120: my $userinput = "$cmd:$tail";
6121: my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
6122: my $inforef = &Apache::lonnet::thaw_unescape($info);
6123: my $dataref = &Apache::lonnet::thaw_unescape($data);
6124: my ($outcome,$result);;
6125: eval {
6126: local($SIG{__DIE__})='DEFAULT';
6127: my %rtnhash;
6128: $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
6129: if ($outcome eq 'ok') {
6130: foreach my $key (keys(%rtnhash)) {
6131: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
6132: }
6133: $result =~ s/\&$//;
6134: }
6135: };
6136: if (!$@) {
6137: if ($outcome eq 'ok') {
6138: if ($cipher) {
6139: my $cmdlength=length($result);
6140: $result.=" ";
6141: my $encresult='';
6142: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
6143: $encresult.= unpack("H16",
6144: $cipher->encrypt(substr($result,
6145: $encidx,
6146: 8)));
6147: }
6148: &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
6149: } else {
6150: &Failure( $client, "error:no_key\n", $userinput);
6151: }
6152: } else {
6153: &Reply($client, "$outcome\n", $userinput);
6154: }
6155: } else {
6156: &Failure($client,"export_error\n",$userinput);
6157: }
6158: return 1;
6159: }
6160: ®ister_handler("autoexportgrades", \&auto_export_grades_handler,
1.489.2.35 raeburn 6161: 1, 1, 0);
1.489.2.22 raeburn 6162:
6163:
1.248 foxr 6164: # Retrieve and remove temporary files created by/during autoenrollment.
6165: #
6166: # Formal Parameters:
6167: # $cmd - The command that got us dispatched.
6168: # $tail - The tail of the command. In our case this is a colon
6169: # separated list that will be split into:
1.489.2.24 raeburn 6170: # $filename - The name of the file to retrieve.
1.248 foxr 6171: # The filename is given as a path relative to
6172: # the LonCAPA temp file directory.
6173: # $client - Socket open on the client.
6174: #
6175: # Returns:
6176: # 1 - Continue processing.
6177: sub retrieve_auto_file_handler {
6178: my ($cmd, $tail, $client) = @_;
6179: my $userinput = "cmd:$tail";
6180:
6181: my ($filename) = split(/:/, $tail);
6182:
6183: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.489.2.20 raeburn 6184: if ($filename =~m{/\.\./}) {
6185: &Failure($client, "refused\n", $userinput);
1.489.2.24 raeburn 6186: } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
6187: &Failure($client, "refused\n", $userinput);
1.489.2.20 raeburn 6188: } elsif ( (-e $source) && ($filename ne '') ) {
1.248 foxr 6189: my $reply = '';
6190: if (open(my $fh,$source)) {
6191: while (<$fh>) {
6192: chomp($_);
6193: $_ =~ s/^\s+//g;
6194: $_ =~ s/\s+$//g;
6195: $reply .= $_;
6196: }
6197: close($fh);
6198: &Reply($client, &escape($reply)."\n", $userinput);
6199:
6200: # Does this have to be uncommented??!? (RF).
6201: #
6202: # unlink($source);
6203: } else {
6204: &Failure($client, "error\n", $userinput);
6205: }
6206: } else {
6207: &Failure($client, "error\n", $userinput);
6208: }
6209:
6210:
6211: return 1;
6212: }
6213: ®ister_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
6214:
1.423 raeburn 6215: sub crsreq_checks_handler {
6216: my ($cmd, $tail, $client) = @_;
6217: my $userinput = "$cmd:$tail";
6218: my $dom = $tail;
6219: my $result;
1.489.2.12 raeburn 6220: my @reqtypes = ('official','unofficial','community','textbook');
1.423 raeburn 6221: eval {
6222: local($SIG{__DIE__})='DEFAULT';
6223: my %validations;
1.424 raeburn 6224: my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
6225: \%validations);
1.423 raeburn 6226: if ($response eq 'ok') {
6227: foreach my $key (keys(%validations)) {
6228: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
6229: }
6230: $result =~ s/\&$//;
6231: } else {
6232: $result = 'error';
6233: }
6234: };
6235: if (!$@) {
6236: &Reply($client, \$result, $userinput);
6237: } else {
6238: &Failure($client,"unknown_cmd\n",$userinput);
6239: }
6240: return 1;
6241: }
6242: ®ister_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
6243:
6244: sub validate_crsreq_handler {
6245: my ($cmd, $tail, $client) = @_;
6246: my $userinput = "$cmd:$tail";
1.489.2.13 raeburn 6247: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423 raeburn 6248: $instcode = &unescape($instcode);
6249: $owner = &unescape($owner);
6250: $crstype = &unescape($crstype);
6251: $inststatuslist = &unescape($inststatuslist);
6252: $instcode = &unescape($instcode);
6253: $instseclist = &unescape($instseclist);
1.489.2.13 raeburn 6254: my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423 raeburn 6255: my $outcome;
6256: eval {
6257: local($SIG{__DIE__})='DEFAULT';
6258: $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
6259: $inststatuslist,$instcode,
1.489.2.13 raeburn 6260: $instseclist,$custominfo);
1.423 raeburn 6261: };
6262: if (!$@) {
6263: &Reply($client, \$outcome, $userinput);
6264: } else {
6265: &Failure($client,"unknown_cmd\n",$userinput);
6266: }
6267: return 1;
6268: }
6269: ®ister_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
6270:
1.489.2.11 raeburn 6271: sub crsreq_update_handler {
6272: my ($cmd, $tail, $client) = @_;
6273: my $userinput = "$cmd:$tail";
1.489.2.14 raeburn 6274: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
6275: $accessstart,$accessend,$infohashref) =
1.489.2.11 raeburn 6276: split(/:/, $tail);
6277: $crstype = &unescape($crstype);
6278: $action = &unescape($action);
6279: $ownername = &unescape($ownername);
6280: $ownerdomain = &unescape($ownerdomain);
6281: $fullname = &unescape($fullname);
6282: $title = &unescape($title);
6283: $code = &unescape($code);
1.489.2.14 raeburn 6284: $accessstart = &unescape($accessstart);
6285: $accessend = &unescape($accessend);
1.489.2.11 raeburn 6286: my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
6287: my ($result,$outcome);
6288: eval {
6289: local($SIG{__DIE__})='DEFAULT';
6290: my %rtnhash;
6291: $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
6292: $ownername,$ownerdomain,$fullname,
1.489.2.14 raeburn 6293: $title,$code,$accessstart,$accessend,
6294: $incoming,\%rtnhash);
1.489.2.11 raeburn 6295: if ($outcome eq 'ok') {
1.489.2.18 raeburn 6296: my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.489.2.11 raeburn 6297: foreach my $key (keys(%rtnhash)) {
6298: if (grep(/^\Q$key\E/,@posskeys)) {
6299: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
6300: }
6301: }
6302: $result =~ s/\&$//;
6303: }
6304: };
6305: if (!$@) {
6306: if ($outcome eq 'ok') {
6307: &Reply($client, \$result, $userinput);
6308: } else {
6309: &Reply($client, "format_error\n", $userinput);
6310: }
6311: } else {
6312: &Failure($client,"unknown_cmd\n",$userinput);
6313: }
6314: return 1;
6315: }
6316: ®ister_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
6317:
1.248 foxr 6318: #
6319: # Read and retrieve institutional code format (for support form).
6320: # Formal Parameters:
6321: # $cmd - Command that dispatched us.
6322: # $tail - Tail of the command. In this case it conatins
6323: # the course domain and the coursename.
6324: # $client - Socket open on the client.
6325: # Returns:
6326: # 1 - Continue processing.
6327: #
6328: sub get_institutional_code_format_handler {
6329: my ($cmd, $tail, $client) = @_;
6330: my $userinput = "$cmd:$tail";
6331:
6332: my $reply;
6333: my($cdom,$course) = split(/:/,$tail);
6334: my @pairs = split/\&/,$course;
6335: my %instcodes = ();
6336: my %codes = ();
6337: my @codetitles = ();
6338: my %cat_titles = ();
6339: my %cat_order = ();
6340: foreach (@pairs) {
6341: my ($key,$value) = split/=/,$_;
6342: $instcodes{&unescape($key)} = &unescape($value);
6343: }
1.489.2.43.2. 2(raebur 6344:5): my $formatreply;
6345:5): eval {
6346:5): local($SIG{__DIE__})='DEFAULT';
6347:5): $formatreply = &localenroll::instcode_format($cdom,
6348:5): \%instcodes,
6349:5): \%codes,
6350:5): \@codetitles,
6351:5): \%cat_titles,
6352:5): \%cat_order);
6353:5): };
1.248 foxr 6354: if ($formatreply eq 'ok') {
1.365 albertel 6355: my $codes_str = &Apache::lonnet::hash2str(%codes);
6356: my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
6357: my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
6358: my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248 foxr 6359: &Reply($client,
6360: $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
6361: .$cat_order_str."\n",
6362: $userinput);
6363: } else {
6364: # this else branch added by RF since if not ok, lonc will
6365: # hang waiting on reply until timeout.
6366: #
6367: &Reply($client, "format_error\n", $userinput);
6368: }
6369:
6370: return 1;
6371: }
1.265 albertel 6372: ®ister_handler("autoinstcodeformat",
6373: \&get_institutional_code_format_handler,0,1,0);
1.246 foxr 6374:
1.345 raeburn 6375: sub get_institutional_defaults_handler {
6376: my ($cmd, $tail, $client) = @_;
6377: my $userinput = "$cmd:$tail";
6378:
6379: my $dom = $tail;
6380: my %defaults_hash;
6381: my @code_order;
6382: my $outcome;
6383: eval {
6384: local($SIG{__DIE__})='DEFAULT';
6385: $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
6386: \@code_order);
6387: };
6388: if (!$@) {
6389: if ($outcome eq 'ok') {
6390: my $result='';
6391: while (my ($key,$value) = each(%defaults_hash)) {
6392: $result.=&escape($key).'='.&escape($value).'&';
6393: }
6394: $result .= 'code_order='.&escape(join('&',@code_order));
1.387 albertel 6395: &Reply($client,\$result,$userinput);
1.345 raeburn 6396: } else {
6397: &Reply($client,"error\n", $userinput);
6398: }
6399: } else {
6400: &Failure($client,"unknown_cmd\n",$userinput);
6401: }
6402: }
6403: ®ister_handler("autoinstcodedefaults",
6404: \&get_institutional_defaults_handler,0,1,0);
6405:
1.416 raeburn 6406: sub get_possible_instcodes_handler {
6407: my ($cmd, $tail, $client) = @_;
6408: my $userinput = "$cmd:$tail";
6409:
6410: my $reply;
6411: my $cdom = $tail;
1.417 raeburn 6412: my (@codetitles,%cat_titles,%cat_order,@code_order);
1.489.2.43.2. 2(raebur 6413:5): my $formatreply;
6414:5): eval {
6415:5): local($SIG{__DIE__})='DEFAULT';
6416:5): $formatreply = &localenroll::possible_instcodes($cdom,
6417:5): \@codetitles,
6418:5): \%cat_titles,
6419:5): \%cat_order,
6420:5): \@code_order);
6421:5): };
1.416 raeburn 6422: if ($formatreply eq 'ok') {
6423: my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417 raeburn 6424: $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416 raeburn 6425: foreach my $key (keys(%cat_titles)) {
6426: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
6427: }
6428: $result =~ s/\&$//;
6429: $result .= ':';
6430: foreach my $key (keys(%cat_order)) {
6431: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
6432: }
6433: $result =~ s/\&$//;
6434: &Reply($client,\$result,$userinput);
6435: } else {
6436: &Reply($client, "format_error\n", $userinput);
6437: }
6438: return 1;
6439: }
6440: ®ister_handler("autopossibleinstcodes",
6441: \&get_possible_instcodes_handler,0,1,0);
6442:
1.381 raeburn 6443: sub get_institutional_user_rules {
6444: my ($cmd, $tail, $client) = @_;
6445: my $userinput = "$cmd:$tail";
6446: my $dom = &unescape($tail);
6447: my (%rules_hash,@rules_order);
6448: my $outcome;
6449: eval {
6450: local($SIG{__DIE__})='DEFAULT';
6451: $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
6452: };
6453: if (!$@) {
6454: if ($outcome eq 'ok') {
6455: my $result;
6456: foreach my $key (keys(%rules_hash)) {
6457: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6458: }
6459: $result =~ s/\&$//;
6460: $result .= ':';
6461: if (@rules_order > 0) {
6462: foreach my $item (@rules_order) {
6463: $result .= &escape($item).'&';
6464: }
6465: }
6466: $result =~ s/\&$//;
1.387 albertel 6467: &Reply($client,\$result,$userinput);
1.381 raeburn 6468: } else {
6469: &Reply($client,"error\n", $userinput);
6470: }
6471: } else {
6472: &Failure($client,"unknown_cmd\n",$userinput);
6473: }
6474: }
6475: ®ister_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
6476:
1.389 raeburn 6477: sub get_institutional_id_rules {
6478: my ($cmd, $tail, $client) = @_;
6479: my $userinput = "$cmd:$tail";
6480: my $dom = &unescape($tail);
6481: my (%rules_hash,@rules_order);
6482: my $outcome;
6483: eval {
6484: local($SIG{__DIE__})='DEFAULT';
6485: $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
6486: };
6487: if (!$@) {
6488: if ($outcome eq 'ok') {
6489: my $result;
6490: foreach my $key (keys(%rules_hash)) {
6491: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6492: }
6493: $result =~ s/\&$//;
6494: $result .= ':';
6495: if (@rules_order > 0) {
6496: foreach my $item (@rules_order) {
6497: $result .= &escape($item).'&';
6498: }
6499: }
6500: $result =~ s/\&$//;
6501: &Reply($client,\$result,$userinput);
6502: } else {
6503: &Reply($client,"error\n", $userinput);
6504: }
6505: } else {
6506: &Failure($client,"unknown_cmd\n",$userinput);
6507: }
6508: }
6509: ®ister_handler("instidrules",\&get_institutional_id_rules,0,1,0);
6510:
1.397 raeburn 6511: sub get_institutional_selfcreate_rules {
1.396 raeburn 6512: my ($cmd, $tail, $client) = @_;
6513: my $userinput = "$cmd:$tail";
6514: my $dom = &unescape($tail);
6515: my (%rules_hash,@rules_order);
6516: my $outcome;
6517: eval {
6518: local($SIG{__DIE__})='DEFAULT';
1.397 raeburn 6519: $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396 raeburn 6520: };
6521: if (!$@) {
6522: if ($outcome eq 'ok') {
6523: my $result;
6524: foreach my $key (keys(%rules_hash)) {
6525: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6526: }
6527: $result =~ s/\&$//;
6528: $result .= ':';
6529: if (@rules_order > 0) {
6530: foreach my $item (@rules_order) {
6531: $result .= &escape($item).'&';
6532: }
6533: }
6534: $result =~ s/\&$//;
6535: &Reply($client,\$result,$userinput);
6536: } else {
6537: &Reply($client,"error\n", $userinput);
6538: }
6539: } else {
6540: &Failure($client,"unknown_cmd\n",$userinput);
6541: }
6542: }
1.397 raeburn 6543: ®ister_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396 raeburn 6544:
1.489.2.43.2. (raeburn 6545:): sub get_unamemap_rules {
6546:): my ($cmd, $tail, $client) = @_;
6547:): my $userinput = "$cmd:$tail";
6548:): my $dom = &unescape($tail);
6549:): my (%rules_hash,@rules_order);
6550:): my $outcome;
6551:): eval {
6552:): local($SIG{__DIE__})='DEFAULT';
6553:): $outcome = &localenroll::unamemap_rules($dom,\%rules_hash,\@rules_order);
6554:): };
6555:): if (!$@) {
6556:): if ($outcome eq 'ok') {
6557:): my $result;
6558:): foreach my $key (keys(%rules_hash)) {
6559:): $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6560:): }
6561:): $result =~ s/\&$//;
6562:): $result .= ':';
6563:): if (@rules_order > 0) {
6564:): foreach my $item (@rules_order) {
6565:): $result .= &escape($item).'&';
6566:): }
6567:): }
6568:): $result =~ s/\&$//;
6569:): &Reply($client,\$result,$userinput);
6570:): } else {
6571:): &Reply($client,"error\n", $userinput);
6572:): }
6573:): } else {
6574:): &Failure($client,"unknown_cmd\n",$userinput);
6575:): }
6576:): }
6577:): ®ister_handler("unamemaprules",\&get_unamemap_rules,0,1,0);
1.381 raeburn 6578:
6579: sub institutional_username_check {
6580: my ($cmd, $tail, $client) = @_;
6581: my $userinput = "$cmd:$tail";
6582: my %rulecheck;
6583: my $outcome;
6584: my ($udom,$uname,@rules) = split(/:/,$tail);
6585: $udom = &unescape($udom);
6586: $uname = &unescape($uname);
6587: @rules = map {&unescape($_);} (@rules);
6588: eval {
6589: local($SIG{__DIE__})='DEFAULT';
6590: $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
6591: };
6592: if (!$@) {
6593: if ($outcome eq 'ok') {
6594: my $result='';
6595: foreach my $key (keys(%rulecheck)) {
6596: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
6597: }
1.387 albertel 6598: &Reply($client,\$result,$userinput);
1.381 raeburn 6599: } else {
6600: &Reply($client,"error\n", $userinput);
6601: }
6602: } else {
6603: &Failure($client,"unknown_cmd\n",$userinput);
6604: }
6605: }
6606: ®ister_handler("instrulecheck",\&institutional_username_check,0,1,0);
6607:
1.389 raeburn 6608: sub institutional_id_check {
6609: my ($cmd, $tail, $client) = @_;
6610: my $userinput = "$cmd:$tail";
6611: my %rulecheck;
6612: my $outcome;
6613: my ($udom,$id,@rules) = split(/:/,$tail);
6614: $udom = &unescape($udom);
6615: $id = &unescape($id);
6616: @rules = map {&unescape($_);} (@rules);
6617: eval {
6618: local($SIG{__DIE__})='DEFAULT';
6619: $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
6620: };
6621: if (!$@) {
6622: if ($outcome eq 'ok') {
6623: my $result='';
6624: foreach my $key (keys(%rulecheck)) {
6625: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
6626: }
6627: &Reply($client,\$result,$userinput);
6628: } else {
6629: &Reply($client,"error\n", $userinput);
6630: }
6631: } else {
6632: &Failure($client,"unknown_cmd\n",$userinput);
6633: }
6634: }
6635: ®ister_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345 raeburn 6636:
1.397 raeburn 6637: sub institutional_selfcreate_check {
1.396 raeburn 6638: my ($cmd, $tail, $client) = @_;
6639: my $userinput = "$cmd:$tail";
6640: my %rulecheck;
6641: my $outcome;
6642: my ($udom,$email,@rules) = split(/:/,$tail);
6643: $udom = &unescape($udom);
6644: $email = &unescape($email);
6645: @rules = map {&unescape($_);} (@rules);
6646: eval {
6647: local($SIG{__DIE__})='DEFAULT';
1.397 raeburn 6648: $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396 raeburn 6649: };
6650: if (!$@) {
6651: if ($outcome eq 'ok') {
6652: my $result='';
6653: foreach my $key (keys(%rulecheck)) {
6654: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
6655: }
6656: &Reply($client,\$result,$userinput);
6657: } else {
6658: &Reply($client,"error\n", $userinput);
6659: }
6660: } else {
6661: &Failure($client,"unknown_cmd\n",$userinput);
6662: }
6663: }
1.397 raeburn 6664: ®ister_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396 raeburn 6665:
1.317 raeburn 6666: # Get domain specific conditions for import of student photographs to a course
6667: #
6668: # Retrieves information from photo_permission subroutine in localenroll.
6669: # Returns outcome (ok) if no processing errors, and whether course owner is
6670: # required to accept conditions of use (yes/no).
6671: #
6672: #
6673: sub photo_permission_handler {
6674: my ($cmd, $tail, $client) = @_;
6675: my $userinput = "$cmd:$tail";
6676: my $cdom = $tail;
6677: my ($perm_reqd,$conditions);
1.320 albertel 6678: my $outcome;
6679: eval {
6680: local($SIG{__DIE__})='DEFAULT';
6681: $outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
6682: \$conditions);
6683: };
6684: if (!$@) {
6685: &Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
6686: $userinput);
6687: } else {
6688: &Failure($client,"unknown_cmd\n",$userinput);
6689: }
6690: return 1;
1.317 raeburn 6691: }
6692: ®ister_handler("autophotopermission",\&photo_permission_handler,0,1,0);
6693:
6694: #
6695: # Checks if student photo is available for a user in the domain, in the user's
6696: # directory (in /userfiles/internal/studentphoto.jpg).
6697: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
6698: # the student's photo.
6699:
6700: sub photo_check_handler {
6701: my ($cmd, $tail, $client) = @_;
6702: my $userinput = "$cmd:$tail";
6703: my ($udom,$uname,$pid) = split(/:/,$tail);
6704: $udom = &unescape($udom);
6705: $uname = &unescape($uname);
6706: $pid = &unescape($pid);
6707: my $path=&propath($udom,$uname).'/userfiles/internal/';
6708: if (!-e $path) {
6709: &mkpath($path);
6710: }
6711: my $response;
6712: my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
6713: $result .= ':'.$response;
6714: &Reply($client, &escape($result)."\n",$userinput);
1.320 albertel 6715: return 1;
1.317 raeburn 6716: }
6717: ®ister_handler("autophotocheck",\&photo_check_handler,0,1,0);
6718:
6719: #
6720: # Retrieve information from localenroll about whether to provide a button
6721: # for users who have enbled import of student photos to initiate an
6722: # update of photo files for registered students. Also include
6723: # comment to display alongside button.
6724:
6725: sub photo_choice_handler {
6726: my ($cmd, $tail, $client) = @_;
6727: my $userinput = "$cmd:$tail";
6728: my $cdom = &unescape($tail);
1.320 albertel 6729: my ($update,$comment);
6730: eval {
6731: local($SIG{__DIE__})='DEFAULT';
6732: ($update,$comment) = &localenroll::manager_photo_update($cdom);
6733: };
6734: if (!$@) {
6735: &Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
6736: } else {
6737: &Failure($client,"unknown_cmd\n",$userinput);
6738: }
6739: return 1;
1.317 raeburn 6740: }
6741: ®ister_handler("autophotochoice",\&photo_choice_handler,0,1,0);
6742:
1.265 albertel 6743: #
6744: # Gets a student's photo to exist (in the correct image type) in the user's
6745: # directory.
6746: # Formal Parameters:
6747: # $cmd - The command request that got us dispatched.
6748: # $tail - A colon separated set of words that will be split into:
6749: # $domain - student's domain
6750: # $uname - student username
6751: # $type - image type desired
6752: # $client - The socket open on the client.
6753: # Returns:
6754: # 1 - continue processing.
1.317 raeburn 6755:
1.265 albertel 6756: sub student_photo_handler {
6757: my ($cmd, $tail, $client) = @_;
1.317 raeburn 6758: my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265 albertel 6759:
1.317 raeburn 6760: my $path=&propath($domain,$uname). '/userfiles/internal/';
6761: my $filename = 'studentphoto.'.$ext;
6762: if ($type eq 'thumbnail') {
6763: $filename = 'studentphoto_tn.'.$ext;
6764: }
6765: if (-e $path.$filename) {
1.265 albertel 6766: &Reply($client,"ok\n","$cmd:$tail");
6767: return 1;
6768: }
6769: &mkpath($path);
1.317 raeburn 6770: my $file;
6771: if ($type eq 'thumbnail') {
1.320 albertel 6772: eval {
6773: local($SIG{__DIE__})='DEFAULT';
6774: $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
6775: };
1.317 raeburn 6776: } else {
6777: $file=&localstudentphoto::fetch($domain,$uname);
6778: }
1.265 albertel 6779: if (!$file) {
6780: &Failure($client,"unavailable\n","$cmd:$tail");
6781: return 1;
6782: }
1.317 raeburn 6783: if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
6784: if (-e $path.$filename) {
1.265 albertel 6785: &Reply($client,"ok\n","$cmd:$tail");
6786: return 1;
6787: }
6788: &Failure($client,"unable_to_convert\n","$cmd:$tail");
6789: return 1;
6790: }
6791: ®ister_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246 foxr 6792:
1.361 raeburn 6793: sub inst_usertypes_handler {
6794: my ($cmd, $domain, $client) = @_;
6795: my $res;
6796: my $userinput = $cmd.":".$domain; # For logging purposes.
1.370 albertel 6797: my (%typeshash,@order,$result);
6798: eval {
6799: local($SIG{__DIE__})='DEFAULT';
6800: $result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
6801: };
6802: if ($result eq 'ok') {
1.361 raeburn 6803: if (keys(%typeshash) > 0) {
6804: foreach my $key (keys(%typeshash)) {
6805: $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
6806: }
6807: }
6808: $res=~s/\&$//;
6809: $res .= ':';
6810: if (@order > 0) {
6811: foreach my $item (@order) {
6812: $res .= &escape($item).'&';
6813: }
6814: }
6815: $res=~s/\&$//;
6816: }
1.387 albertel 6817: &Reply($client, \$res, $userinput);
1.361 raeburn 6818: return 1;
6819: }
6820: ®ister_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
6821:
1.264 albertel 6822: # mkpath makes all directories for a file, expects an absolute path with a
6823: # file or a trailing / if just a dir is passed
6824: # returns 1 on success 0 on failure
6825: sub mkpath {
6826: my ($file)=@_;
6827: my @parts=split(/\//,$file,-1);
6828: my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
6829: for (my $i=3;$i<= ($#parts-1);$i++) {
1.265 albertel 6830: $now.='/'.$parts[$i];
1.264 albertel 6831: if (!-e $now) {
6832: if (!mkdir($now,0770)) { return 0; }
6833: }
6834: }
6835: return 1;
6836: }
6837:
1.207 foxr 6838: #---------------------------------------------------------------
6839: #
6840: # Getting, decoding and dispatching requests:
6841: #
6842: #
6843: # Get a Request:
6844: # Gets a Request message from the client. The transaction
6845: # is defined as a 'line' of text. We remove the new line
6846: # from the text line.
1.226 foxr 6847: #
1.211 albertel 6848: sub get_request {
1.207 foxr 6849: my $input = <$client>;
6850: chomp($input);
1.226 foxr 6851:
1.234 foxr 6852: &Debug("get_request: Request = $input\n");
1.207 foxr 6853:
6854: &status('Processing '.$clientname.':'.$input);
6855:
6856: return $input;
6857: }
1.212 foxr 6858: #---------------------------------------------------------------
6859: #
6860: # Process a request. This sub should shrink as each action
6861: # gets farmed out into a separat sub that is registered
6862: # with the dispatch hash.
6863: #
6864: # Parameters:
6865: # user_input - The request received from the client (lonc).
6866: # Returns:
6867: # true to keep processing, false if caller should exit.
6868: #
6869: sub process_request {
6870: my ($userinput) = @_; # Easier for now to break style than to
6871: # fix all the userinput -> user_input.
6872: my $wasenc = 0; # True if request was encrypted.
6873: # ------------------------------------------------------------ See if encrypted
1.322 albertel 6874: # for command
6875: # sethost:<server>
6876: # <command>:<args>
6877: # we just send it to the processor
6878: # for
6879: # sethost:<server>:<command>:<args>
6880: # we do the implict set host and then do the command
6881: if ($userinput =~ /^sethost:/) {
6882: (my $cmd,my $newid,$userinput) = split(':',$userinput,3);
6883: if (defined($userinput)) {
6884: &sethost("$cmd:$newid");
6885: } else {
6886: $userinput = "$cmd:$newid";
6887: }
6888: }
6889:
1.212 foxr 6890: if ($userinput =~ /^enc/) {
6891: $userinput = decipher($userinput);
6892: $wasenc=1;
6893: if(!$userinput) { # Cipher not defined.
1.251 foxr 6894: &Failure($client, "error: Encrypted data without negotated key\n");
1.212 foxr 6895: return 0;
6896: }
6897: }
6898: Debug("process_request: $userinput\n");
6899:
1.213 foxr 6900: #
6901: # The 'correct way' to add a command to lond is now to
6902: # write a sub to execute it and Add it to the command dispatch
6903: # hash via a call to register_handler.. The comments to that
6904: # sub should give you enough to go on to show how to do this
6905: # along with the examples that are building up as this code
6906: # is getting refactored. Until all branches of the
6907: # if/elseif monster below have been factored out into
6908: # separate procesor subs, if the dispatch hash is missing
6909: # the command keyword, we will fall through to the remainder
6910: # of the if/else chain below in order to keep this thing in
6911: # working order throughout the transmogrification.
6912:
6913: my ($command, $tail) = split(/:/, $userinput, 2);
6914: chomp($command);
6915: chomp($tail);
6916: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
1.214 foxr 6917: $command =~ s/(\r)//; # And this too for parameterless commands.
6918: if(!$tail) {
6919: $tail =""; # defined but blank.
6920: }
1.213 foxr 6921:
6922: &Debug("Command received: $command, encoded = $wasenc");
6923:
6924: if(defined $Dispatcher{$command}) {
6925:
6926: my $dispatch_info = $Dispatcher{$command};
6927: my $handler = $$dispatch_info[0];
6928: my $need_encode = $$dispatch_info[1];
6929: my $client_types = $$dispatch_info[2];
6930: Debug("Matched dispatch hash: mustencode: $need_encode "
6931: ."ClientType $client_types");
6932:
6933: # Validate the request:
6934:
6935: my $ok = 1;
6936: my $requesterprivs = 0;
6937: if(&isClient()) {
6938: $requesterprivs |= $CLIENT_OK;
6939: }
6940: if(&isManager()) {
6941: $requesterprivs |= $MANAGER_OK;
6942: }
6943: if($need_encode && (!$wasenc)) {
6944: Debug("Must encode but wasn't: $need_encode $wasenc");
6945: $ok = 0;
6946: }
6947: if(($client_types & $requesterprivs) == 0) {
6948: Debug("Client not privileged to do this operation");
6949: $ok = 0;
6950: }
6951:
6952: if($ok) {
6953: Debug("Dispatching to handler $command $tail");
6954: my $keep_going = &$handler($command, $tail, $client);
6955: return $keep_going;
6956: } else {
6957: Debug("Refusing to dispatch because client did not match requirements");
6958: Failure($client, "refused\n", $userinput);
6959: return 1;
6960: }
6961:
6962: }
6963:
1.262 foxr 6964: print $client "unknown_cmd\n";
1.212 foxr 6965: # -------------------------------------------------------------------- complete
6966: Debug("process_request - returning 1");
6967: return 1;
6968: }
1.207 foxr 6969: #
6970: # Decipher encoded traffic
6971: # Parameters:
6972: # input - Encoded data.
6973: # Returns:
6974: # Decoded data or undef if encryption key was not yet negotiated.
6975: # Implicit input:
6976: # cipher - This global holds the negotiated encryption key.
6977: #
1.211 albertel 6978: sub decipher {
1.207 foxr 6979: my ($input) = @_;
6980: my $output = '';
1.212 foxr 6981:
6982:
1.207 foxr 6983: if($cipher) {
6984: my($enc, $enclength, $encinput) = split(/:/, $input);
6985: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
6986: $output .=
6987: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
6988: }
6989: return substr($output, 0, $enclength);
6990: } else {
6991: return undef;
6992: }
6993: }
6994:
6995: #
6996: # Register a command processor. This function is invoked to register a sub
6997: # to process a request. Once registered, the ProcessRequest sub can automatically
6998: # dispatch requests to an appropriate sub, and do the top level validity checking
6999: # as well:
7000: # - Is the keyword recognized.
7001: # - Is the proper client type attempting the request.
7002: # - Is the request encrypted if it has to be.
7003: # Parameters:
7004: # $request_name - Name of the request being registered.
7005: # This is the command request that will match
7006: # against the hash keywords to lookup the information
7007: # associated with the dispatch information.
7008: # $procedure - Reference to a sub to call to process the request.
7009: # All subs get called as follows:
7010: # Procedure($cmd, $tail, $replyfd, $key)
7011: # $cmd - the actual keyword that invoked us.
7012: # $tail - the tail of the request that invoked us.
7013: # $replyfd- File descriptor connected to the client
7014: # $must_encode - True if the request must be encoded to be good.
7015: # $client_ok - True if it's ok for a client to request this.
7016: # $manager_ok - True if it's ok for a manager to request this.
7017: # Side effects:
7018: # - On success, the Dispatcher hash has an entry added for the key $RequestName
7019: # - On failure, the program will die as it's a bad internal bug to try to
7020: # register a duplicate command handler.
7021: #
1.211 albertel 7022: sub register_handler {
1.212 foxr 7023: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
1.207 foxr 7024:
7025: # Don't allow duplication#
7026:
7027: if (defined $Dispatcher{$request_name}) {
7028: die "Attempting to define a duplicate request handler for $request_name\n";
7029: }
7030: # Build the client type mask:
7031:
7032: my $client_type_mask = 0;
7033: if($client_ok) {
7034: $client_type_mask |= $CLIENT_OK;
7035: }
7036: if($manager_ok) {
7037: $client_type_mask |= $MANAGER_OK;
7038: }
7039:
7040: # Enter the hash:
7041:
7042: my @entry = ($procedure, $must_encode, $client_type_mask);
7043:
7044: $Dispatcher{$request_name} = \@entry;
7045:
7046: }
7047:
7048:
7049: #------------------------------------------------------------------
7050:
7051:
7052:
7053:
1.141 foxr 7054: #
1.96 foxr 7055: # Convert an error return code from lcpasswd to a string value.
7056: #
7057: sub lcpasswdstrerror {
7058: my $ErrorCode = shift;
1.97 foxr 7059: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 7060: return "lcpasswd Unrecognized error return value ".$ErrorCode;
7061: } else {
1.98 foxr 7062: return $passwderrors[$ErrorCode];
1.96 foxr 7063: }
7064: }
7065:
1.23 harris41 7066: # grabs exception and records it to log before exiting
7067: sub catchexception {
1.27 albertel 7068: my ($error)=@_;
1.25 www 7069: $SIG{'QUIT'}='DEFAULT';
7070: $SIG{__DIE__}='DEFAULT';
1.165 albertel 7071: &status("Catching exception");
1.190 albertel 7072: &logthis("<font color='red'>CRITICAL: "
1.373 albertel 7073: ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27 albertel 7074: ."a crash with this error msg->[$error]</font>");
1.57 www 7075: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 7076: if ($client) { print $client "error: $error\n"; }
1.59 www 7077: $server->close();
1.27 albertel 7078: die($error);
1.23 harris41 7079: }
1.63 www 7080: sub timeout {
1.165 albertel 7081: &status("Handling Timeout");
1.190 albertel 7082: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63 www 7083: &catchexception('Timeout');
7084: }
1.22 harris41 7085: # -------------------------------- Set signal handlers to record abnormal exits
7086:
1.226 foxr 7087:
1.22 harris41 7088: $SIG{'QUIT'}=\&catchexception;
7089: $SIG{__DIE__}=\&catchexception;
7090:
1.81 matthew 7091: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 7092: &status("Read loncapa.conf and loncapa_apache.conf");
7093: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 7094: %perlvar=%{$perlvarref};
1.80 harris41 7095: undef $perlvarref;
1.19 www 7096:
1.35 harris41 7097: # ----------------------------- Make sure this process is running from user=www
7098: my $wwwid=getpwnam('www');
7099: if ($wwwid!=$<) {
1.489.2.43.2. 1(raebur 7100:4): my $emailto="$perlvar{'lonAdmEMail'} $perlvar{'lonSysEMail'}";
1.134 albertel 7101: my $subj="LON: $currenthostid User ID mismatch";
1.489.2.31 raeburn 7102: system("echo 'User ID mismatch. lond must be run as user www.' |".
7103: " mail -s '$subj' $emailto > /dev/null");
1.35 harris41 7104: exit 1;
7105: }
7106:
1.19 www 7107: # --------------------------------------------- Check if other instance running
7108:
7109: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
7110:
7111: if (-e $pidfile) {
7112: my $lfh=IO::File->new("$pidfile");
7113: my $pide=<$lfh>;
7114: chomp($pide);
1.29 harris41 7115: if (kill 0 => $pide) { die "already running"; }
1.19 www 7116: }
1.1 albertel 7117:
7118: # ------------------------------------------------------------- Read hosts file
7119:
7120:
7121:
7122: # establish SERVER socket, bind and listen.
7123: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
7124: Type => SOCK_STREAM,
7125: Proto => 'tcp',
1.469 foxr 7126: ReuseAddr => 1,
1.1 albertel 7127: Listen => 10 )
1.29 harris41 7128: or die "making socket: $@\n";
1.1 albertel 7129:
7130: # --------------------------------------------------------- Do global variables
7131:
7132: # global variables
7133:
1.134 albertel 7134: my %children = (); # keys are current child process IDs
1.1 albertel 7135:
7136: sub REAPER { # takes care of dead children
7137: $SIG{CHLD} = \&REAPER;
1.165 albertel 7138: &status("Handling child death");
1.178 foxr 7139: my $pid;
7140: do {
7141: $pid = waitpid(-1,&WNOHANG());
7142: if (defined($children{$pid})) {
7143: &logthis("Child $pid died");
7144: delete($children{$pid});
1.183 albertel 7145: } elsif ($pid > 0) {
1.178 foxr 7146: &logthis("Unknown Child $pid died");
7147: }
7148: } while ( $pid > 0 );
7149: foreach my $child (keys(%children)) {
7150: $pid = waitpid($child,&WNOHANG());
7151: if ($pid > 0) {
7152: &logthis("Child $child - $pid looks like we missed it's death");
7153: delete($children{$pid});
7154: }
1.176 albertel 7155: }
1.165 albertel 7156: &status("Finished Handling child death");
1.1 albertel 7157: }
7158:
7159: sub HUNTSMAN { # signal handler for SIGINT
1.165 albertel 7160: &status("Killing children (INT)");
1.1 albertel 7161: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
7162: kill 'INT' => keys %children;
1.59 www 7163: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 7164: my $execdir=$perlvar{'lonDaemons'};
7165: unlink("$execdir/logs/lond.pid");
1.190 albertel 7166: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165 albertel 7167: &status("Done killing children");
1.1 albertel 7168: exit; # clean up with dignity
7169: }
7170:
7171: sub HUPSMAN { # signal handler for SIGHUP
7172: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.165 albertel 7173: &status("Killing children for restart (HUP)");
1.1 albertel 7174: kill 'INT' => keys %children;
1.59 www 7175: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190 albertel 7176: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134 albertel 7177: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 7178: unlink("$execdir/logs/lond.pid");
1.165 albertel 7179: &status("Restarting self (HUP)");
1.1 albertel 7180: exec("$execdir/lond"); # here we go again
7181: }
7182:
1.144 foxr 7183: #
1.148 foxr 7184: # Reload the Apache daemon's state.
1.150 foxr 7185: # This is done by invoking /home/httpd/perl/apachereload
7186: # a setuid perl script that can be root for us to do this job.
1.148 foxr 7187: #
7188: sub ReloadApache {
1.473 raeburn 7189: # --------------------------- Handle case of another apachereload process (locking)
1.474 raeburn 7190: if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
7191: my $execdir = $perlvar{'lonDaemons'};
7192: my $script = $execdir."/apachereload";
7193: system($script);
7194: unlink('/tmp/lock_apachereload'); # Remove the lock file.
7195: }
1.148 foxr 7196: }
7197:
7198: #
1.144 foxr 7199: # Called in response to a USR2 signal.
7200: # - Reread hosts.tab
7201: # - All children connected to hosts that were removed from hosts.tab
7202: # are killed via SIGINT
7203: # - All children connected to previously existing hosts are sent SIGUSR1
7204: # - Our internal hosts hash is updated to reflect the new contents of
7205: # hosts.tab causing connections from hosts added to hosts.tab to
7206: # now be honored.
7207: #
7208: sub UpdateHosts {
1.165 albertel 7209: &status("Reload hosts.tab");
1.147 foxr 7210: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 7211: #
7212: # The %children hash has the set of IP's we currently have children
7213: # on. These need to be matched against records in the hosts.tab
7214: # Any ip's no longer in the table get killed off they correspond to
7215: # either dropped or changed hosts. Note that the re-read of the table
7216: # will take care of new and changed hosts as connections come into being.
7217:
1.371 albertel 7218: &Apache::lonnet::reset_hosts_info();
1.148 foxr 7219:
1.368 albertel 7220: foreach my $child (keys(%children)) {
1.148 foxr 7221: my $childip = $children{$child};
1.374 albertel 7222: if ($childip ne '127.0.0.1'
7223: && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149 foxr 7224: logthis('<font color="blue"> UpdateHosts killing child '
7225: ." $child for ip $childip </font>");
1.148 foxr 7226: kill('INT', $child);
1.149 foxr 7227: } else {
7228: logthis('<font color="green"> keeping child for ip '
7229: ." $childip (pid=$child) </font>");
1.148 foxr 7230: }
7231: }
7232: ReloadApache;
1.165 albertel 7233: &status("Finished reloading hosts.tab");
1.144 foxr 7234: }
7235:
1.148 foxr 7236:
1.57 www 7237: sub checkchildren {
1.165 albertel 7238: &status("Checking on the children (sending signals)");
1.57 www 7239: &initnewstatus();
7240: &logstatus();
7241: &logthis('Going to check on the children');
1.134 albertel 7242: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 7243: foreach (sort keys %children) {
1.221 albertel 7244: #sleep 1;
1.57 www 7245: unless (kill 'USR1' => $_) {
7246: &logthis ('Child '.$_.' is dead');
7247: &logstatus($$.' is dead');
1.221 albertel 7248: delete($children{$_});
1.57 www 7249: }
1.61 harris41 7250: }
1.63 www 7251: sleep 5;
1.212 foxr 7252: $SIG{ALRM} = sub { Debug("timeout");
7253: die "timeout"; };
1.113 albertel 7254: $SIG{__DIE__} = 'DEFAULT';
1.165 albertel 7255: &status("Checking on the children (waiting for reports)");
1.63 www 7256: foreach (sort keys %children) {
7257: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 7258: eval {
7259: alarm(300);
1.63 www 7260: &logthis('Child '.$_.' did not respond');
1.67 albertel 7261: kill 9 => $_;
1.131 albertel 7262: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
7263: #$subj="LON: $currenthostid killed lond process $_";
7264: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
7265: #$execdir=$perlvar{'lonDaemons'};
7266: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221 albertel 7267: delete($children{$_});
1.113 albertel 7268: alarm(0);
7269: }
1.63 www 7270: }
7271: }
1.113 albertel 7272: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 7273: $SIG{__DIE__} = \&catchexception;
1.165 albertel 7274: &status("Finished checking children");
1.221 albertel 7275: &logthis('Finished Checking children');
1.57 www 7276: }
7277:
1.1 albertel 7278: # --------------------------------------------------------------------- Logging
7279:
7280: sub logthis {
7281: my $message=shift;
7282: my $execdir=$perlvar{'lonDaemons'};
7283: my $fh=IO::File->new(">>$execdir/logs/lond.log");
7284: my $now=time;
7285: my $local=localtime($now);
1.58 www 7286: $lastlog=$local.': '.$message;
1.1 albertel 7287: print $fh "$local ($$): $message\n";
7288: }
7289:
1.77 foxr 7290: # ------------------------- Conditional log if $DEBUG true.
7291: sub Debug {
7292: my $message = shift;
7293: if($DEBUG) {
7294: &logthis($message);
7295: }
7296: }
1.161 foxr 7297:
7298: #
7299: # Sub to do replies to client.. this gives a hook for some
7300: # debug tracing too:
7301: # Parameters:
7302: # fd - File open on client.
7303: # reply - Text to send to client.
7304: # request - Original request from client.
7305: #
7306: sub Reply {
1.192 foxr 7307: my ($fd, $reply, $request) = @_;
1.387 albertel 7308: if (ref($reply)) {
7309: print $fd $$reply;
7310: print $fd "\n";
7311: if ($DEBUG) { Debug("Request was $request Reply was $$reply"); }
7312: } else {
7313: print $fd $reply;
7314: if ($DEBUG) { Debug("Request was $request Reply was $reply"); }
7315: }
1.212 foxr 7316: $Transactions++;
7317: }
7318:
7319:
7320: #
7321: # Sub to report a failure.
7322: # This function:
7323: # - Increments the failure statistic counters.
7324: # - Invokes Reply to send the error message to the client.
7325: # Parameters:
7326: # fd - File descriptor open on the client
7327: # reply - Reply text to emit.
7328: # request - The original request message (used by Reply
7329: # to debug if that's enabled.
7330: # Implicit outputs:
7331: # $Failures- The number of failures is incremented.
7332: # Reply (invoked here) sends a message to the
7333: # client:
7334: #
7335: sub Failure {
7336: my $fd = shift;
7337: my $reply = shift;
7338: my $request = shift;
7339:
7340: $Failures++;
7341: Reply($fd, $reply, $request); # That's simple eh?
1.161 foxr 7342: }
1.57 www 7343: # ------------------------------------------------------------------ Log status
7344:
7345: sub logstatus {
1.178 foxr 7346: &status("Doing logging");
7347: my $docdir=$perlvar{'lonDocRoot'};
7348: {
7349: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200 matthew 7350: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178 foxr 7351: $fh->close();
7352: }
1.221 albertel 7353: &status("Finished $$.txt");
7354: {
7355: open(LOG,">>$docdir/lon-status/londstatus.txt");
7356: flock(LOG,LOCK_EX);
7357: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
7358: .$status."\t".$lastlog."\t $keymode\n";
1.275 albertel 7359: flock(LOG,LOCK_UN);
1.221 albertel 7360: close(LOG);
7361: }
1.178 foxr 7362: &status("Finished logging");
1.57 www 7363: }
7364:
7365: sub initnewstatus {
7366: my $docdir=$perlvar{'lonDocRoot'};
7367: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460 foxr 7368: my $now=time();
1.57 www 7369: my $local=localtime($now);
7370: print $fh "LOND status $local - parent $$\n\n";
1.64 www 7371: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 7372: while (my $filename=readdir(DIR)) {
1.64 www 7373: unlink("$docdir/lon-status/londchld/$filename");
7374: }
7375: closedir(DIR);
1.57 www 7376: }
7377:
7378: # -------------------------------------------------------------- Status setting
7379:
7380: sub status {
7381: my $what=shift;
7382: my $now=time;
7383: my $local=localtime($now);
1.178 foxr 7384: $status=$local.': '.$what;
7385: $0='lond: '.$what.' '.$local;
1.57 www 7386: }
1.11 www 7387:
1.13 www 7388: # -------------------------------------------------------------- Talk to lonsql
7389:
1.234 foxr 7390: sub sql_reply {
1.12 harris41 7391: my ($cmd)=@_;
1.234 foxr 7392: my $answer=&sub_sql_reply($cmd);
7393: if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12 harris41 7394: return $answer;
7395: }
7396:
1.234 foxr 7397: sub sub_sql_reply {
1.12 harris41 7398: my ($cmd)=@_;
7399: my $unixsock="mysqlsock";
7400: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
7401: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
7402: Type => SOCK_STREAM,
7403: Timeout => 10)
7404: or return "con_lost";
1.319 www 7405: print $sclient "$cmd:$currentdomainid\n";
1.12 harris41 7406: my $answer=<$sclient>;
7407: chomp($answer);
7408: if (!$answer) { $answer="con_lost"; }
7409: return $answer;
7410: }
7411:
1.1 albertel 7412: # --------------------------------------- Is this the home server of an author?
1.11 www 7413:
1.1 albertel 7414: sub ishome {
7415: my $author=shift;
7416: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
7417: my ($udom,$uname)=split(/\//,$author);
7418: my $proname=propath($udom,$uname);
7419: if (-e $proname) {
7420: return 'owner';
7421: } else {
7422: return 'not_owner';
7423: }
7424: }
7425:
7426: # ======================================================= Continue main program
7427: # ---------------------------------------------------- Fork once and dissociate
7428:
1.134 albertel 7429: my $fpid=fork;
1.1 albertel 7430: exit if $fpid;
1.29 harris41 7431: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 7432:
1.29 harris41 7433: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 7434:
7435: # ------------------------------------------------------- Write our PID on disk
7436:
1.134 albertel 7437: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 7438: open (PIDSAVE,">$execdir/logs/lond.pid");
7439: print PIDSAVE "$$\n";
7440: close(PIDSAVE);
1.190 albertel 7441: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57 www 7442: &status('Starting');
1.1 albertel 7443:
1.106 foxr 7444:
1.1 albertel 7445:
7446: # ----------------------------------------------------- Install signal handlers
7447:
1.57 www 7448:
1.1 albertel 7449: $SIG{CHLD} = \&REAPER;
7450: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
7451: $SIG{HUP} = \&HUPSMAN;
1.57 www 7452: $SIG{USR1} = \&checkchildren;
1.144 foxr 7453: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 7454:
1.148 foxr 7455: # Read the host hashes:
1.368 albertel 7456: &Apache::lonnet::load_hosts_tab();
1.447 raeburn 7457: my %iphost = &Apache::lonnet::get_iphost(1);
1.106 foxr 7458:
1.480 raeburn 7459: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286 albertel 7460:
1.471 raeburn 7461: my $arch = `uname -i`;
1.475 raeburn 7462: chomp($arch);
1.471 raeburn 7463: if ($arch eq 'unknown') {
7464: $arch = `uname -m`;
1.475 raeburn 7465: chomp($arch);
1.471 raeburn 7466: }
7467:
1.106 foxr 7468: # --------------------------------------------------------------
7469: # Accept connections. When a connection comes in, it is validated
7470: # and if good, a child process is created to process transactions
7471: # along the connection.
7472:
1.1 albertel 7473: while (1) {
1.165 albertel 7474: &status('Starting accept');
1.106 foxr 7475: $client = $server->accept() or next;
1.165 albertel 7476: &status('Accepted '.$client.' off to spawn');
1.386 albertel 7477: make_new_child($client);
1.165 albertel 7478: &status('Finished spawning');
1.1 albertel 7479: }
7480:
1.212 foxr 7481: sub make_new_child {
7482: my $pid;
7483: # my $cipher; # Now global
7484: my $sigset;
1.178 foxr 7485:
1.212 foxr 7486: $client = shift;
7487: &status('Starting new child '.$client);
7488: &logthis('<font color="green"> Attempting to start child ('.$client.
7489: ")</font>");
7490: # block signal for fork
7491: $sigset = POSIX::SigSet->new(SIGINT);
7492: sigprocmask(SIG_BLOCK, $sigset)
7493: or die "Can't block SIGINT for fork: $!\n";
1.178 foxr 7494:
1.212 foxr 7495: die "fork: $!" unless defined ($pid = fork);
1.178 foxr 7496:
1.212 foxr 7497: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
7498: # connection liveness.
1.178 foxr 7499:
1.212 foxr 7500: #
7501: # Figure out who we're talking to so we can record the peer in
7502: # the pid hash.
7503: #
7504: my $caller = getpeername($client);
7505: my ($port,$iaddr);
7506: if (defined($caller) && length($caller) > 0) {
7507: ($port,$iaddr)=unpack_sockaddr_in($caller);
7508: } else {
7509: &logthis("Unable to determine who caller was, getpeername returned nothing");
7510: }
7511: if (defined($iaddr)) {
7512: $clientip = inet_ntoa($iaddr);
7513: Debug("Connected with $clientip");
7514: } else {
7515: &logthis("Unable to determine clientip");
7516: $clientip='Unavailable';
7517: }
7518:
7519: if ($pid) {
7520: # Parent records the child's birth and returns.
7521: sigprocmask(SIG_UNBLOCK, $sigset)
7522: or die "Can't unblock SIGINT for fork: $!\n";
7523: $children{$pid} = $clientip;
7524: &status('Started child '.$pid);
1.462 foxr 7525: close($client);
1.212 foxr 7526: return;
7527: } else {
7528: # Child can *not* return from this subroutine.
7529: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
7530: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
7531: #don't get intercepted
7532: $SIG{USR1}= \&logstatus;
7533: $SIG{ALRM}= \&timeout;
1.468 foxr 7534: #
7535: # Block sigpipe as it gets thrownon socket disconnect and we want to
7536: # deal with that as a read faiure instead.
7537: #
7538: my $blockset = POSIX::SigSet->new(SIGPIPE);
7539: sigprocmask(SIG_BLOCK, $blockset);
7540:
1.212 foxr 7541: $lastlog='Forked ';
7542: $status='Forked';
1.178 foxr 7543:
1.212 foxr 7544: # unblock signals
7545: sigprocmask(SIG_UNBLOCK, $sigset)
7546: or die "Can't unblock SIGINT for fork: $!\n";
1.178 foxr 7547:
1.212 foxr 7548: # my $tmpsnum=0; # Now global
7549: #---------------------------------------------------- kerberos 5 initialization
7550: &Authen::Krb5::init_context();
1.489.2.16 raeburn 7551:
7552: my $no_ets;
1.489.2.43 raeburn 7553: if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
1.489.2.16 raeburn 7554: if ($1 >= 7) {
7555: $no_ets = 1;
7556: }
7557: } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
7558: if (($1 eq '9.3') || ($1 >= 12.2)) {
7559: $no_ets = 1;
7560: }
1.489.2.17 raeburn 7561: } elsif ($dist =~ /^sles(\d+)$/) {
7562: if ($1 > 11) {
7563: $no_ets = 1;
7564: }
1.489.2.16 raeburn 7565: } elsif ($dist =~ /^fedora(\d+)$/) {
7566: if ($1 < 7) {
7567: $no_ets = 1;
7568: }
7569: }
7570: unless ($no_ets) {
7571: &Authen::Krb5::init_ets();
7572: }
1.209 albertel 7573:
1.212 foxr 7574: &status('Accepted connection');
7575: # =============================================================================
7576: # do something with the connection
7577: # -----------------------------------------------------------------------------
7578: # see if we know client and 'check' for spoof IP by ineffective challenge
1.178 foxr 7579:
1.278 albertel 7580: my $outsideip=$clientip;
7581: if ($clientip eq '127.0.0.1') {
1.368 albertel 7582: $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278 albertel 7583: }
1.412 foxr 7584: &ReadManagerTable();
1.368 albertel 7585: my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278 albertel 7586: my $ismanager=($managers{$outsideip} ne undef);
1.432 raeburn 7587: $clientname = "[unknown]";
1.212 foxr 7588: if($clientrec) { # Establish client type.
7589: $ConnectionType = "client";
1.368 albertel 7590: $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212 foxr 7591: if($ismanager) {
7592: $ConnectionType = "both";
7593: }
7594: } else {
7595: $ConnectionType = "manager";
1.278 albertel 7596: $clientname = $managers{$outsideip};
1.212 foxr 7597: }
7598: my $clientok;
1.178 foxr 7599:
1.212 foxr 7600: if ($clientrec || $ismanager) {
7601: &status("Waiting for init from $clientip $clientname");
7602: &logthis('<font color="yellow">INFO: Connection, '.
7603: $clientip.
7604: " ($clientname) connection type = $ConnectionType </font>" );
7605: &status("Connecting $clientip ($clientname))");
7606: my $remotereq=<$client>;
7607: chomp($remotereq);
7608: Debug("Got init: $remotereq");
1.337 albertel 7609:
1.212 foxr 7610: if ($remotereq =~ /^init/) {
7611: &sethost("sethost:$perlvar{'lonHostID'}");
7612: #
7613: # If the remote is attempting a local init... give that a try:
7614: #
1.432 raeburn 7615: (my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.489.2.4 raeburn 7616: # For LON-CAPA 2.9, the client session will have sent its LON-CAPA
7617: # version when initiating the connection. For LON-CAPA 2.8 and older,
7618: # the version is retrieved from the global %loncaparevs in lonnet.pm.
7619: # $clientversion contains path to keyfile if $inittype eq 'local'
7620: # it's overridden below in this case
7621: $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209 albertel 7622:
1.212 foxr 7623: # If the connection type is ssl, but I didn't get my
7624: # certificate files yet, then I'll drop back to
7625: # insecure (if allowed).
7626:
7627: if($inittype eq "ssl") {
7628: my ($ca, $cert) = lonssl::CertificateFile;
7629: my $kfile = lonssl::KeyFile;
7630: if((!$ca) ||
7631: (!$cert) ||
7632: (!$kfile)) {
7633: $inittype = ""; # This forces insecure attempt.
7634: &logthis("<font color=\"blue\"> Certificates not "
7635: ."installed -- trying insecure auth</font>");
1.224 foxr 7636: } else { # SSL certificates are in place so
1.212 foxr 7637: } # Leave the inittype alone.
7638: }
7639:
7640: if($inittype eq "local") {
1.432 raeburn 7641: $clientversion = $perlvar{'lonVersion'};
1.212 foxr 7642: my $key = LocalConnection($client, $remotereq);
7643: if($key) {
7644: Debug("Got local key $key");
7645: $clientok = 1;
7646: my $cipherkey = pack("H32", $key);
7647: $cipher = new IDEA($cipherkey);
7648: print $client "ok:local\n";
1.442 www 7649: &logthis('<font color="green">'
1.212 foxr 7650: . "Successful local authentication </font>");
7651: $keymode = "local"
1.178 foxr 7652: } else {
1.212 foxr 7653: Debug("Failed to get local key");
7654: $clientok = 0;
7655: shutdown($client, 3);
7656: close $client;
1.178 foxr 7657: }
1.212 foxr 7658: } elsif ($inittype eq "ssl") {
7659: my $key = SSLConnection($client);
7660: if ($key) {
7661: $clientok = 1;
7662: my $cipherkey = pack("H32", $key);
7663: $cipher = new IDEA($cipherkey);
7664: &logthis('<font color="green">'
7665: ."Successfull ssl authentication with $clientname </font>");
7666: $keymode = "ssl";
7667:
1.178 foxr 7668: } else {
1.212 foxr 7669: $clientok = 0;
7670: close $client;
1.178 foxr 7671: }
1.212 foxr 7672:
7673: } else {
7674: my $ok = InsecureConnection($client);
7675: if($ok) {
7676: $clientok = 1;
7677: &logthis('<font color="green">'
7678: ."Successful insecure authentication with $clientname </font>");
7679: print $client "ok\n";
7680: $keymode = "insecure";
1.178 foxr 7681: } else {
1.212 foxr 7682: &logthis('<font color="yellow">'
7683: ."Attempted insecure connection disallowed </font>");
7684: close $client;
7685: $clientok = 0;
1.178 foxr 7686: }
7687: }
1.212 foxr 7688: } else {
7689: &logthis(
7690: "<font color='blue'>WARNING: "
7691: ."$clientip failed to initialize: >$remotereq< </font>");
7692: &status('No init '.$clientip);
7693: }
7694: } else {
7695: &logthis(
7696: "<font color='blue'>WARNING: Unknown client $clientip</font>");
7697: &status('Hung up on '.$clientip);
7698: }
7699:
7700: if ($clientok) {
7701: # ---------------- New known client connecting, could mean machine online again
1.368 albertel 7702: if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip
1.367 albertel 7703: && $clientip ne '127.0.0.1') {
1.375 albertel 7704: &Apache::lonnet::reconlonc($clientname);
1.212 foxr 7705: }
7706: &logthis("<font color='green'>Established connection: $clientname</font>");
7707: &status('Will listen to '.$clientname);
7708: # ------------------------------------------------------------ Process requests
7709: my $keep_going = 1;
7710: my $user_input;
1.448 raeburn 7711: my $clienthost = &Apache::lonnet::hostname($clientname);
7712: my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
7713: $clienthomedom = &Apache::lonnet::host_domain($clientserverhomeID);
1.212 foxr 7714: while(($user_input = get_request) && $keep_going) {
7715: alarm(120);
7716: Debug("Main: Got $user_input\n");
7717: $keep_going = &process_request($user_input);
1.178 foxr 7718: alarm(0);
1.489.2.42 raeburn 7719: &status('Listening to '.$clientname." ($keymode)");
1.161 foxr 7720: }
1.212 foxr 7721:
1.59 www 7722: # --------------------------------------------- client unknown or fishy, refuse
1.212 foxr 7723: } else {
1.161 foxr 7724: print $client "refused\n";
7725: $client->close();
1.190 albertel 7726: &logthis("<font color='blue'>WARNING: "
1.161 foxr 7727: ."Rejected client $clientip, closing connection</font>");
7728: }
1.212 foxr 7729: }
1.161 foxr 7730:
1.1 albertel 7731: # =============================================================================
1.161 foxr 7732:
1.190 albertel 7733: &logthis("<font color='red'>CRITICAL: "
1.161 foxr 7734: ."Disconnect from $clientip ($clientname)</font>");
1.489.2.42 raeburn 7735:
7736:
1.161 foxr 7737: # this exit is VERY important, otherwise the child will become
7738: # a producer of more and more children, forking yourself into
7739: # process death.
7740: exit;
1.106 foxr 7741:
1.78 foxr 7742: }
1.261 foxr 7743: #
7744: # Determine if a user is an author for the indicated domain.
7745: #
7746: # Parameters:
7747: # domain - domain to check in .
7748: # user - Name of user to check.
7749: #
7750: # Return:
7751: # 1 - User is an author for domain.
7752: # 0 - User is not an author for domain.
7753: sub is_author {
7754: my ($domain, $user) = @_;
7755:
7756: &Debug("is_author: $user @ $domain");
7757:
7758: my $hashref = &tie_user_hash($domain, $user, "roles",
7759: &GDBM_READER());
7760:
7761: # Author role should show up as a key /domain/_au
1.78 foxr 7762:
1.321 albertel 7763: my $value;
1.487 foxr 7764: if ($hashref) {
1.78 foxr 7765:
1.487 foxr 7766: my $key = "/$domain/_au";
7767: if (defined($hashref)) {
7768: $value = $hashref->{$key};
7769: if(!untie_user_hash($hashref)) {
7770: return 'error: ' . ($!+0)." untie (GDBM) Failed";
7771: }
7772: }
7773:
7774: if(defined($value)) {
7775: &Debug("$user @ $domain is an author");
7776: }
7777: } else {
7778: return 'error: '.($!+0)." tie (GDBM) Failed";
1.261 foxr 7779: }
7780:
7781: return defined($value);
7782: }
1.78 foxr 7783: #
7784: # Checks to see if the input roleput request was to set
1.482 www 7785: # an author role. If so, creates construction space
1.78 foxr 7786: # Parameters:
7787: # request - The request sent to the rolesput subchunk.
7788: # We're looking for /domain/_au
7789: # domain - The domain in which the user is having roles doctored.
7790: # user - Name of the user for which the role is being put.
7791: # authtype - The authentication type associated with the user.
7792: #
1.289 albertel 7793: sub manage_permissions {
1.192 foxr 7794: my ($request, $domain, $user, $authtype) = @_;
1.78 foxr 7795: # See if the request is of the form /$domain/_au
1.289 albertel 7796: if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484 raeburn 7797: my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482 www 7798: unless (-e $path) {
7799: mkdir($path);
7800: }
7801: unless (-e $path.'/'.$user) {
7802: mkdir($path.'/'.$user);
7803: }
1.78 foxr 7804: }
7805: }
1.222 foxr 7806:
7807:
7808: #
7809: # Return the full path of a user password file, whether it exists or not.
7810: # Parameters:
7811: # domain - Domain in which the password file lives.
7812: # user - name of the user.
7813: # Returns:
7814: # Full passwd path:
7815: #
7816: sub password_path {
7817: my ($domain, $user) = @_;
1.264 albertel 7818: return &propath($domain, $user).'/passwd';
1.222 foxr 7819: }
7820:
7821: # Password Filename
7822: # Returns the path to a passwd file given domain and user... only if
7823: # it exists.
7824: # Parameters:
7825: # domain - Domain in which to search.
7826: # user - username.
7827: # Returns:
7828: # - If the password file exists returns its path.
7829: # - If the password file does not exist, returns undefined.
7830: #
7831: sub password_filename {
7832: my ($domain, $user) = @_;
7833:
7834: Debug ("PasswordFilename called: dom = $domain user = $user");
7835:
7836: my $path = &password_path($domain, $user);
7837: Debug("PasswordFilename got path: $path");
7838: if(-e $path) {
7839: return $path;
7840: } else {
7841: return undef;
7842: }
7843: }
7844:
7845: #
7846: # Rewrite the contents of the user's passwd file.
7847: # Parameters:
7848: # domain - domain of the user.
7849: # name - User's name.
7850: # contents - New contents of the file.
1.489.2.26 raeburn 7851: # saveold - (optional). If true save old file in a passwd.bak file.
1.222 foxr 7852: # Returns:
7853: # 0 - Failed.
7854: # 1 - Success.
7855: #
7856: sub rewrite_password_file {
1.489.2.26 raeburn 7857: my ($domain, $user, $contents, $saveold) = @_;
1.222 foxr 7858:
7859: my $file = &password_filename($domain, $user);
7860: if (defined $file) {
1.489.2.26 raeburn 7861: if ($saveold) {
7862: my $bakfile = $file.'.bak';
7863: if (CopyFile($file,$bakfile)) {
7864: chmod(0400,$bakfile);
7865: &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
7866: } else {
7867: &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
7868: }
7869: }
1.222 foxr 7870: my $pf = IO::File->new(">$file");
7871: if($pf) {
7872: print $pf "$contents\n";
7873: return 1;
7874: } else {
7875: return 0;
7876: }
7877: } else {
7878: return 0;
7879: }
7880:
7881: }
7882:
1.78 foxr 7883: #
1.222 foxr 7884: # get_auth_type - Determines the authorization type of a user in a domain.
1.78 foxr 7885:
7886: # Returns the authorization type or nouser if there is no such user.
7887: #
1.436 raeburn 7888: sub get_auth_type {
1.192 foxr 7889: my ($domain, $user) = @_;
1.78 foxr 7890:
1.222 foxr 7891: Debug("get_auth_type( $domain, $user ) \n");
1.78 foxr 7892: my $proname = &propath($domain, $user);
7893: my $passwdfile = "$proname/passwd";
7894: if( -e $passwdfile ) {
7895: my $pf = IO::File->new($passwdfile);
7896: my $realpassword = <$pf>;
7897: chomp($realpassword);
1.79 foxr 7898: Debug("Password info = $realpassword\n");
1.78 foxr 7899: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 7900: Debug("Authtype = $authtype, content = $contentpwd\n");
1.259 raeburn 7901: return "$authtype:$contentpwd";
1.224 foxr 7902: } else {
1.79 foxr 7903: Debug("Returning nouser");
1.78 foxr 7904: return "nouser";
7905: }
1.1 albertel 7906: }
7907:
1.220 foxr 7908: #
7909: # Validate a user given their domain, name and password. This utility
7910: # function is used by both AuthenticateHandler and ChangePasswordHandler
7911: # to validate the login credentials of a user.
7912: # Parameters:
7913: # $domain - The domain being logged into (this is required due to
7914: # the capability for multihomed systems.
7915: # $user - The name of the user being validated.
7916: # $password - The user's propoposed password.
7917: #
7918: # Returns:
7919: # 1 - The domain,user,pasword triplet corresponds to a valid
7920: # user.
7921: # 0 - The domain,user,password triplet is not a valid user.
7922: #
7923: sub validate_user {
1.396 raeburn 7924: my ($domain, $user, $password, $checkdefauth) = @_;
1.220 foxr 7925:
7926: # Why negative ~pi you may well ask? Well this function is about
7927: # authentication, and therefore very important to get right.
7928: # I've initialized the flag that determines whether or not I've
7929: # validated correctly to a value it's not supposed to get.
7930: # At the end of this function. I'll ensure that it's not still that
7931: # value so we don't just wind up returning some accidental value
7932: # as a result of executing an unforseen code path that
1.249 foxr 7933: # did not set $validated. At the end of valid execution paths,
7934: # validated shoule be 1 for success or 0 for failuer.
1.220 foxr 7935:
7936: my $validated = -3.14159;
7937:
7938: # How we authenticate is determined by the type of authentication
7939: # the user has been assigned. If the authentication type is
7940: # "nouser", the user does not exist so we will return 0.
7941:
1.222 foxr 7942: my $contents = &get_auth_type($domain, $user);
1.220 foxr 7943: my ($howpwd, $contentpwd) = split(/:/, $contents);
7944:
7945: my $null = pack("C",0); # Used by kerberos auth types.
7946:
1.395 raeburn 7947: if ($howpwd eq 'nouser') {
1.396 raeburn 7948: if ($checkdefauth) {
7949: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
7950: if ($domdefaults{'auth_def'} eq 'localauth') {
7951: $howpwd = $domdefaults{'auth_def'};
7952: $contentpwd = $domdefaults{'auth_arg_def'};
7953: } elsif ((($domdefaults{'auth_def'} eq 'krb4') ||
7954: ($domdefaults{'auth_def'} eq 'krb5')) &&
7955: ($domdefaults{'auth_arg_def'} ne '')) {
1.489.2.43.2. (raeburn 7956:): #
7957:): # Don't attempt authentication for username and password supplied
7958:): # for user without an account if username contains @ to avoid
7959:): # call to &Authen::Krb5::parse_name() which will result in con_lost
7960:): #
7961:): unless ($user =~ /\@/) {
7962:): $howpwd = $domdefaults{'auth_def'};
7963:): $contentpwd = $domdefaults{'auth_arg_def'};
7964:): }
1.396 raeburn 7965: }
1.395 raeburn 7966: }
1.489.2.26 raeburn 7967: }
1.220 foxr 7968: if ($howpwd ne 'nouser') {
7969: if($howpwd eq "internal") { # Encrypted is in local password file.
1.489.2.21 raeburn 7970: if (length($contentpwd) == 13) {
7971: $validated = (crypt($password,$contentpwd) eq $contentpwd);
7972: if ($validated) {
1.489.2.26 raeburn 7973: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
7974: if ($domdefaults{'intauth_switch'}) {
7975: my $ncpass = &hash_passwd($domain,$password);
7976: my $saveold;
7977: if ($domdefaults{'intauth_switch'} == 2) {
7978: $saveold = 1;
7979: }
7980: if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
7981: &update_passwd_history($user,$domain,$howpwd,'conversion');
7982: &logthis("Validated password hashed with bcrypt for $user:$domain");
7983: }
1.489.2.21 raeburn 7984: }
7985: }
7986: } else {
1.489.2.26 raeburn 7987: $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.489.2.21 raeburn 7988: }
1.220 foxr 7989: }
7990: elsif ($howpwd eq "unix") { # User is a normal unix user.
7991: $contentpwd = (getpwnam($user))[1];
7992: if($contentpwd) {
7993: if($contentpwd eq 'x') { # Shadow password file...
7994: my $pwauth_path = "/usr/local/sbin/pwauth";
7995: open PWAUTH, "|$pwauth_path" or
7996: die "Cannot invoke authentication";
7997: print PWAUTH "$user\n$password\n";
7998: close PWAUTH;
7999: $validated = ! $?;
8000:
8001: } else { # Passwords in /etc/passwd.
8002: $validated = (crypt($password,
8003: $contentpwd) eq $contentpwd);
8004: }
8005: } else {
8006: $validated = 0;
8007: }
1.439 raeburn 8008: } elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
8009: my $checkwithkrb5 = 0;
8010: if ($dist =~/^fedora(\d+)$/) {
8011: if ($1 > 11) {
8012: $checkwithkrb5 = 1;
8013: }
8014: } elsif ($dist =~ /^suse([\d.]+)$/) {
8015: if ($1 > 11.1) {
8016: $checkwithkrb5 = 1;
8017: }
8018: }
8019: if ($checkwithkrb5) {
8020: $validated = &krb5_authen($password,$null,$user,$contentpwd);
8021: } else {
8022: $validated = &krb4_authen($password,$null,$user,$contentpwd);
8023: }
1.224 foxr 8024: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439 raeburn 8025: $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224 foxr 8026: } elsif ($howpwd eq "localauth") {
1.220 foxr 8027: # Authenticate via installation specific authentcation method:
8028: $validated = &localauth::localauth($user,
8029: $password,
1.353 albertel 8030: $contentpwd,
8031: $domain);
1.358 albertel 8032: if ($validated < 0) {
1.357 albertel 8033: &logthis("localauth for $contentpwd $user:$domain returned a $validated");
8034: $validated = 0;
8035: }
1.224 foxr 8036: } else { # Unrecognized auth is also bad.
1.220 foxr 8037: $validated = 0;
8038: }
8039: } else {
8040: $validated = 0;
8041: }
8042: #
8043: # $validated has the correct stat of the authentication:
8044: #
8045:
8046: unless ($validated != -3.14159) {
1.249 foxr 8047: # I >really really< want to know if this happens.
8048: # since it indicates that user authentication is badly
8049: # broken in some code path.
8050: #
8051: die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220 foxr 8052: }
8053: return $validated;
8054: }
8055:
1.489.2.21 raeburn 8056: sub check_internal_passwd {
1.489.2.26 raeburn 8057: my ($plainpass,$stored,$domain,$user) = @_;
1.489.2.21 raeburn 8058: my (undef,$method,@rest) = split(/!/,$stored);
1.489.2.26 raeburn 8059: if ($method eq 'bcrypt') {
1.489.2.21 raeburn 8060: my $result = &hash_passwd($domain,$plainpass,@rest);
8061: if ($result ne $stored) {
8062: return 0;
8063: }
1.489.2.26 raeburn 8064: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
8065: if ($domdefaults{'intauth_check'}) {
8066: # Upgrade to a larger number of rounds if necessary
8067: my $defaultcost = $domdefaults{'intauth_cost'};
8068: if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
8069: $defaultcost = 10;
8070: }
8071: if (int($rest[0])<int($defaultcost)) {
8072: if ($domdefaults{'intauth_check'} == 1) {
8073: my $ncpass = &hash_passwd($domain,$plainpass);
8074: if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
8075: &update_passwd_history($user,$domain,'internal','update cost');
8076: &logthis("Validated password hashed with bcrypt for $user:$domain");
8077: }
8078: return 1;
8079: } elsif ($domdefaults{'intauth_check'} == 2) {
8080: return 0;
8081: }
8082: }
8083: } else {
8084: return 1;
1.489.2.21 raeburn 8085: }
8086: }
8087: return 0;
8088: }
8089:
8090: sub get_last_authchg {
8091: my ($domain,$user) = @_;
8092: my $lastmod;
8093: my $logname = &propath($domain,$user).'/passwd.log';
8094: if (-e "$logname") {
8095: $lastmod = (stat("$logname"))[9];
8096: }
8097: return $lastmod;
8098: }
8099:
1.439 raeburn 8100: sub krb4_authen {
8101: my ($password,$null,$user,$contentpwd) = @_;
8102: my $validated = 0;
8103: if (!($password =~ /$null/) ) { # Null password not allowed.
8104: eval {
8105: require Authen::Krb4;
8106: };
8107: if (!$@) {
8108: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
8109: "",
8110: $contentpwd,,
8111: 'krbtgt',
8112: $contentpwd,
8113: 1,
8114: $password);
8115: if(!$k4error) {
8116: $validated = 1;
8117: } else {
8118: $validated = 0;
8119: &logthis('krb4: '.$user.', '.$contentpwd.', '.
8120: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
8121: }
8122: } else {
8123: $validated = krb5_authen($password,$null,$user,$contentpwd);
8124: }
8125: }
8126: return $validated;
8127: }
8128:
8129: sub krb5_authen {
8130: my ($password,$null,$user,$contentpwd) = @_;
8131: my $validated = 0;
8132: if(!($password =~ /$null/)) { # Null password not allowed.
8133: my $krbclient = &Authen::Krb5::parse_name($user.'@'
8134: .$contentpwd);
8135: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
8136: my $krbserver = &Authen::Krb5::parse_name($krbservice);
8137: my $credentials= &Authen::Krb5::cc_default();
8138: $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
8139: .$contentpwd));
8140: my $krbreturn;
8141: if (exists(&Authen::Krb5::get_init_creds_password)) {
8142: $krbreturn =
8143: &Authen::Krb5::get_init_creds_password($krbclient,$password,
8144: $krbservice);
8145: $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
8146: } else {
8147: $krbreturn =
8148: &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
8149: $password,$credentials);
8150: $validated = ($krbreturn == 1);
8151: }
8152: if (!$validated) {
8153: &logthis('krb5: '.$user.', '.$contentpwd.', '.
8154: &Authen::Krb5::error());
8155: }
8156: }
8157: return $validated;
8158: }
1.220 foxr 8159:
1.84 albertel 8160: sub addline {
8161: my ($fname,$hostid,$ip,$newline)=@_;
8162: my $contents;
8163: my $found=0;
1.355 albertel 8164: my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134 albertel 8165: my $sh;
1.84 albertel 8166: if ($sh=IO::File->new("$fname.subscription")) {
8167: while (my $subline=<$sh>) {
8168: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
8169: }
8170: $sh->close();
8171: }
8172: $sh=IO::File->new(">$fname.subscription");
8173: if ($contents) { print $sh $contents; }
8174: if ($newline) { print $sh $newline; }
8175: $sh->close();
8176: return $found;
1.86 www 8177: }
8178:
1.234 foxr 8179: sub get_chat {
1.324 raeburn 8180: my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310 albertel 8181:
1.87 www 8182: my @entries=();
1.324 raeburn 8183: my $namespace = 'nohist_chatroom';
8184: my $namespace_inroom = 'nohist_inchatroom';
1.335 albertel 8185: if ($group ne '') {
1.324 raeburn 8186: $namespace .= '_'.$group;
8187: $namespace_inroom .= '_'.$group;
8188: }
8189: my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310 albertel 8190: &GDBM_READER());
8191: if ($hashref) {
8192: @entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311 albertel 8193: &untie_user_hash($hashref);
1.123 www 8194: }
1.124 www 8195: my @participants=();
1.134 albertel 8196: my $cutoff=time-60;
1.324 raeburn 8197: $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310 albertel 8198: &GDBM_WRCREAT());
8199: if ($hashref) {
8200: $hashref->{$uname.':'.$udom}=time;
8201: foreach my $user (sort(keys(%$hashref))) {
8202: if ($hashref->{$user}>$cutoff) {
8203: push(@participants, 'active_participant:'.$user);
1.123 www 8204: }
8205: }
1.311 albertel 8206: &untie_user_hash($hashref);
1.86 www 8207: }
1.124 www 8208: return (@participants,@entries);
1.86 www 8209: }
8210:
1.234 foxr 8211: sub chat_add {
1.324 raeburn 8212: my ($cdom,$cname,$newchat,$group)=@_;
1.88 albertel 8213: my @entries=();
1.142 www 8214: my $time=time;
1.324 raeburn 8215: my $namespace = 'nohist_chatroom';
8216: my $logfile = 'chatroom.log';
1.335 albertel 8217: if ($group ne '') {
1.324 raeburn 8218: $namespace .= '_'.$group;
8219: $logfile = 'chatroom_'.$group.'.log';
8220: }
8221: my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310 albertel 8222: &GDBM_WRCREAT());
8223: if ($hashref) {
8224: @entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88 albertel 8225: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
8226: my ($thentime,$idnum)=split(/\_/,$lastid);
8227: my $newid=$time.'_000000';
8228: if ($thentime==$time) {
8229: $idnum=~s/^0+//;
8230: $idnum++;
8231: $idnum=substr('000000'.$idnum,-6,6);
8232: $newid=$time.'_'.$idnum;
8233: }
1.310 albertel 8234: $hashref->{$newid}=$newchat;
1.88 albertel 8235: my $expired=$time-3600;
1.310 albertel 8236: foreach my $comment (keys(%$hashref)) {
8237: my ($thistime) = ($comment=~/(\d+)\_/);
1.88 albertel 8238: if ($thistime<$expired) {
1.310 albertel 8239: delete $hashref->{$comment};
1.88 albertel 8240: }
8241: }
1.310 albertel 8242: {
8243: my $proname=&propath($cdom,$cname);
1.324 raeburn 8244: if (open(CHATLOG,">>$proname/$logfile")) {
1.310 albertel 8245: print CHATLOG ("$time:".&unescape($newchat)."\n");
8246: }
8247: close(CHATLOG);
1.142 www 8248: }
1.311 albertel 8249: &untie_user_hash($hashref);
1.86 www 8250: }
1.84 albertel 8251: }
8252:
8253: sub unsub {
8254: my ($fname,$clientip)=@_;
8255: my $result;
1.188 foxr 8256: my $unsubs = 0; # Number of successful unsubscribes:
8257:
8258:
8259: # An old way subscriptions were handled was to have a
8260: # subscription marker file:
8261:
8262: Debug("Attempting unlink of $fname.$clientname");
1.161 foxr 8263: if (unlink("$fname.$clientname")) {
1.188 foxr 8264: $unsubs++; # Successful unsub via marker file.
8265: }
8266:
8267: # The more modern way to do it is to have a subscription list
8268: # file:
8269:
1.84 albertel 8270: if (-e "$fname.subscription") {
1.161 foxr 8271: my $found=&addline($fname,$clientname,$clientip,'');
1.188 foxr 8272: if ($found) {
8273: $unsubs++;
8274: }
8275: }
8276:
8277: # If either or both of these mechanisms succeeded in unsubscribing a
8278: # resource we can return ok:
8279:
8280: if($unsubs) {
8281: $result = "ok\n";
1.84 albertel 8282: } else {
1.188 foxr 8283: $result = "not_subscribed\n";
1.84 albertel 8284: }
1.188 foxr 8285:
1.84 albertel 8286: return $result;
8287: }
8288:
1.101 www 8289: sub currentversion {
8290: my $fname=shift;
8291: my $version=-1;
8292: my $ulsdir='';
8293: if ($fname=~/^(.+)\/[^\/]+$/) {
8294: $ulsdir=$1;
8295: }
1.114 albertel 8296: my ($fnamere1,$fnamere2);
8297: # remove version if already specified
1.101 www 8298: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 8299: # get the bits that go before and after the version number
8300: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
8301: $fnamere1=$1;
8302: $fnamere2='.'.$2;
8303: }
1.101 www 8304: if (-e $fname) { $version=1; }
8305: if (-e $ulsdir) {
1.134 albertel 8306: if(-d $ulsdir) {
8307: if (opendir(LSDIR,$ulsdir)) {
1.489.2.43.2. 0(raebur 8308:3): if (-e $fname) {
8309:3): $version=0;
8310:3): }
1.134 albertel 8311: my $ulsfn;
8312: while ($ulsfn=readdir(LSDIR)) {
1.101 www 8313: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 8314: my $thisfile=$ulsdir.'/'.$ulsfn;
8315: unless (-l $thisfile) {
1.160 www 8316: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 8317: if ($1>$version) { $version=$1; }
8318: }
8319: }
8320: }
8321: closedir(LSDIR);
8322: $version++;
8323: }
8324: }
8325: }
8326: return $version;
1.101 www 8327: }
8328:
8329: sub thisversion {
8330: my $fname=shift;
8331: my $version=-1;
8332: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
8333: $version=$1;
8334: }
8335: return $version;
8336: }
8337:
1.84 albertel 8338: sub subscribe {
8339: my ($userinput,$clientip)=@_;
8340: my $result;
1.293 albertel 8341: my ($cmd,$fname)=split(/:/,$userinput,2);
1.84 albertel 8342: my $ownership=&ishome($fname);
8343: if ($ownership eq 'owner') {
1.101 www 8344: # explitly asking for the current version?
8345: unless (-e $fname) {
8346: my $currentversion=¤tversion($fname);
8347: if (&thisversion($fname)==$currentversion) {
8348: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
8349: my $root=$1;
8350: my $extension=$2;
8351: symlink($root.'.'.$extension,
8352: $root.'.'.$currentversion.'.'.$extension);
1.102 www 8353: unless ($extension=~/\.meta$/) {
8354: symlink($root.'.'.$extension.'.meta',
8355: $root.'.'.$currentversion.'.'.$extension.'.meta');
8356: }
1.101 www 8357: }
8358: }
8359: }
1.84 albertel 8360: if (-e $fname) {
8361: if (-d $fname) {
8362: $result="directory\n";
8363: } else {
1.161 foxr 8364: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 8365: my $now=time;
1.161 foxr 8366: my $found=&addline($fname,$clientname,$clientip,
8367: "$clientname:$clientip:$now\n");
1.84 albertel 8368: if ($found) { $result="$fname\n"; }
8369: # if they were subscribed to only meta data, delete that
8370: # subscription, when you subscribe to a file you also get
8371: # the metadata
8372: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
8373: $fname=~s/\/home\/httpd\/html\/res/raw/;
1.476 raeburn 8374: my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
8375: $protocol = 'http' if ($protocol ne 'https');
8376: $fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84 albertel 8377: $result="$fname\n";
8378: }
8379: } else {
8380: $result="not_found\n";
8381: }
8382: } else {
8383: $result="rejected\n";
8384: }
8385: return $result;
8386: }
1.287 foxr 8387: # Change the passwd of a unix user. The caller must have
8388: # first verified that the user is a loncapa user.
8389: #
8390: # Parameters:
8391: # user - Unix user name to change.
8392: # pass - New password for the user.
8393: # Returns:
8394: # ok - if success
8395: # other - Some meaningfule error message string.
8396: # NOTE:
8397: # invokes a setuid script to change the passwd.
8398: sub change_unix_password {
8399: my ($user, $pass) = @_;
8400:
8401: &Debug("change_unix_password");
8402: my $execdir=$perlvar{'lonDaemons'};
8403: &Debug("Opening lcpasswd pipeline");
8404: my $pf = IO::File->new("|$execdir/lcpasswd > "
8405: ."$perlvar{'lonDaemons'}"
8406: ."/logs/lcpasswd.log");
8407: print $pf "$user\n$pass\n$pass\n";
8408: close $pf;
8409: my $err = $?;
8410: return ($err < @passwderrors) ? $passwderrors[$err] :
8411: "pwchange_falure - unknown error";
8412:
8413:
8414: }
8415:
1.91 albertel 8416:
8417: sub make_passwd_file {
1.489.2.21 raeburn 8418: my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390 raeburn 8419: my $result="ok";
1.91 albertel 8420: if ($umode eq 'krb4' or $umode eq 'krb5') {
8421: {
8422: my $pf = IO::File->new(">$passfilename");
1.261 foxr 8423: if ($pf) {
8424: print $pf "$umode:$npass\n";
1.489.2.21 raeburn 8425: &update_passwd_history($uname,$udom,$umode,$action);
1.261 foxr 8426: } else {
8427: $result = "pass_file_failed_error";
8428: }
1.91 albertel 8429: }
8430: } elsif ($umode eq 'internal') {
1.489.2.21 raeburn 8431: my $ncpass = &hash_passwd($udom,$npass);
1.91 albertel 8432: {
8433: &Debug("Creating internal auth");
8434: my $pf = IO::File->new(">$passfilename");
1.261 foxr 8435: if($pf) {
8436: print $pf "internal:$ncpass\n";
1.489.2.21 raeburn 8437: &update_passwd_history($uname,$udom,$umode,$action);
1.261 foxr 8438: } else {
8439: $result = "pass_file_failed_error";
8440: }
1.91 albertel 8441: }
8442: } elsif ($umode eq 'localauth') {
8443: {
8444: my $pf = IO::File->new(">$passfilename");
1.261 foxr 8445: if($pf) {
8446: print $pf "localauth:$npass\n";
1.489.2.21 raeburn 8447: &update_passwd_history($uname,$udom,$umode,$action);
1.261 foxr 8448: } else {
8449: $result = "pass_file_failed_error";
8450: }
1.91 albertel 8451: }
8452: } elsif ($umode eq 'unix') {
1.489.2.8 raeburn 8453: &logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
8454: $result="no_new_unix_accounts";
1.91 albertel 8455: } elsif ($umode eq 'none') {
8456: {
1.223 foxr 8457: my $pf = IO::File->new("> $passfilename");
1.261 foxr 8458: if($pf) {
8459: print $pf "none:\n";
8460: } else {
8461: $result = "pass_file_failed_error";
8462: }
1.91 albertel 8463: }
8464: } else {
1.390 raeburn 8465: $result="auth_mode_error";
1.91 albertel 8466: }
8467: return $result;
1.121 albertel 8468: }
8469:
1.265 albertel 8470: sub convert_photo {
8471: my ($start,$dest)=@_;
8472: system("convert $start $dest");
8473: }
8474:
1.121 albertel 8475: sub sethost {
8476: my ($remotereq) = @_;
8477: my (undef,$hostid)=split(/:/,$remotereq);
1.322 albertel 8478: # ignore sethost if we are already correct
8479: if ($hostid eq $currenthostid) {
8480: return 'ok';
8481: }
8482:
1.121 albertel 8483: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368 albertel 8484: if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'})
8485: eq &Apache::lonnet::get_host_ip($hostid)) {
1.200 matthew 8486: $currenthostid =$hostid;
1.369 albertel 8487: $currentdomainid=&Apache::lonnet::host_domain($hostid);
1.443 www 8488: # &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121 albertel 8489: } else {
8490: &logthis("Requested host id $hostid not an alias of ".
8491: $perlvar{'lonHostID'}." refusing connection");
8492: return 'unable_to_set';
8493: }
8494: return 'ok';
8495: }
8496:
8497: sub version {
8498: my ($userinput)=@_;
8499: $remoteVERSION=(split(/:/,$userinput))[1];
8500: return "version:$VERSION";
1.127 albertel 8501: }
1.178 foxr 8502:
1.447 raeburn 8503: sub get_usersession_config {
8504: my ($dom,$name) = @_;
8505: my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
8506: if (defined($cached)) {
8507: return $usersessionconf;
8508: } else {
8509: my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
8510: if (ref($domconfig{'usersessions'}) eq 'HASH') {
8511: &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
8512: return $domconfig{'usersessions'};
8513: }
8514: }
8515: return;
8516: }
1.200 matthew 8517:
1.489.2.27 raeburn 8518: sub get_usersearch_config {
8519: my ($dom,$name) = @_;
8520: my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
8521: if (defined($cached)) {
8522: return $usersearchconf;
8523: } else {
8524: my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
8525: &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},3600);
8526: return $domconfig{'directorysrch'};
8527: }
8528: return;
8529: }
1.450 raeburn 8530:
1.471 raeburn 8531: sub distro_and_arch {
8532: return $dist.':'.$arch;
8533: }
8534:
1.61 harris41 8535: # ----------------------------------- POD (plain old documentation, CPAN style)
8536:
8537: =head1 NAME
8538:
8539: lond - "LON Daemon" Server (port "LOND" 5663)
8540:
8541: =head1 SYNOPSIS
8542:
1.74 harris41 8543: Usage: B<lond>
8544:
8545: Should only be run as user=www. This is a command-line script which
8546: is invoked by B<loncron>. There is no expectation that a typical user
8547: will manually start B<lond> from the command-line. (In other words,
8548: DO NOT START B<lond> YOURSELF.)
1.61 harris41 8549:
8550: =head1 DESCRIPTION
8551:
1.74 harris41 8552: There are two characteristics associated with the running of B<lond>,
8553: PROCESS MANAGEMENT (starting, stopping, handling child processes)
8554: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
8555: subscriptions, etc). These are described in two large
8556: sections below.
8557:
8558: B<PROCESS MANAGEMENT>
8559:
1.61 harris41 8560: Preforker - server who forks first. Runs as a daemon. HUPs.
8561: Uses IDEA encryption
8562:
1.74 harris41 8563: B<lond> forks off children processes that correspond to the other servers
8564: in the network. Management of these processes can be done at the
8565: parent process level or the child process level.
8566:
8567: B<logs/lond.log> is the location of log messages.
8568:
8569: The process management is now explained in terms of linux shell commands,
8570: subroutines internal to this code, and signal assignments:
8571:
8572: =over 4
8573:
8574: =item *
8575:
8576: PID is stored in B<logs/lond.pid>
8577:
8578: This is the process id number of the parent B<lond> process.
8579:
8580: =item *
8581:
8582: SIGTERM and SIGINT
8583:
8584: Parent signal assignment:
8585: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
8586:
8587: Child signal assignment:
8588: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
8589: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
8590: to restart a new child.)
8591:
8592: Command-line invocations:
8593: B<kill> B<-s> SIGTERM I<PID>
8594: B<kill> B<-s> SIGINT I<PID>
8595:
8596: Subroutine B<HUNTSMAN>:
8597: This is only invoked for the B<lond> parent I<PID>.
8598: This kills all the children, and then the parent.
8599: The B<lonc.pid> file is cleared.
8600:
8601: =item *
8602:
8603: SIGHUP
8604:
8605: Current bug:
8606: This signal can only be processed the first time
8607: on the parent process. Subsequent SIGHUP signals
8608: have no effect.
8609:
8610: Parent signal assignment:
8611: $SIG{HUP} = \&HUPSMAN;
8612:
8613: Child signal assignment:
8614: none (nothing happens)
8615:
8616: Command-line invocations:
8617: B<kill> B<-s> SIGHUP I<PID>
8618:
8619: Subroutine B<HUPSMAN>:
8620: This is only invoked for the B<lond> parent I<PID>,
8621: This kills all the children, and then the parent.
8622: The B<lond.pid> file is cleared.
8623:
8624: =item *
8625:
8626: SIGUSR1
8627:
8628: Parent signal assignment:
8629: $SIG{USR1} = \&USRMAN;
8630:
8631: Child signal assignment:
8632: $SIG{USR1}= \&logstatus;
8633:
8634: Command-line invocations:
8635: B<kill> B<-s> SIGUSR1 I<PID>
8636:
8637: Subroutine B<USRMAN>:
8638: When invoked for the B<lond> parent I<PID>,
8639: SIGUSR1 is sent to all the children, and the status of
8640: each connection is logged.
1.144 foxr 8641:
8642: =item *
8643:
8644: SIGUSR2
8645:
8646: Parent Signal assignment:
8647: $SIG{USR2} = \&UpdateHosts
8648:
8649: Child signal assignment:
8650: NONE
8651:
1.74 harris41 8652:
8653: =item *
8654:
8655: SIGCHLD
8656:
8657: Parent signal assignment:
8658: $SIG{CHLD} = \&REAPER;
8659:
8660: Child signal assignment:
8661: none
8662:
8663: Command-line invocations:
8664: B<kill> B<-s> SIGCHLD I<PID>
8665:
8666: Subroutine B<REAPER>:
8667: This is only invoked for the B<lond> parent I<PID>.
8668: Information pertaining to the child is removed.
8669: The socket port is cleaned up.
8670:
8671: =back
8672:
8673: B<SERVER-SIDE ACTIVITIES>
8674:
8675: Server-side information can be accepted in an encrypted or non-encrypted
8676: method.
8677:
8678: =over 4
8679:
8680: =item ping
8681:
8682: Query a client in the hosts.tab table; "Are you there?"
8683:
8684: =item pong
8685:
8686: Respond to a ping query.
8687:
8688: =item ekey
8689:
8690: Read in encrypted key, make cipher. Respond with a buildkey.
8691:
8692: =item load
8693:
8694: Respond with CPU load based on a computation upon /proc/loadavg.
8695:
8696: =item currentauth
8697:
8698: Reply with current authentication information (only over an
8699: encrypted channel).
8700:
8701: =item auth
8702:
8703: Only over an encrypted channel, reply as to whether a user's
8704: authentication information can be validated.
8705:
8706: =item passwd
8707:
8708: Allow for a password to be set.
8709:
8710: =item makeuser
8711:
8712: Make a user.
8713:
8714: =item passwd
8715:
8716: Allow for authentication mechanism and password to be changed.
8717:
8718: =item home
1.61 harris41 8719:
1.74 harris41 8720: Respond to a question "are you the home for a given user?"
8721:
8722: =item update
8723:
8724: Update contents of a subscribed resource.
8725:
8726: =item unsubscribe
8727:
8728: The server is unsubscribing from a resource.
8729:
8730: =item subscribe
8731:
8732: The server is subscribing to a resource.
8733:
8734: =item log
8735:
8736: Place in B<logs/lond.log>
8737:
8738: =item put
8739:
8740: stores hash in namespace
8741:
1.489.2.2 raeburn 8742: =item rolesput
1.74 harris41 8743:
8744: put a role into a user's environment
8745:
8746: =item get
8747:
8748: returns hash with keys from array
8749: reference filled in from namespace
8750:
8751: =item eget
8752:
8753: returns hash with keys from array
8754: reference filled in from namesp (encrypts the return communication)
8755:
8756: =item rolesget
8757:
8758: get a role from a user's environment
8759:
8760: =item del
8761:
8762: deletes keys out of array from namespace
8763:
8764: =item keys
8765:
8766: returns namespace keys
8767:
8768: =item dump
8769:
8770: dumps the complete (or key matching regexp) namespace into a hash
8771:
8772: =item store
8773:
8774: stores hash permanently
8775: for this url; hashref needs to be given and should be a \%hashname; the
8776: remaining args aren't required and if they aren't passed or are '' they will
8777: be derived from the ENV
8778:
8779: =item restore
8780:
8781: returns a hash for a given url
8782:
8783: =item querysend
8784:
8785: Tells client about the lonsql process that has been launched in response
8786: to a sent query.
8787:
8788: =item queryreply
8789:
8790: Accept information from lonsql and make appropriate storage in temporary
8791: file space.
8792:
8793: =item idput
8794:
8795: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
8796: for each student, defined perhaps by the institutional Registrar.)
8797:
8798: =item idget
8799:
8800: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
8801: for each student, defined perhaps by the institutional Registrar.)
8802:
8803: =item tmpput
8804:
8805: Accept and store information in temporary space.
8806:
8807: =item tmpget
8808:
8809: Send along temporarily stored information.
8810:
8811: =item ls
8812:
8813: List part of a user's directory.
8814:
1.135 foxr 8815: =item pushtable
8816:
8817: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
8818: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
8819: must be restored manually in case of a problem with the new table file.
8820: pushtable requires that the request be encrypted and validated via
8821: ValidateManager. The form of the command is:
8822: enc:pushtable tablename <tablecontents> \n
8823: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
8824: cleartext newline.
8825:
1.74 harris41 8826: =item Hanging up (exit or init)
8827:
8828: What to do when a client tells the server that they (the client)
8829: are leaving the network.
8830:
8831: =item unknown command
8832:
8833: If B<lond> is sent an unknown command (not in the list above),
8834: it replys to the client "unknown_cmd".
1.135 foxr 8835:
1.74 harris41 8836:
8837: =item UNKNOWN CLIENT
8838:
8839: If the anti-spoofing algorithm cannot verify the client,
8840: the client is rejected (with a "refused" message sent
8841: to the client, and the connection is closed.
8842:
8843: =back
1.61 harris41 8844:
8845: =head1 PREREQUISITES
8846:
8847: IO::Socket
8848: IO::File
8849: Apache::File
8850: POSIX
8851: Crypt::IDEA
8852: LWP::UserAgent()
8853: GDBM_File
8854: Authen::Krb4
1.91 albertel 8855: Authen::Krb5
1.61 harris41 8856:
8857: =head1 COREQUISITES
8858:
8859: =head1 OSNAMES
8860:
8861: linux
8862:
8863: =head1 SCRIPT CATEGORIES
8864:
8865: Server/Process
8866:
8867: =cut
1.409 foxr 8868:
8869:
8870: =pod
8871:
8872: =head1 LOG MESSAGES
8873:
8874: The messages below can be emitted in the lond log. This log is located
8875: in ~httpd/perl/logs/lond.log Many log messages have HTML encapsulation
8876: to provide coloring if examined from inside a web page. Some do not.
8877: Where color is used, the colors are; Red for sometihhng to get excited
8878: about and to follow up on. Yellow for something to keep an eye on to
8879: be sure it does not get worse, Green,and Blue for informational items.
8880:
8881: In the discussions below, sometimes reference is made to ~httpd
8882: when describing file locations. There isn't really an httpd
8883: user, however there is an httpd directory that gets installed in the
8884: place that user home directories go. On linux, this is usually
8885: (always?) /home/httpd.
8886:
8887:
8888: Some messages are colorless. These are usually (not always)
8889: Green/Blue color level messages.
8890:
8891: =over 2
8892:
8893: =item (Red) LocalConnection rejecting non local: <ip> ne 127.0.0.1
8894:
8895: A local connection negotiation was attempted by
8896: a host whose IP address was not 127.0.0.1.
8897: The socket is closed and the child will exit.
8898: lond has three ways to establish an encyrption
8899: key with a client:
8900:
8901: =over 2
8902:
8903: =item local
8904:
8905: The key is written and read from a file.
8906: This is only valid for connections from localhost.
8907:
8908: =item insecure
8909:
8910: The key is generated by the server and
8911: transmitted to the client.
8912:
8913: =item ssl (secure)
8914:
8915: An ssl connection is negotiated with the client,
8916: the key is generated by the server and sent to the
8917: client across this ssl connection before the
8918: ssl connectionis terminated and clear text
8919: transmission resumes.
8920:
8921: =back
8922:
8923: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
8924:
8925: The client is local but has not sent an initialization
8926: string that is the literal "init:local" The connection
8927: is closed and the child exits.
8928:
8929: =item Red CRITICAL Can't get key file <error>
8930:
8931: SSL key negotiation is being attempted but the call to
8932: lonssl::KeyFile failed. This usually means that the
8933: configuration file is not correctly defining or protecting
8934: the directories/files lonCertificateDirectory or
8935: lonnetPrivateKey
8936: <error> is a string that describes the reason that
8937: the key file could not be located.
8938:
8939: =item (Red) CRITICAL Can't get certificates <error>
8940:
8941: SSL key negotiation failed because we were not able to retrives our certificate
8942: or the CA's certificate in the call to lonssl::CertificateFile
8943: <error> is the textual reason this failed. Usual reasons:
8944:
8945: =over 2
8946:
8947: =item Apache config file for loncapa incorrect:
8948:
8949: one of the variables
8950: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
8951: undefined or incorrect
8952:
8953: =item Permission error:
8954:
8955: The directory pointed to by lonCertificateDirectory is not readable by lond
8956:
8957: =item Permission error:
8958:
8959: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
8960:
8961: =item Installation error:
8962:
8963: Either the certificate authority file or the certificate have not
8964: been installed in lonCertificateDirectory.
8965:
8966: =item (Red) CRITICAL SSL Socket promotion failed: <err>
8967:
8968: The promotion of the connection from plaintext to SSL failed
8969: <err> is the reason for the failure. There are two
8970: system calls involved in the promotion (one of which failed),
8971: a dup to produce
8972: a second fd on the raw socket over which the encrypted data
8973: will flow and IO::SOcket::SSL->new_from_fd which creates
8974: the SSL connection on the duped fd.
8975:
8976: =item (Blue) WARNING client did not respond to challenge
8977:
8978: This occurs on an insecure (non SSL) connection negotiation request.
8979: lond generates some number from the time, the PID and sends it to
8980: the client. The client must respond by echoing this information back.
8981: If the client does not do so, that's a violation of the challenge
8982: protocols and the connection will be failed.
8983:
8984: =item (Red) No manager table. Nobody can manage!!
8985:
8986: lond has the concept of privileged hosts that
8987: can perform remote management function such
8988: as update the hosts.tab. The manager hosts
8989: are described in the
8990: ~httpd/lonTabs/managers.tab file.
8991: this message is logged if this file is missing.
8992:
8993:
8994: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
8995:
8996: Reports the successful parse and registration
8997: of a specific manager.
8998:
8999: =item Green existing host <clustername:dnsname>
9000:
9001: The manager host is already defined in the hosts.tab
9002: the information in that table, rather than the info in the
9003: manager table will be used to determine the manager's ip.
9004:
9005: =item (Red) Unable to craete <filename>
9006:
9007: lond has been asked to create new versions of an administrative
9008: file (by a manager). When this is done, the new file is created
9009: in a temp file and then renamed into place so that there are always
9010: usable administrative files, even if the update fails. This failure
9011: message means that the temp file could not be created.
9012: The update is abandoned, and the old file is available for use.
9013:
9014: =item (Green) CopyFile from <oldname> to <newname> failed
9015:
9016: In an update of administrative files, the copy of the existing file to a
9017: backup file failed. The installation of the new file may still succeed,
9018: but there will not be a back up file to rever to (this should probably
9019: be yellow).
9020:
9021: =item (Green) Pushfile: backed up <oldname> to <newname>
9022:
9023: See above, the backup of the old administrative file succeeded.
9024:
9025: =item (Red) Pushfile: Unable to install <filename> <reason>
9026:
9027: The new administrative file could not be installed. In this case,
9028: the old administrative file is still in use.
9029:
9030: =item (Green) Installed new < filename>.
9031:
9032: The new administrative file was successfullly installed.
9033:
9034: =item (Red) Reinitializing lond pid=<pid>
9035:
9036: The lonc child process <pid> will be sent a USR2
9037: signal.
9038:
9039: =item (Red) Reinitializing self
9040:
9041: We've been asked to re-read our administrative files,and
9042: are doing so.
9043:
9044: =item (Yellow) error:Invalid process identifier <ident>
9045:
9046: A reinit command was received, but the target part of the
9047: command was not valid. It must be either
9048: 'lond' or 'lonc' but was <ident>
9049:
9050: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
9051:
9052: Checking to see if lond has been handed a valid edit
9053: command. It is possible the edit command is not valid
9054: in that case there are no log messages to indicate that.
9055:
9056: =item Result of password change for <username> pwchange_success
9057:
9058: The password for <username> was
9059: successfully changed.
9060:
9061: =item Unable to open <user> passwd to change password
9062:
9063: Could not rewrite the
9064: internal password file for a user
9065:
9066: =item Result of password change for <user> : <result>
9067:
9068: A unix password change for <user> was attempted
9069: and the pipe returned <result>
9070:
9071: =item LWP GET: <message> for <fname> (<remoteurl>)
9072:
9073: The lightweight process fetch for a resource failed
9074: with <message> the local filename that should
9075: have existed/been created was <fname> the
9076: corresponding URI: <remoteurl> This is emitted in several
9077: places.
9078:
9079: =item Unable to move <transname> to <destname>
9080:
9081: From fetch_user_file_handler - the user file was replicated but could not
9082: be mv'd to its final location.
9083:
9084: =item Looking for <domain> <username>
9085:
9086: From user_has_session_handler - This should be a Debug call instead
9087: it indicates lond is about to check whether the specified user has a
9088: session active on the specified domain on the local host.
9089:
9090: =item Client <ip> (<name>) hanging up: <input>
9091:
9092: lond has been asked to exit by its client. The <ip> and <name> identify the
9093: client systemand <input> is the full exit command sent to the server.
9094:
9095: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
9096:
9097: A lond child terminated. NOte that this termination can also occur when the
9098: child receives the QUIT or DIE signals. <pid> is the process id of the child,
9099: <hostname> the host lond is working for, and <message> the reason the child died
9100: to the best of our ability to get it (I would guess that any numeric value
9101: represents and errno value). This is immediately followed by
9102:
9103: =item Famous last words: Catching exception - <log>
9104:
9105: Where log is some recent information about the state of the child.
9106:
9107: =item Red CRITICAL: TIME OUT <pid>
9108:
9109: Some timeout occured for server <pid>. THis is normally a timeout on an LWP
9110: doing an HTTP::GET.
9111:
9112: =item child <pid> died
9113:
9114: The reaper caught a SIGCHILD for the lond child process <pid>
9115: This should be modified to also display the IP of the dying child
9116: $children{$pid}
9117:
9118: =item Unknown child 0 died
9119: A child died but the wait for it returned a pid of zero which really should not
9120: ever happen.
9121:
9122: =item Child <which> - <pid> looks like we missed it's death
9123:
9124: When a sigchild is received, the reaper process checks all children to see if they are
9125: alive. If children are dying quite quickly, the lack of signal queuing can mean
9126: that a signal hearalds the death of more than one child. If so this message indicates
9127: which other one died. <which> is the ip of a dead child
9128:
9129: =item Free socket: <shutdownretval>
9130:
9131: The HUNTSMAN sub was called due to a SIGINT in a child process. The socket is being shutdown.
9132: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
9133: to return anything. This is followed by:
9134:
9135: =item Red CRITICAL: Shutting down
9136:
9137: Just prior to exit.
9138:
9139: =item Free socket: <shutdownretval>
9140:
9141: The HUPSMAN sub was called due to a SIGHUP. all children get killsed, and lond execs itself.
9142: This is followed by:
9143:
9144: =item (Red) CRITICAL: Restarting
9145:
9146: lond is about to exec itself to restart.
9147:
9148: =item (Blue) Updating connections
9149:
9150: (In response to a USR2). All the children (except the one for localhost)
9151: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
9152:
9153: =item (Blue) UpdateHosts killing child <pid> for ip <ip>
9154:
9155: Due to USR2 as above.
9156:
9157: =item (Green) keeping child for ip <ip> (pid = <pid>)
9158:
9159: In response to USR2 as above, the child indicated is not being restarted because
9160: it's assumed that we'll always need a child for the localhost.
9161:
9162:
9163: =item Going to check on the children
9164:
9165: Parent is about to check on the health of the child processes.
9166: Note that this is in response to a USR1 sent to the parent lond.
9167: there may be one or more of the next two messages:
9168:
9169: =item <pid> is dead
9170:
9171: A child that we have in our child hash as alive has evidently died.
9172:
9173: =item Child <pid> did not respond
9174:
9175: In the health check the child <pid> did not update/produce a pid_.txt
9176: file when sent it's USR1 signal. That process is killed with a 9 signal, as it's
9177: assumed to be hung in some un-fixable way.
9178:
9179: =item Finished checking children
9180:
9181: Master processs's USR1 processing is cojmplete.
9182:
9183: =item (Red) CRITICAL: ------- Starting ------
9184:
9185: (There are more '-'s on either side). Lond has forked itself off to
9186: form a new session and is about to start actual initialization.
9187:
9188: =item (Green) Attempting to start child (<client>)
9189:
9190: Started a new child process for <client>. Client is IO::Socket object
9191: connected to the child. This was as a result of a TCP/IP connection from a client.
9192:
9193: =item Unable to determine who caller was, getpeername returned nothing
9194:
9195: In child process initialization. either getpeername returned undef or
9196: a zero sized object was returned. Processing continues, but in my opinion,
9197: this should be cause for the child to exit.
9198:
9199: =item Unable to determine clientip
9200:
9201: In child process initialization. The peer address from getpeername was not defined.
9202: The client address is stored as "Unavailable" and processing continues.
9203:
9204: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
9205:
9206: In child initialization. A good connectionw as received from <ip>.
9207:
9208: =over 2
9209:
9210: =item <name>
9211:
9212: is the name of the client from hosts.tab.
9213:
9214: =item <type>
9215:
9216: Is the connection type which is either
9217:
9218: =over 2
9219:
9220: =item manager
9221:
9222: The connection is from a manager node, not in hosts.tab
9223:
9224: =item client
9225:
9226: the connection is from a non-manager in the hosts.tab
9227:
9228: =item both
9229:
9230: The connection is from a manager in the hosts.tab.
9231:
9232: =back
9233:
9234: =back
9235:
9236: =item (Blue) Certificates not installed -- trying insecure auth
9237:
9238: One of the certificate file, key file or
9239: certificate authority file could not be found for a client attempting
9240: SSL connection intiation. COnnection will be attemptied in in-secure mode.
9241: (this would be a system with an up to date lond that has not gotten a
9242: certificate from us).
9243:
9244: =item (Green) Successful local authentication
9245:
9246: A local connection successfully negotiated the encryption key.
9247: In this case the IDEA key is in a file (that is hopefully well protected).
9248:
9249: =item (Green) Successful ssl authentication with <client>
9250:
9251: The client (<client> is the peer's name in hosts.tab), has successfully
9252: negotiated an SSL connection with this child process.
9253:
9254: =item (Green) Successful insecure authentication with <client>
9255:
9256:
9257: The client has successfully negotiated an insecure connection withthe child process.
9258:
9259: =item (Yellow) Attempted insecure connection disallowed
9260:
9261: The client attempted and failed to successfully negotiate a successful insecure
9262: connection. This can happen either because the variable londAllowInsecure is false
9263: or undefined, or becuse the child did not successfully echo back the challenge
9264: string.
9265:
9266:
9267: =back
9268:
1.441 raeburn 9269: =back
9270:
1.409 foxr 9271:
9272: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>