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