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