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