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