Annotation of loncom/lond, revision 1.297
1.1 albertel 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60 www 4: #
1.297 ! raeburn 5: # $Id: lond,v 1.296 2005/09/01 07:49:43 albertel Exp $
1.60 www 6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
1.167 foxr 13: # the Free Software Foundation; either version 2 of the License, or
1.60 www 14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
1.178 foxr 23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1.60 www 24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
1.161 foxr 27:
28:
1.60 www 29: # http://www.lon-capa.org/
30: #
1.54 harris41 31:
1.134 albertel 32: use strict;
1.80 harris41 33: use lib '/home/httpd/lib/perl/';
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.297 ! raeburn 62: my $VERSION='$Revision: 1.296 $'; #' 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);
1976: }
1977: }
1978: &Reply( $client, "ok\n", $userinput);
1979: } else {
1980: &Failure($client, "not_found\n", $userinput);
1981: }
1982: } else {
1983: &Failure($client, "rejected\n", $userinput);
1984: }
1985: return 1;
1986: }
1987: ®ister_handler("update", \&update_resource_handler, 0 ,1, 0);
1988:
1989: #
1.226 foxr 1990: # Fetch a user file from a remote server to the user's home directory
1991: # userfiles subdir.
1.225 foxr 1992: # Parameters:
1993: # $cmd - The command that got us here.
1994: # $tail - Tail of the command (remaining parameters).
1995: # $client - File descriptor connected to client.
1996: # Returns
1997: # 0 - Requested to exit, caller should shut down.
1998: # 1 - Continue processing.
1999: #
2000: sub fetch_user_file_handler {
2001:
2002: my ($cmd, $tail, $client) = @_;
2003:
2004: my $userinput = "$cmd:$tail";
2005: my $fname = $tail;
1.232 foxr 2006: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225 foxr 2007: my $udir=&propath($udom,$uname).'/userfiles';
2008: unless (-e $udir) {
2009: mkdir($udir,0770);
2010: }
1.232 foxr 2011: Debug("fetch user file for $fname");
1.225 foxr 2012: if (-e $udir) {
2013: $ufile=~s/^[\.\~]+//;
1.232 foxr 2014:
2015: # IF necessary, create the path right down to the file.
2016: # Note that any regular files in the way of this path are
2017: # wiped out to deal with some earlier folly of mine.
2018:
1.267 raeburn 2019: if (!&mkpath($udir.'/'.$ufile)) {
1.264 albertel 2020: &Failure($client, "unable_to_create\n", $userinput);
1.232 foxr 2021: }
2022:
1.225 foxr 2023: my $destname=$udir.'/'.$ufile;
2024: my $transname=$udir.'/'.$ufile.'.in.transit';
2025: my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
2026: my $response;
1.232 foxr 2027: Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.225 foxr 2028: alarm(120);
2029: {
2030: my $ua=new LWP::UserAgent;
2031: my $request=new HTTP::Request('GET',"$remoteurl");
2032: $response=$ua->request($request,$transname);
2033: }
2034: alarm(0);
2035: if ($response->is_error()) {
2036: unlink($transname);
2037: my $message=$response->status_line;
2038: &logthis("LWP GET: $message for $fname ($remoteurl)");
2039: &Failure($client, "failed\n", $userinput);
2040: } else {
1.232 foxr 2041: Debug("Renaming $transname to $destname");
1.225 foxr 2042: if (!rename($transname,$destname)) {
2043: &logthis("Unable to move $transname to $destname");
2044: unlink($transname);
2045: &Failure($client, "failed\n", $userinput);
2046: } else {
2047: &Reply($client, "ok\n", $userinput);
2048: }
2049: }
2050: } else {
2051: &Failure($client, "not_home\n", $userinput);
2052: }
2053: return 1;
2054: }
2055: ®ister_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
2056:
1.226 foxr 2057: #
2058: # Remove a file from a user's home directory userfiles subdirectory.
2059: # Parameters:
2060: # cmd - the Lond request keyword that got us here.
2061: # tail - the part of the command past the keyword.
2062: # client- File descriptor connected with the client.
2063: #
2064: # Returns:
2065: # 1 - Continue processing.
2066: sub remove_user_file_handler {
2067: my ($cmd, $tail, $client) = @_;
2068:
2069: my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2070:
2071: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2072: if ($ufile =~m|/\.\./|) {
2073: # any files paths with /../ in them refuse
2074: # to deal with
2075: &Failure($client, "refused\n", "$cmd:$tail");
2076: } else {
2077: my $udir = &propath($udom,$uname);
2078: if (-e $udir) {
2079: my $file=$udir.'/userfiles/'.$ufile;
2080: if (-e $file) {
1.253 foxr 2081: #
2082: # If the file is a regular file unlink is fine...
2083: # However it's possible the client wants a dir.
2084: # removed, in which case rmdir is more approprate:
2085: #
1.240 banghart 2086: if (-f $file){
1.241 albertel 2087: unlink($file);
2088: } elsif(-d $file) {
2089: rmdir($file);
1.240 banghart 2090: }
1.226 foxr 2091: if (-e $file) {
1.253 foxr 2092: # File is still there after we deleted it ?!?
2093:
1.226 foxr 2094: &Failure($client, "failed\n", "$cmd:$tail");
2095: } else {
2096: &Reply($client, "ok\n", "$cmd:$tail");
2097: }
2098: } else {
2099: &Failure($client, "not_found\n", "$cmd:$tail");
2100: }
2101: } else {
2102: &Failure($client, "not_home\n", "$cmd:$tail");
2103: }
2104: }
2105: return 1;
2106: }
2107: ®ister_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
2108:
1.236 albertel 2109: #
2110: # make a directory in a user's home directory userfiles subdirectory.
2111: # Parameters:
2112: # cmd - the Lond request keyword that got us here.
2113: # tail - the part of the command past the keyword.
2114: # client- File descriptor connected with the client.
2115: #
2116: # Returns:
2117: # 1 - Continue processing.
2118: sub mkdir_user_file_handler {
2119: my ($cmd, $tail, $client) = @_;
2120:
2121: my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2122: $dir=&unescape($dir);
2123: my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
2124: if ($ufile =~m|/\.\./|) {
2125: # any files paths with /../ in them refuse
2126: # to deal with
2127: &Failure($client, "refused\n", "$cmd:$tail");
2128: } else {
2129: my $udir = &propath($udom,$uname);
2130: if (-e $udir) {
1.264 albertel 2131: my $newdir=$udir.'/userfiles/'.$ufile.'/';
2132: if (!&mkpath($newdir)) {
2133: &Failure($client, "failed\n", "$cmd:$tail");
1.236 albertel 2134: }
1.264 albertel 2135: &Reply($client, "ok\n", "$cmd:$tail");
1.236 albertel 2136: } else {
2137: &Failure($client, "not_home\n", "$cmd:$tail");
2138: }
2139: }
2140: return 1;
2141: }
2142: ®ister_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
2143:
1.237 albertel 2144: #
2145: # rename a file in a user's home directory userfiles subdirectory.
2146: # Parameters:
2147: # cmd - the Lond request keyword that got us here.
2148: # tail - the part of the command past the keyword.
2149: # client- File descriptor connected with the client.
2150: #
2151: # Returns:
2152: # 1 - Continue processing.
2153: sub rename_user_file_handler {
2154: my ($cmd, $tail, $client) = @_;
2155:
2156: my ($udom,$uname,$old,$new) = split(/:/, $tail);
2157: $old=&unescape($old);
2158: $new=&unescape($new);
2159: if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
2160: # any files paths with /../ in them refuse to deal with
2161: &Failure($client, "refused\n", "$cmd:$tail");
2162: } else {
2163: my $udir = &propath($udom,$uname);
2164: if (-e $udir) {
2165: my $oldfile=$udir.'/userfiles/'.$old;
2166: my $newfile=$udir.'/userfiles/'.$new;
2167: if (-e $newfile) {
2168: &Failure($client, "exists\n", "$cmd:$tail");
2169: } elsif (! -e $oldfile) {
2170: &Failure($client, "not_found\n", "$cmd:$tail");
2171: } else {
2172: if (!rename($oldfile,$newfile)) {
2173: &Failure($client, "failed\n", "$cmd:$tail");
2174: } else {
2175: &Reply($client, "ok\n", "$cmd:$tail");
2176: }
2177: }
2178: } else {
2179: &Failure($client, "not_home\n", "$cmd:$tail");
2180: }
2181: }
2182: return 1;
2183: }
2184: ®ister_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
2185:
1.227 foxr 2186: #
1.263 albertel 2187: # Authenticate access to a user file by checking that the token the user's
2188: # passed also exists in their session file
1.227 foxr 2189: #
2190: # Parameters:
2191: # cmd - The request keyword that dispatched to tus.
2192: # tail - The tail of the request (colon separated parameters).
2193: # client - Filehandle open on the client.
2194: # Return:
2195: # 1.
2196: sub token_auth_user_file_handler {
2197: my ($cmd, $tail, $client) = @_;
2198:
2199: my ($fname, $session) = split(/:/, $tail);
2200:
2201: chomp($session);
1.251 foxr 2202: my $reply="non_auth\n";
1.227 foxr 2203: if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
2204: $session.'.id')) {
2205: while (my $line=<ENVIN>) {
1.251 foxr 2206: if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply="ok\n"; }
1.227 foxr 2207: }
2208: close(ENVIN);
1.251 foxr 2209: &Reply($client, $reply, "$cmd:$tail");
1.227 foxr 2210: } else {
2211: &Failure($client, "invalid_token\n", "$cmd:$tail");
2212: }
2213: return 1;
2214:
2215: }
2216: ®ister_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229 foxr 2217:
2218: #
2219: # Unsubscribe from a resource.
2220: #
2221: # Parameters:
2222: # $cmd - The command that got us here.
2223: # $tail - Tail of the command (remaining parameters).
2224: # $client - File descriptor connected to client.
2225: # Returns
2226: # 0 - Requested to exit, caller should shut down.
2227: # 1 - Continue processing.
2228: #
2229: sub unsubscribe_handler {
2230: my ($cmd, $tail, $client) = @_;
2231:
2232: my $userinput= "$cmd:$tail";
2233:
2234: my ($fname) = split(/:/,$tail); # Split in case there's extrs.
2235:
2236: &Debug("Unsubscribing $fname");
2237: if (-e $fname) {
2238: &Debug("Exists");
2239: &Reply($client, &unsub($fname,$clientip), $userinput);
2240: } else {
2241: &Failure($client, "not_found\n", $userinput);
2242: }
2243: return 1;
2244: }
2245: ®ister_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263 albertel 2246:
1.230 foxr 2247: # Subscribe to a resource
2248: #
2249: # Parameters:
2250: # $cmd - The command that got us here.
2251: # $tail - Tail of the command (remaining parameters).
2252: # $client - File descriptor connected to client.
2253: # Returns
2254: # 0 - Requested to exit, caller should shut down.
2255: # 1 - Continue processing.
2256: #
2257: sub subscribe_handler {
2258: my ($cmd, $tail, $client)= @_;
2259:
2260: my $userinput = "$cmd:$tail";
2261:
2262: &Reply( $client, &subscribe($userinput,$clientip), $userinput);
2263:
2264: return 1;
2265: }
2266: ®ister_handler("sub", \&subscribe_handler, 0, 1, 0);
2267:
2268: #
2269: # Determine the version of a resource (?) Or is it return
2270: # the top version of the resource? Not yet clear from the
2271: # code in currentversion.
2272: #
2273: # Parameters:
2274: # $cmd - The command that got us here.
2275: # $tail - Tail of the command (remaining parameters).
2276: # $client - File descriptor connected to client.
2277: # Returns
2278: # 0 - Requested to exit, caller should shut down.
2279: # 1 - Continue processing.
2280: #
2281: sub current_version_handler {
2282: my ($cmd, $tail, $client) = @_;
2283:
2284: my $userinput= "$cmd:$tail";
2285:
2286: my $fname = $tail;
2287: &Reply( $client, ¤tversion($fname)."\n", $userinput);
2288: return 1;
2289:
2290: }
2291: ®ister_handler("currentversion", \¤t_version_handler, 0, 1, 0);
2292:
2293: # Make an entry in a user's activity log.
2294: #
2295: # Parameters:
2296: # $cmd - The command that got us here.
2297: # $tail - Tail of the command (remaining parameters).
2298: # $client - File descriptor connected to client.
2299: # Returns
2300: # 0 - Requested to exit, caller should shut down.
2301: # 1 - Continue processing.
2302: #
2303: sub activity_log_handler {
2304: my ($cmd, $tail, $client) = @_;
2305:
2306:
2307: my $userinput= "$cmd:$tail";
2308:
2309: my ($udom,$uname,$what)=split(/:/,$tail);
2310: chomp($what);
2311: my $proname=&propath($udom,$uname);
2312: my $now=time;
2313: my $hfh;
2314: if ($hfh=IO::File->new(">>$proname/activity.log")) {
2315: print $hfh "$now:$clientname:$what\n";
2316: &Reply( $client, "ok\n", $userinput);
2317: } else {
2318: &Failure($client, "error: ".($!+0)." IO::File->new Failed "
2319: ."while attempting log\n",
2320: $userinput);
2321: }
2322:
2323: return 1;
2324: }
1.263 albertel 2325: ®ister_handler("log", \&activity_log_handler, 0, 1, 0);
1.230 foxr 2326:
2327: #
2328: # Put a namespace entry in a user profile hash.
2329: # My druthers would be for this to be an encrypted interaction too.
2330: # anything that might be an inadvertent covert channel about either
2331: # user authentication or user personal information....
2332: #
2333: # Parameters:
2334: # $cmd - The command that got us here.
2335: # $tail - Tail of the command (remaining parameters).
2336: # $client - File descriptor connected to client.
2337: # Returns
2338: # 0 - Requested to exit, caller should shut down.
2339: # 1 - Continue processing.
2340: #
2341: sub put_user_profile_entry {
2342: my ($cmd, $tail, $client) = @_;
1.229 foxr 2343:
1.230 foxr 2344: my $userinput = "$cmd:$tail";
2345:
1.242 raeburn 2346: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230 foxr 2347: if ($namespace ne 'roles') {
2348: chomp($what);
2349: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2350: &GDBM_WRCREAT(),"P",$what);
2351: if($hashref) {
2352: my @pairs=split(/\&/,$what);
2353: foreach my $pair (@pairs) {
2354: my ($key,$value)=split(/=/,$pair);
2355: $hashref->{$key}=$value;
2356: }
2357: if (untie(%$hashref)) {
2358: &Reply( $client, "ok\n", $userinput);
2359: } else {
2360: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2361: "while attempting put\n",
2362: $userinput);
2363: }
2364: } else {
2365: &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
2366: "while attempting put\n", $userinput);
2367: }
2368: } else {
2369: &Failure( $client, "refused\n", $userinput);
2370: }
2371:
2372: return 1;
2373: }
2374: ®ister_handler("put", \&put_user_profile_entry, 0, 1, 0);
2375:
1.283 albertel 2376: # Put a piece of new data in hash, returns error if entry already exists
2377: # Parameters:
2378: # $cmd - The command that got us here.
2379: # $tail - Tail of the command (remaining parameters).
2380: # $client - File descriptor connected to client.
2381: # Returns
2382: # 0 - Requested to exit, caller should shut down.
2383: # 1 - Continue processing.
2384: #
2385: sub newput_user_profile_entry {
2386: my ($cmd, $tail, $client) = @_;
2387:
2388: my $userinput = "$cmd:$tail";
2389:
2390: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
2391: if ($namespace eq 'roles') {
2392: &Failure( $client, "refused\n", $userinput);
2393: return 1;
2394: }
2395:
2396: chomp($what);
2397:
2398: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2399: &GDBM_WRCREAT(),"N",$what);
2400: if(!$hashref) {
2401: &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
2402: "while attempting put\n", $userinput);
2403: return 1;
2404: }
2405:
2406: my @pairs=split(/\&/,$what);
2407: foreach my $pair (@pairs) {
2408: my ($key,$value)=split(/=/,$pair);
2409: if (exists($hashref->{$key})) {
2410: &Failure($client, "key_exists: ".$key."\n",$userinput);
2411: return 1;
2412: }
2413: }
2414:
2415: foreach my $pair (@pairs) {
2416: my ($key,$value)=split(/=/,$pair);
2417: $hashref->{$key}=$value;
2418: }
2419:
2420: if (untie(%$hashref)) {
2421: &Reply( $client, "ok\n", $userinput);
2422: } else {
2423: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2424: "while attempting put\n",
2425: $userinput);
2426: }
2427: return 1;
2428: }
2429: ®ister_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
2430:
1.230 foxr 2431: #
2432: # Increment a profile entry in the user history file.
2433: # The history contains keyword value pairs. In this case,
2434: # The value itself is a pair of numbers. The first, the current value
2435: # the second an increment that this function applies to the current
2436: # value.
2437: #
2438: # Parameters:
2439: # $cmd - The command that got us here.
2440: # $tail - Tail of the command (remaining parameters).
2441: # $client - File descriptor connected to client.
2442: # Returns
2443: # 0 - Requested to exit, caller should shut down.
2444: # 1 - Continue processing.
2445: #
2446: sub increment_user_value_handler {
2447: my ($cmd, $tail, $client) = @_;
2448:
2449: my $userinput = "$cmd:$tail";
2450:
2451: my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
2452: if ($namespace ne 'roles') {
2453: chomp($what);
2454: my $hashref = &tie_user_hash($udom, $uname,
2455: $namespace, &GDBM_WRCREAT(),
2456: "P",$what);
2457: if ($hashref) {
2458: my @pairs=split(/\&/,$what);
2459: foreach my $pair (@pairs) {
2460: my ($key,$value)=split(/=/,$pair);
1.284 raeburn 2461: $value = &unescape($value);
1.230 foxr 2462: # We could check that we have a number...
2463: if (! defined($value) || $value eq '') {
2464: $value = 1;
2465: }
2466: $hashref->{$key}+=$value;
1.284 raeburn 2467: if ($namespace eq 'nohist_resourcetracker') {
2468: if ($hashref->{$key} < 0) {
2469: $hashref->{$key} = 0;
2470: }
2471: }
1.230 foxr 2472: }
2473: if (untie(%$hashref)) {
2474: &Reply( $client, "ok\n", $userinput);
2475: } else {
2476: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2477: "while attempting inc\n", $userinput);
2478: }
2479: } else {
2480: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2481: "while attempting inc\n", $userinput);
2482: }
2483: } else {
2484: &Failure($client, "refused\n", $userinput);
2485: }
2486:
2487: return 1;
2488: }
2489: ®ister_handler("inc", \&increment_user_value_handler, 0, 1, 0);
2490:
2491: #
2492: # Put a new role for a user. Roles are LonCAPA's packaging of permissions.
2493: # Each 'role' a user has implies a set of permissions. Adding a new role
2494: # for a person grants the permissions packaged with that role
2495: # to that user when the role is selected.
2496: #
2497: # Parameters:
2498: # $cmd - The command string (rolesput).
2499: # $tail - The remainder of the request line. For rolesput this
2500: # consists of a colon separated list that contains:
2501: # The domain and user that is granting the role (logged).
2502: # The domain and user that is getting the role.
2503: # The roles being granted as a set of & separated pairs.
2504: # each pair a key value pair.
2505: # $client - File descriptor connected to the client.
2506: # Returns:
2507: # 0 - If the daemon should exit
2508: # 1 - To continue processing.
2509: #
2510: #
2511: sub roles_put_handler {
2512: my ($cmd, $tail, $client) = @_;
2513:
2514: my $userinput = "$cmd:$tail";
2515:
2516: my ( $exedom, $exeuser, $udom, $uname, $what) = split(/:/,$tail);
2517:
2518:
2519: my $namespace='roles';
2520: chomp($what);
2521: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2522: &GDBM_WRCREAT(), "P",
2523: "$exedom:$exeuser:$what");
2524: #
2525: # Log the attempt to set a role. The {}'s here ensure that the file
2526: # handle is open for the minimal amount of time. Since the flush
2527: # is done on close this improves the chances the log will be an un-
2528: # corrupted ordered thing.
2529: if ($hashref) {
1.261 foxr 2530: my $pass_entry = &get_auth_type($udom, $uname);
2531: my ($auth_type,$pwd) = split(/:/, $pass_entry);
2532: $auth_type = $auth_type.":";
1.230 foxr 2533: my @pairs=split(/\&/,$what);
2534: foreach my $pair (@pairs) {
2535: my ($key,$value)=split(/=/,$pair);
2536: &manage_permissions($key, $udom, $uname,
1.260 foxr 2537: $auth_type);
1.230 foxr 2538: $hashref->{$key}=$value;
2539: }
2540: if (untie($hashref)) {
2541: &Reply($client, "ok\n", $userinput);
2542: } else {
2543: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2544: "while attempting rolesput\n", $userinput);
2545: }
2546: } else {
2547: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2548: "while attempting rolesput\n", $userinput);
2549: }
2550: return 1;
2551: }
2552: ®ister_handler("rolesput", \&roles_put_handler, 1,1,0); # Encoded client only.
2553:
2554: #
1.231 foxr 2555: # Deletes (removes) a role for a user. This is equivalent to removing
2556: # a permissions package associated with the role from the user's profile.
2557: #
2558: # Parameters:
2559: # $cmd - The command (rolesdel)
2560: # $tail - The remainder of the request line. This consists
2561: # of:
2562: # The domain and user requesting the change (logged)
2563: # The domain and user being changed.
2564: # The roles being revoked. These are shipped to us
2565: # as a bunch of & separated role name keywords.
2566: # $client - The file handle open on the client.
2567: # Returns:
2568: # 1 - Continue processing
2569: # 0 - Exit.
2570: #
2571: sub roles_delete_handler {
2572: my ($cmd, $tail, $client) = @_;
2573:
2574: my $userinput = "$cmd:$tail";
2575:
2576: my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
2577: &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
2578: "what = ".$what);
2579: my $namespace='roles';
2580: chomp($what);
2581: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2582: &GDBM_WRCREAT(), "D",
2583: "$exedom:$exeuser:$what");
2584:
2585: if ($hashref) {
2586: my @rolekeys=split(/\&/,$what);
2587:
2588: foreach my $key (@rolekeys) {
2589: delete $hashref->{$key};
2590: }
2591: if (untie(%$hashref)) {
2592: &Reply($client, "ok\n", $userinput);
2593: } else {
2594: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2595: "while attempting rolesdel\n", $userinput);
2596: }
2597: } else {
2598: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2599: "while attempting rolesdel\n", $userinput);
2600: }
2601:
2602: return 1;
2603: }
2604: ®ister_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
2605:
2606: # Unencrypted get from a user's profile database. See
2607: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
2608: # This function retrieves a keyed item from a specific named database in the
2609: # user's directory.
2610: #
2611: # Parameters:
2612: # $cmd - Command request keyword (get).
2613: # $tail - Tail of the command. This is a colon separated list
2614: # consisting of the domain and username that uniquely
2615: # identifies the profile,
2616: # The 'namespace' which selects the gdbm file to
2617: # do the lookup in,
2618: # & separated list of keys to lookup. Note that
2619: # the values are returned as an & separated list too.
2620: # $client - File descriptor open on the client.
2621: # Returns:
2622: # 1 - Continue processing.
2623: # 0 - Exit.
2624: #
2625: sub get_profile_entry {
2626: my ($cmd, $tail, $client) = @_;
2627:
2628: my $userinput= "$cmd:$tail";
2629:
2630: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2631: chomp($what);
1.255 foxr 2632:
2633: my $replystring = read_profile($udom, $uname, $namespace, $what);
2634: my ($first) = split(/:/,$replystring);
2635: if($first ne "error") {
2636: &Reply($client, "$replystring\n", $userinput);
1.231 foxr 2637: } else {
1.255 foxr 2638: &Failure($client, $replystring." while attempting get\n", $userinput);
1.231 foxr 2639: }
2640: return 1;
1.255 foxr 2641:
2642:
1.231 foxr 2643: }
2644: ®ister_handler("get", \&get_profile_entry, 0,1,0);
2645:
2646: #
2647: # Process the encrypted get request. Note that the request is sent
2648: # in clear, but the reply is encrypted. This is a small covert channel:
2649: # information about the sensitive keys is given to the snooper. Just not
2650: # information about the values of the sensitive key. Hmm if I wanted to
2651: # know these I'd snoop for the egets. Get the profile item names from them
2652: # and then issue a get for them since there's no enforcement of the
2653: # requirement of an encrypted get for particular profile items. If I
2654: # were re-doing this, I'd force the request to be encrypted as well as the
2655: # reply. I'd also just enforce encrypted transactions for all gets since
2656: # that would prevent any covert channel snooping.
2657: #
2658: # Parameters:
2659: # $cmd - Command keyword of request (eget).
2660: # $tail - Tail of the command. See GetProfileEntry
# for more information about this.
2661: # $client - File open on the client.
2662: # Returns:
2663: # 1 - Continue processing
2664: # 0 - server should exit.
2665: sub get_profile_entry_encrypted {
2666: my ($cmd, $tail, $client) = @_;
2667:
2668: my $userinput = "$cmd:$tail";
2669:
2670: my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
2671: chomp($what);
1.255 foxr 2672: my $qresult = read_profile($udom, $uname, $namespace, $what);
2673: my ($first) = split(/:/, $qresult);
2674: if($first ne "error") {
2675:
2676: if ($cipher) {
2677: my $cmdlength=length($qresult);
2678: $qresult.=" ";
2679: my $encqresult='';
2680: for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
2681: $encqresult.= unpack("H16",
2682: $cipher->encrypt(substr($qresult,
2683: $encidx,
2684: 8)));
2685: }
2686: &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
2687: } else {
1.231 foxr 2688: &Failure( $client, "error:no_key\n", $userinput);
2689: }
2690: } else {
1.255 foxr 2691: &Failure($client, "$qresult while attempting eget\n", $userinput);
2692:
1.231 foxr 2693: }
2694:
2695: return 1;
2696: }
1.255 foxr 2697: ®ister_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263 albertel 2698:
1.231 foxr 2699: #
2700: # Deletes a key in a user profile database.
2701: #
2702: # Parameters:
2703: # $cmd - Command keyword (del).
2704: # $tail - Command tail. IN this case a colon
2705: # separated list containing:
2706: # The domain and user that identifies uniquely
2707: # the identity of the user.
2708: # The profile namespace (name of the profile
2709: # database file).
2710: # & separated list of keywords to delete.
2711: # $client - File open on client socket.
2712: # Returns:
2713: # 1 - Continue processing
2714: # 0 - Exit server.
2715: #
2716: #
2717: sub delete_profile_entry {
2718: my ($cmd, $tail, $client) = @_;
2719:
2720: my $userinput = "cmd:$tail";
2721:
2722: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2723: chomp($what);
2724: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2725: &GDBM_WRCREAT(),
2726: "D",$what);
2727: if ($hashref) {
2728: my @keys=split(/\&/,$what);
2729: foreach my $key (@keys) {
2730: delete($hashref->{$key});
2731: }
2732: if (untie(%$hashref)) {
2733: &Reply($client, "ok\n", $userinput);
2734: } else {
2735: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2736: "while attempting del\n", $userinput);
2737: }
2738: } else {
2739: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2740: "while attempting del\n", $userinput);
2741: }
2742: return 1;
2743: }
2744: ®ister_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263 albertel 2745:
1.231 foxr 2746: #
2747: # List the set of keys that are defined in a profile database file.
2748: # A successful reply from this will contain an & separated list of
2749: # the keys.
2750: # Parameters:
2751: # $cmd - Command request (keys).
2752: # $tail - Remainder of the request, a colon separated
2753: # list containing domain/user that identifies the
2754: # user being queried, and the database namespace
2755: # (database filename essentially).
2756: # $client - File open on the client.
2757: # Returns:
2758: # 1 - Continue processing.
2759: # 0 - Exit the server.
2760: #
2761: sub get_profile_keys {
2762: my ($cmd, $tail, $client) = @_;
2763:
2764: my $userinput = "$cmd:$tail";
2765:
2766: my ($udom,$uname,$namespace)=split(/:/,$tail);
2767: my $qresult='';
2768: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2769: &GDBM_READER());
2770: if ($hashref) {
2771: foreach my $key (keys %$hashref) {
2772: $qresult.="$key&";
2773: }
2774: if (untie(%$hashref)) {
2775: $qresult=~s/\&$//;
2776: &Reply($client, "$qresult\n", $userinput);
2777: } else {
2778: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2779: "while attempting keys\n", $userinput);
2780: }
2781: } else {
2782: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2783: "while attempting keys\n", $userinput);
2784: }
2785:
2786: return 1;
2787: }
2788: ®ister_handler("keys", \&get_profile_keys, 0, 1, 0);
2789:
2790: #
2791: # Dump the contents of a user profile database.
2792: # Note that this constitutes a very large covert channel too since
2793: # the dump will return sensitive information that is not encrypted.
2794: # The naive security assumption is that the session negotiation ensures
2795: # our client is trusted and I don't believe that's assured at present.
2796: # Sure want badly to go to ssl or tls. Of course if my peer isn't really
2797: # a LonCAPA node they could have negotiated an encryption key too so >sigh<.
2798: #
2799: # Parameters:
2800: # $cmd - The command request keyword (currentdump).
2801: # $tail - Remainder of the request, consisting of a colon
2802: # separated list that has the domain/username and
2803: # the namespace to dump (database file).
2804: # $client - file open on the remote client.
2805: # Returns:
2806: # 1 - Continue processing.
2807: # 0 - Exit the server.
2808: #
2809: sub dump_profile_database {
2810: my ($cmd, $tail, $client) = @_;
2811:
2812: my $userinput = "$cmd:$tail";
2813:
2814: my ($udom,$uname,$namespace) = split(/:/,$tail);
2815: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2816: &GDBM_READER());
2817: if ($hashref) {
2818: # Structure of %data:
2819: # $data{$symb}->{$parameter}=$value;
2820: # $data{$symb}->{'v.'.$parameter}=$version;
2821: # since $parameter will be unescaped, we do not
2822: # have to worry about silly parameter names...
2823:
2824: my $qresult='';
2825: my %data = (); # A hash of anonymous hashes..
2826: while (my ($key,$value) = each(%$hashref)) {
2827: my ($v,$symb,$param) = split(/:/,$key);
2828: next if ($v eq 'version' || $symb eq 'keys');
2829: next if (exists($data{$symb}) &&
2830: exists($data{$symb}->{$param}) &&
2831: $data{$symb}->{'v.'.$param} > $v);
2832: $data{$symb}->{$param}=$value;
2833: $data{$symb}->{'v.'.$param}=$v;
2834: }
2835: if (untie(%$hashref)) {
2836: while (my ($symb,$param_hash) = each(%data)) {
2837: while(my ($param,$value) = each (%$param_hash)){
2838: next if ($param =~ /^v\./); # Ignore versions...
2839: #
2840: # Just dump the symb=value pairs separated by &
2841: #
2842: $qresult.=$symb.':'.$param.'='.$value.'&';
2843: }
2844: }
2845: chop($qresult);
2846: &Reply($client , "$qresult\n", $userinput);
2847: } else {
2848: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2849: "while attempting currentdump\n", $userinput);
2850: }
2851: } else {
2852: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2853: "while attempting currentdump\n", $userinput);
2854: }
2855:
2856: return 1;
2857: }
2858: ®ister_handler("currentdump", \&dump_profile_database, 0, 1, 0);
2859:
2860: #
2861: # Dump a profile database with an optional regular expression
2862: # to match against the keys. In this dump, no effort is made
2863: # to separate symb from version information. Presumably the
2864: # databases that are dumped by this command are of a different
2865: # structure. Need to look at this and improve the documentation of
2866: # both this and the currentdump handler.
2867: # Parameters:
2868: # $cmd - The command keyword.
2869: # $tail - All of the characters after the $cmd:
2870: # These are expected to be a colon
2871: # separated list containing:
2872: # domain/user - identifying the user.
2873: # namespace - identifying the database.
2874: # regexp - optional regular expression
2875: # that is matched against
2876: # database keywords to do
2877: # selective dumps.
2878: # $client - Channel open on the client.
2879: # Returns:
2880: # 1 - Continue processing.
2881: # Side effects:
2882: # response is written to $client.
2883: #
2884: sub dump_with_regexp {
2885: my ($cmd, $tail, $client) = @_;
2886:
2887:
2888: my $userinput = "$cmd:$tail";
2889:
2890: my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);
2891: if (defined($regexp)) {
2892: $regexp=&unescape($regexp);
2893: } else {
2894: $regexp='.';
2895: }
2896: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2897: &GDBM_READER());
2898: if ($hashref) {
2899: my $qresult='';
2900: while (my ($key,$value) = each(%$hashref)) {
2901: if ($regexp eq '.') {
2902: $qresult.=$key.'='.$value.'&';
2903: } else {
2904: my $unescapeKey = &unescape($key);
2905: if (eval('$unescapeKey=~/$regexp/')) {
2906: $qresult.="$key=$value&";
2907: }
2908: }
2909: }
2910: if (untie(%$hashref)) {
2911: chop($qresult);
2912: &Reply($client, "$qresult\n", $userinput);
2913: } else {
2914: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2915: "while attempting dump\n", $userinput);
2916: }
2917: } else {
2918: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2919: "while attempting dump\n", $userinput);
2920: }
2921:
2922: return 1;
2923: }
2924: ®ister_handler("dump", \&dump_with_regexp, 0, 1, 0);
2925:
2926: # Store a set of key=value pairs associated with a versioned name.
2927: #
2928: # Parameters:
2929: # $cmd - Request command keyword.
2930: # $tail - Tail of the request. This is a colon
2931: # separated list containing:
2932: # domain/user - User and authentication domain.
2933: # namespace - Name of the database being modified
2934: # rid - Resource keyword to modify.
2935: # what - new value associated with rid.
2936: #
2937: # $client - Socket open on the client.
2938: #
2939: #
2940: # Returns:
2941: # 1 (keep on processing).
2942: # Side-Effects:
2943: # Writes to the client
2944: sub store_handler {
2945: my ($cmd, $tail, $client) = @_;
2946:
2947: my $userinput = "$cmd:$tail";
2948:
2949: my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
2950: if ($namespace ne 'roles') {
2951:
2952: chomp($what);
2953: my @pairs=split(/\&/,$what);
2954: my $hashref = &tie_user_hash($udom, $uname, $namespace,
1.268 albertel 2955: &GDBM_WRCREAT(), "S",
1.231 foxr 2956: "$rid:$what");
2957: if ($hashref) {
2958: my $now = time;
2959: my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
2960: my $key;
2961: $hashref->{"version:$rid"}++;
2962: my $version=$hashref->{"version:$rid"};
2963: my $allkeys='';
2964: foreach my $pair (@pairs) {
2965: my ($key,$value)=split(/=/,$pair);
2966: $allkeys.=$key.':';
2967: $hashref->{"$version:$rid:$key"}=$value;
2968: }
2969: $hashref->{"$version:$rid:timestamp"}=$now;
2970: $allkeys.='timestamp';
2971: $hashref->{"$version:keys:$rid"}=$allkeys;
2972: if (untie($hashref)) {
2973: &Reply($client, "ok\n", $userinput);
2974: } else {
2975: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2976: "while attempting store\n", $userinput);
2977: }
2978: } else {
2979: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2980: "while attempting store\n", $userinput);
2981: }
2982: } else {
2983: &Failure($client, "refused\n", $userinput);
2984: }
2985:
2986: return 1;
2987: }
2988: ®ister_handler("store", \&store_handler, 0, 1, 0);
1.263 albertel 2989:
1.231 foxr 2990: #
2991: # Dump out all versions of a resource that has key=value pairs associated
2992: # with it for each version. These resources are built up via the store
2993: # command.
2994: #
2995: # Parameters:
2996: # $cmd - Command keyword.
2997: # $tail - Remainder of the request which consists of:
2998: # domain/user - User and auth. domain.
2999: # namespace - name of resource database.
3000: # rid - Resource id.
3001: # $client - socket open on the client.
3002: #
3003: # Returns:
3004: # 1 indicating the caller should not yet exit.
3005: # Side-effects:
3006: # Writes a reply to the client.
3007: # The reply is a string of the following shape:
3008: # version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
3009: # Where the 1 above represents version 1.
3010: # this continues for all pairs of keys in all versions.
3011: #
3012: #
3013: #
3014: #
3015: sub restore_handler {
3016: my ($cmd, $tail, $client) = @_;
3017:
3018: my $userinput = "$cmd:$tail"; # Only used for logging purposes.
3019:
3020: my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
3021: $namespace=~s/\//\_/g;
3022: $namespace=~s/\W//g;
3023: chomp($rid);
3024: my $proname=&propath($udom,$uname);
3025: my $qresult='';
3026: my %hash;
3027: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
3028: &GDBM_READER(),0640)) {
3029: my $version=$hash{"version:$rid"};
3030: $qresult.="version=$version&";
3031: my $scope;
3032: for ($scope=1;$scope<=$version;$scope++) {
3033: my $vkeys=$hash{"$scope:keys:$rid"};
3034: my @keys=split(/:/,$vkeys);
3035: my $key;
3036: $qresult.="$scope:keys=$vkeys&";
3037: foreach $key (@keys) {
3038: $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
3039: }
3040: }
3041: if (untie(%hash)) {
3042: $qresult=~s/\&$//;
3043: &Reply( $client, "$qresult\n", $userinput);
3044: } else {
3045: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3046: "while attempting restore\n", $userinput);
3047: }
3048: } else {
3049: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3050: "while attempting restore\n", $userinput);
3051: }
3052:
3053: return 1;
3054:
3055:
3056: }
3057: ®ister_handler("restore", \&restore_handler, 0,1,0);
1.234 foxr 3058:
3059: #
3060: # Add a chat message to to a discussion board.
3061: #
3062: # Parameters:
3063: # $cmd - Request keyword.
3064: # $tail - Tail of the command. A colon separated list
3065: # containing:
3066: # cdom - Domain on which the chat board lives
3067: # cnum - Identifier of the discussion group.
3068: # post - Body of the posting.
3069: # $client - Socket open on the client.
3070: # Returns:
3071: # 1 - Indicating caller should keep on processing.
3072: #
3073: # Side-effects:
3074: # writes a reply to the client.
3075: #
3076: #
3077: sub send_chat_handler {
3078: my ($cmd, $tail, $client) = @_;
3079:
3080:
3081: my $userinput = "$cmd:$tail";
3082:
3083: my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
3084: &chat_add($cdom,$cnum,$newpost);
3085: &Reply($client, "ok\n", $userinput);
3086:
3087: return 1;
3088: }
3089: ®ister_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263 albertel 3090:
1.234 foxr 3091: #
3092: # Retrieve the set of chat messagss from a discussion board.
3093: #
3094: # Parameters:
3095: # $cmd - Command keyword that initiated the request.
3096: # $tail - Remainder of the request after the command
3097: # keyword. In this case a colon separated list of
3098: # chat domain - Which discussion board.
3099: # chat id - Discussion thread(?)
3100: # domain/user - Authentication domain and username
3101: # of the requesting person.
3102: # $client - Socket open on the client program.
3103: # Returns:
3104: # 1 - continue processing
3105: # Side effects:
3106: # Response is written to the client.
3107: #
3108: sub retrieve_chat_handler {
3109: my ($cmd, $tail, $client) = @_;
3110:
3111:
3112: my $userinput = "$cmd:$tail";
3113:
3114: my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
3115: my $reply='';
3116: foreach (&get_chat($cdom,$cnum,$udom,$uname)) {
3117: $reply.=&escape($_).':';
3118: }
3119: $reply=~s/\:$//;
3120: &Reply($client, $reply."\n", $userinput);
3121:
3122:
3123: return 1;
3124: }
3125: ®ister_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
3126:
3127: #
3128: # Initiate a query of an sql database. SQL query repsonses get put in
3129: # a file for later retrieval. This prevents sql query results from
3130: # bottlenecking the system. Note that with loncnew, perhaps this is
3131: # less of an issue since multiple outstanding requests can be concurrently
3132: # serviced.
3133: #
3134: # Parameters:
3135: # $cmd - COmmand keyword that initiated the request.
3136: # $tail - Remainder of the command after the keyword.
3137: # For this function, this consists of a query and
3138: # 3 arguments that are self-documentingly labelled
3139: # in the original arg1, arg2, arg3.
3140: # $client - Socket open on the client.
3141: # Return:
3142: # 1 - Indicating processing should continue.
3143: # Side-effects:
3144: # a reply is written to $client.
3145: #
3146: sub send_query_handler {
3147: my ($cmd, $tail, $client) = @_;
3148:
3149:
3150: my $userinput = "$cmd:$tail";
3151:
3152: my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
3153: $query=~s/\n*$//g;
3154: &Reply($client, "". &sql_reply("$clientname\&$query".
3155: "\&$arg1"."\&$arg2"."\&$arg3")."\n",
3156: $userinput);
3157:
3158: return 1;
3159: }
3160: ®ister_handler("querysend", \&send_query_handler, 0, 1, 0);
3161:
3162: #
3163: # Add a reply to an sql query. SQL queries are done asyncrhonously.
3164: # The query is submitted via a "querysend" transaction.
3165: # There it is passed on to the lonsql daemon, queued and issued to
3166: # mysql.
3167: # This transaction is invoked when the sql transaction is complete
3168: # it stores the query results in flie and indicates query completion.
3169: # presumably local software then fetches this response... I'm guessing
3170: # the sequence is: lonc does a querysend, we ask lonsql to do it.
3171: # lonsql on completion of the query interacts with the lond of our
3172: # client to do a query reply storing two files:
3173: # - id - The results of the query.
3174: # - id.end - Indicating the transaction completed.
3175: # NOTE: id is a unique id assigned to the query and querysend time.
3176: # Parameters:
3177: # $cmd - Command keyword that initiated this request.
3178: # $tail - Remainder of the tail. In this case that's a colon
3179: # separated list containing the query Id and the
3180: # results of the query.
3181: # $client - Socket open on the client.
3182: # Return:
3183: # 1 - Indicating that we should continue processing.
3184: # Side effects:
3185: # ok written to the client.
3186: #
3187: sub reply_query_handler {
3188: my ($cmd, $tail, $client) = @_;
3189:
3190:
3191: my $userinput = "$cmd:$tail";
3192:
3193: my ($cmd,$id,$reply)=split(/:/,$userinput);
3194: my $store;
3195: my $execdir=$perlvar{'lonDaemons'};
3196: if ($store=IO::File->new(">$execdir/tmp/$id")) {
3197: $reply=~s/\&/\n/g;
3198: print $store $reply;
3199: close $store;
3200: my $store2=IO::File->new(">$execdir/tmp/$id.end");
3201: print $store2 "done\n";
3202: close $store2;
3203: &Reply($client, "ok\n", $userinput);
3204: } else {
3205: &Failure($client, "error: ".($!+0)
3206: ." IO::File->new Failed ".
3207: "while attempting queryreply\n", $userinput);
3208: }
3209:
3210:
3211: return 1;
3212: }
3213: ®ister_handler("queryreply", \&reply_query_handler, 0, 1, 0);
3214:
3215: #
3216: # Process the courseidput request. Not quite sure what this means
3217: # at the system level sense. It appears a gdbm file in the
3218: # /home/httpd/lonUsers/$domain/nohist_courseids is tied and
3219: # a set of entries made in that database.
3220: #
3221: # Parameters:
3222: # $cmd - The command keyword that initiated this request.
3223: # $tail - Tail of the command. In this case consists of a colon
3224: # separated list contaning the domain to apply this to and
3225: # an ampersand separated list of keyword=value pairs.
1.272 raeburn 3226: # Each value is a colon separated list that includes:
3227: # description, institutional code and course owner.
3228: # For backward compatibility with versions included
3229: # in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
3230: # code and/or course owner are preserved from the existing
3231: # record when writing a new record in response to 1.1 or
3232: # 1.2 implementations of lonnet::flushcourselogs().
3233: #
1.234 foxr 3234: # $client - Socket open on the client.
3235: # Returns:
3236: # 1 - indicating that processing should continue
3237: #
3238: # Side effects:
3239: # reply is written to the client.
3240: #
3241: sub put_course_id_handler {
3242: my ($cmd, $tail, $client) = @_;
3243:
3244:
3245: my $userinput = "$cmd:$tail";
3246:
1.266 raeburn 3247: my ($udom, $what) = split(/:/, $tail,2);
1.234 foxr 3248: chomp($what);
3249: my $now=time;
3250: my @pairs=split(/\&/,$what);
3251:
3252: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3253: if ($hashref) {
3254: foreach my $pair (@pairs) {
1.271 raeburn 3255: my ($key,$courseinfo) = split(/=/,$pair,2);
3256: $courseinfo =~ s/=/:/g;
1.272 raeburn 3257:
1.273 albertel 3258: my @current_items = split(/:/,$hashref->{$key});
3259: shift(@current_items); # remove description
3260: pop(@current_items); # remove last access
1.272 raeburn 3261: my $numcurrent = scalar(@current_items);
3262:
1.273 albertel 3263: my @new_items = split(/:/,$courseinfo);
1.272 raeburn 3264: my $numnew = scalar(@new_items);
3265: if ($numcurrent > 0) {
3266: if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
3267: $courseinfo .= ':'.join(':',@current_items);
3268: } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
3269: $courseinfo .= ':'.$current_items[$numcurrent-1];
3270: }
3271: }
1.266 raeburn 3272: $hashref->{$key}=$courseinfo.':'.$now;
1.234 foxr 3273: }
3274: if (untie(%$hashref)) {
1.253 foxr 3275: &Reply( $client, "ok\n", $userinput);
1.234 foxr 3276: } else {
1.253 foxr 3277: &Failure($client, "error: ".($!+0)
1.234 foxr 3278: ." untie(GDBM) Failed ".
3279: "while attempting courseidput\n", $userinput);
3280: }
3281: } else {
1.253 foxr 3282: &Failure($client, "error: ".($!+0)
1.234 foxr 3283: ." tie(GDBM) Failed ".
3284: "while attempting courseidput\n", $userinput);
3285: }
1.253 foxr 3286:
1.234 foxr 3287:
3288: return 1;
3289: }
3290: ®ister_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
3291:
3292: # Retrieves the value of a course id resource keyword pattern
3293: # defined since a starting date. Both the starting date and the
3294: # keyword pattern are optional. If the starting date is not supplied it
3295: # is treated as the beginning of time. If the pattern is not found,
3296: # it is treatred as "." matching everything.
3297: #
3298: # Parameters:
3299: # $cmd - Command keyword that resulted in us being dispatched.
3300: # $tail - The remainder of the command that, in this case, consists
3301: # of a colon separated list of:
3302: # domain - The domain in which the course database is
3303: # defined.
3304: # since - Optional parameter describing the minimum
3305: # time of definition(?) of the resources that
3306: # will match the dump.
3307: # description - regular expression that is used to filter
3308: # the dump. Only keywords matching this regexp
3309: # will be used.
1.272 raeburn 3310: # institutional code - optional supplied code to filter
3311: # the dump. Only courses with an institutional code
3312: # that match the supplied code will be returned.
3313: # owner - optional supplied username of owner to filter
3314: # the dump. Only courses for which the course
3315: # owner matches the supplied username will be
1.274 albertel 3316: # returned. Implicit assumption that owner
3317: # is a user in the domain in which the
3318: # course database is defined.
1.234 foxr 3319: # $client - The socket open on the client.
3320: # Returns:
3321: # 1 - Continue processing.
3322: # Side Effects:
3323: # a reply is written to $client.
3324: sub dump_course_id_handler {
3325: my ($cmd, $tail, $client) = @_;
3326:
3327: my $userinput = "$cmd:$tail";
3328:
1.282 raeburn 3329: my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter) =split(/:/,$tail);
1.234 foxr 3330: if (defined($description)) {
3331: $description=&unescape($description);
3332: } else {
3333: $description='.';
3334: }
1.266 raeburn 3335: if (defined($instcodefilter)) {
3336: $instcodefilter=&unescape($instcodefilter);
3337: } else {
3338: $instcodefilter='.';
3339: }
3340: if (defined($ownerfilter)) {
3341: $ownerfilter=&unescape($ownerfilter);
3342: } else {
3343: $ownerfilter='.';
3344: }
1.282 raeburn 3345: if (defined($coursefilter)) {
3346: $coursefilter=&unescape($coursefilter);
3347: } else {
3348: $coursefilter='.';
3349: }
1.266 raeburn 3350:
1.234 foxr 3351: unless (defined($since)) { $since=0; }
3352: my $qresult='';
3353: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3354: if ($hashref) {
3355: while (my ($key,$value) = each(%$hashref)) {
1.266 raeburn 3356: my ($descr,$lasttime,$inst_code,$owner);
1.274 albertel 3357: my @courseitems = split(/:/,$value);
3358: $lasttime = pop(@courseitems);
3359: ($descr,$inst_code,$owner)=@courseitems;
1.234 foxr 3360: if ($lasttime<$since) { next; }
1.266 raeburn 3361: my $match = 1;
3362: unless ($description eq '.') {
3363: my $unescapeDescr = &unescape($descr);
3364: unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
3365: $match = 0;
1.234 foxr 3366: }
1.266 raeburn 3367: }
3368: unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
3369: my $unescapeInstcode = &unescape($inst_code);
3370: unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
3371: $match = 0;
3372: }
1.234 foxr 3373: }
1.266 raeburn 3374: unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
3375: my $unescapeOwner = &unescape($owner);
3376: unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
3377: $match = 0;
3378: }
3379: }
1.282 raeburn 3380: unless ($coursefilter eq '.' || !defined($coursefilter)) {
3381: my $unescapeCourse = &unescape($key);
3382: unless (eval('$unescapeCourse=~/^$udom(_)\Q$coursefilter\E$/')) {
3383: $match = 0;
3384: }
3385: }
1.266 raeburn 3386: if ($match == 1) {
3387: $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
3388: }
1.234 foxr 3389: }
3390: if (untie(%$hashref)) {
3391: chop($qresult);
3392: &Reply($client, "$qresult\n", $userinput);
3393: } else {
3394: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3395: "while attempting courseiddump\n", $userinput);
3396: }
3397: } else {
3398: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3399: "while attempting courseiddump\n", $userinput);
3400: }
3401:
3402:
3403: return 1;
3404: }
3405: ®ister_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238 foxr 3406:
3407: #
3408: # Puts an id to a domains id database.
3409: #
3410: # Parameters:
3411: # $cmd - The command that triggered us.
3412: # $tail - Remainder of the request other than the command. This is a
3413: # colon separated list containing:
3414: # $domain - The domain for which we are writing the id.
3415: # $pairs - The id info to write... this is and & separated list
3416: # of keyword=value.
3417: # $client - Socket open on the client.
3418: # Returns:
3419: # 1 - Continue processing.
3420: # Side effects:
3421: # reply is written to $client.
3422: #
3423: sub put_id_handler {
3424: my ($cmd,$tail,$client) = @_;
3425:
3426:
3427: my $userinput = "$cmd:$tail";
3428:
3429: my ($udom,$what)=split(/:/,$tail);
3430: chomp($what);
3431: my @pairs=split(/\&/,$what);
3432: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
3433: "P", $what);
3434: if ($hashref) {
3435: foreach my $pair (@pairs) {
3436: my ($key,$value)=split(/=/,$pair);
3437: $hashref->{$key}=$value;
3438: }
3439: if (untie(%$hashref)) {
3440: &Reply($client, "ok\n", $userinput);
3441: } else {
3442: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3443: "while attempting idput\n", $userinput);
3444: }
3445: } else {
3446: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3447: "while attempting idput\n", $userinput);
3448: }
3449:
3450: return 1;
3451: }
1.263 albertel 3452: ®ister_handler("idput", \&put_id_handler, 0, 1, 0);
1.238 foxr 3453:
3454: #
3455: # Retrieves a set of id values from the id database.
3456: # Returns an & separated list of results, one for each requested id to the
3457: # client.
3458: #
3459: # Parameters:
3460: # $cmd - Command keyword that caused us to be dispatched.
3461: # $tail - Tail of the command. Consists of a colon separated:
3462: # domain - the domain whose id table we dump
3463: # ids Consists of an & separated list of
3464: # id keywords whose values will be fetched.
3465: # nonexisting keywords will have an empty value.
3466: # $client - Socket open on the client.
3467: #
3468: # Returns:
3469: # 1 - indicating processing should continue.
3470: # Side effects:
3471: # An & separated list of results is written to $client.
3472: #
3473: sub get_id_handler {
3474: my ($cmd, $tail, $client) = @_;
3475:
3476:
3477: my $userinput = "$client:$tail";
3478:
3479: my ($udom,$what)=split(/:/,$tail);
3480: chomp($what);
3481: my @queries=split(/\&/,$what);
3482: my $qresult='';
3483: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
3484: if ($hashref) {
3485: for (my $i=0;$i<=$#queries;$i++) {
3486: $qresult.="$hashref->{$queries[$i]}&";
3487: }
3488: if (untie(%$hashref)) {
3489: $qresult=~s/\&$//;
3490: &Reply($client, "$qresult\n", $userinput);
3491: } else {
3492: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3493: "while attempting idget\n",$userinput);
3494: }
3495: } else {
3496: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3497: "while attempting idget\n",$userinput);
3498: }
3499:
3500: return 1;
3501: }
1.263 albertel 3502: ®ister_handler("idget", \&get_id_handler, 0, 1, 0);
1.238 foxr 3503:
3504: #
3505: # Process the tmpput command I'm not sure what this does.. Seems to
3506: # create a file in the lonDaemons/tmp directory of the form $id.tmp
3507: # where Id is the client's ip concatenated with a sequence number.
3508: # The file will contain some value that is passed in. Is this e.g.
3509: # a login token?
3510: #
3511: # Parameters:
3512: # $cmd - The command that got us dispatched.
3513: # $tail - The remainder of the request following $cmd:
3514: # In this case this will be the contents of the file.
3515: # $client - Socket connected to the client.
3516: # Returns:
3517: # 1 indicating processing can continue.
3518: # Side effects:
3519: # A file is created in the local filesystem.
3520: # A reply is sent to the client.
3521: sub tmp_put_handler {
3522: my ($cmd, $what, $client) = @_;
3523:
3524: my $userinput = "$cmd:$what"; # Reconstruct for logging.
3525:
3526:
3527: my $store;
3528: $tmpsnum++;
3529: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
3530: $id=~s/\W/\_/g;
3531: $what=~s/\n//g;
3532: my $execdir=$perlvar{'lonDaemons'};
3533: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
3534: print $store $what;
3535: close $store;
3536: &Reply($client, "$id\n", $userinput);
3537: } else {
3538: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
3539: "while attempting tmpput\n", $userinput);
3540: }
3541: return 1;
3542:
3543: }
3544: ®ister_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263 albertel 3545:
1.238 foxr 3546: # Processes the tmpget command. This command returns the contents
3547: # of a temporary resource file(?) created via tmpput.
3548: #
3549: # Paramters:
3550: # $cmd - Command that got us dispatched.
3551: # $id - Tail of the command, contain the id of the resource
3552: # we want to fetch.
3553: # $client - socket open on the client.
3554: # Return:
3555: # 1 - Inidcating processing can continue.
3556: # Side effects:
3557: # A reply is sent to the client.
3558: #
3559: sub tmp_get_handler {
3560: my ($cmd, $id, $client) = @_;
3561:
3562: my $userinput = "$cmd:$id";
3563:
3564:
3565: $id=~s/\W/\_/g;
3566: my $store;
3567: my $execdir=$perlvar{'lonDaemons'};
3568: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
3569: my $reply=<$store>;
3570: &Reply( $client, "$reply\n", $userinput);
3571: close $store;
3572: } else {
3573: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
3574: "while attempting tmpget\n", $userinput);
3575: }
3576:
3577: return 1;
3578: }
3579: ®ister_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263 albertel 3580:
1.238 foxr 3581: #
3582: # Process the tmpdel command. This command deletes a temp resource
3583: # created by the tmpput command.
3584: #
3585: # Parameters:
3586: # $cmd - Command that got us here.
3587: # $id - Id of the temporary resource created.
3588: # $client - socket open on the client process.
3589: #
3590: # Returns:
3591: # 1 - Indicating processing should continue.
3592: # Side Effects:
3593: # A file is deleted
3594: # A reply is sent to the client.
3595: sub tmp_del_handler {
3596: my ($cmd, $id, $client) = @_;
3597:
3598: my $userinput= "$cmd:$id";
3599:
3600: chomp($id);
3601: $id=~s/\W/\_/g;
3602: my $execdir=$perlvar{'lonDaemons'};
3603: if (unlink("$execdir/tmp/$id.tmp")) {
3604: &Reply($client, "ok\n", $userinput);
3605: } else {
3606: &Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
3607: "while attempting tmpdel\n", $userinput);
3608: }
3609:
3610: return 1;
3611:
3612: }
3613: ®ister_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263 albertel 3614:
1.238 foxr 3615: #
1.246 foxr 3616: # Processes the setannounce command. This command
3617: # creates a file named announce.txt in the top directory of
3618: # the documentn root and sets its contents. The announce.txt file is
3619: # printed in its entirety at the LonCAPA login page. Note:
3620: # once the announcement.txt fileis created it cannot be deleted.
3621: # However, setting the contents of the file to empty removes the
3622: # announcement from the login page of loncapa so who cares.
3623: #
3624: # Parameters:
3625: # $cmd - The command that got us dispatched.
3626: # $announcement - The text of the announcement.
3627: # $client - Socket open on the client process.
3628: # Retunrns:
3629: # 1 - Indicating request processing should continue
3630: # Side Effects:
3631: # The file {DocRoot}/announcement.txt is created.
3632: # A reply is sent to $client.
3633: #
3634: sub set_announce_handler {
3635: my ($cmd, $announcement, $client) = @_;
3636:
3637: my $userinput = "$cmd:$announcement";
3638:
3639: chomp($announcement);
3640: $announcement=&unescape($announcement);
3641: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
3642: '/announcement.txt')) {
3643: print $store $announcement;
3644: close $store;
3645: &Reply($client, "ok\n", $userinput);
3646: } else {
3647: &Failure($client, "error: ".($!+0)."\n", $userinput);
3648: }
3649:
3650: return 1;
3651: }
3652: ®ister_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263 albertel 3653:
1.246 foxr 3654: #
3655: # Return the version of the daemon. This can be used to determine
3656: # the compatibility of cross version installations or, alternatively to
3657: # simply know who's out of date and who isn't. Note that the version
3658: # is returned concatenated with the tail.
3659: # Parameters:
3660: # $cmd - the request that dispatched to us.
3661: # $tail - Tail of the request (client's version?).
3662: # $client - Socket open on the client.
3663: #Returns:
3664: # 1 - continue processing requests.
3665: # Side Effects:
3666: # Replies with version to $client.
3667: sub get_version_handler {
3668: my ($cmd, $tail, $client) = @_;
3669:
3670: my $userinput = $cmd.$tail;
3671:
3672: &Reply($client, &version($userinput)."\n", $userinput);
3673:
3674:
3675: return 1;
3676: }
3677: ®ister_handler("version", \&get_version_handler, 0, 1, 0);
1.263 albertel 3678:
1.246 foxr 3679: # Set the current host and domain. This is used to support
3680: # multihomed systems. Each IP of the system, or even separate daemons
3681: # on the same IP can be treated as handling a separate lonCAPA virtual
3682: # machine. This command selects the virtual lonCAPA. The client always
3683: # knows the right one since it is lonc and it is selecting the domain/system
3684: # from the hosts.tab file.
3685: # Parameters:
3686: # $cmd - Command that dispatched us.
3687: # $tail - Tail of the command (domain/host requested).
3688: # $socket - Socket open on the client.
3689: #
3690: # Returns:
3691: # 1 - Indicates the program should continue to process requests.
3692: # Side-effects:
3693: # The default domain/system context is modified for this daemon.
3694: # a reply is sent to the client.
3695: #
3696: sub set_virtual_host_handler {
3697: my ($cmd, $tail, $socket) = @_;
3698:
3699: my $userinput ="$cmd:$tail";
3700:
3701: &Reply($client, &sethost($userinput)."\n", $userinput);
3702:
3703:
3704: return 1;
3705: }
1.247 albertel 3706: ®ister_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246 foxr 3707:
3708: # Process a request to exit:
3709: # - "bye" is sent to the client.
3710: # - The client socket is shutdown and closed.
3711: # - We indicate to the caller that we should exit.
3712: # Formal Parameters:
3713: # $cmd - The command that got us here.
3714: # $tail - Tail of the command (empty).
3715: # $client - Socket open on the tail.
3716: # Returns:
3717: # 0 - Indicating the program should exit!!
3718: #
3719: sub exit_handler {
3720: my ($cmd, $tail, $client) = @_;
3721:
3722: my $userinput = "$cmd:$tail";
3723:
3724: &logthis("Client $clientip ($clientname) hanging up: $userinput");
3725: &Reply($client, "bye\n", $userinput);
3726: $client->shutdown(2); # shutdown the socket forcibly.
3727: $client->close();
3728:
3729: return 0;
3730: }
1.248 foxr 3731: ®ister_handler("exit", \&exit_handler, 0,1,1);
3732: ®ister_handler("init", \&exit_handler, 0,1,1);
3733: ®ister_handler("quit", \&exit_handler, 0,1,1);
3734:
3735: # Determine if auto-enrollment is enabled.
3736: # Note that the original had what I believe to be a defect.
3737: # The original returned 0 if the requestor was not a registerd client.
3738: # It should return "refused".
3739: # Formal Parameters:
3740: # $cmd - The command that invoked us.
3741: # $tail - The tail of the command (Extra command parameters.
3742: # $client - The socket open on the client that issued the request.
3743: # Returns:
3744: # 1 - Indicating processing should continue.
3745: #
3746: sub enrollment_enabled_handler {
3747: my ($cmd, $tail, $client) = @_;
3748: my $userinput = $cmd.":".$tail; # For logging purposes.
3749:
3750:
3751: my $cdom = split(/:/, $tail); # Domain we're asking about.
3752: my $outcome = &localenroll::run($cdom);
3753: &Reply($client, "$outcome\n", $userinput);
3754:
3755: return 1;
3756: }
3757: ®ister_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
3758:
3759: # Get the official sections for which auto-enrollment is possible.
3760: # Since the admin people won't know about 'unofficial sections'
3761: # we cannot auto-enroll on them.
3762: # Formal Parameters:
3763: # $cmd - The command request that got us dispatched here.
3764: # $tail - The remainder of the request. In our case this
3765: # will be split into:
3766: # $coursecode - The course name from the admin point of view.
3767: # $cdom - The course's domain(?).
3768: # $client - Socket open on the client.
3769: # Returns:
3770: # 1 - Indiciting processing should continue.
3771: #
3772: sub get_sections_handler {
3773: my ($cmd, $tail, $client) = @_;
3774: my $userinput = "$cmd:$tail";
3775:
3776: my ($coursecode, $cdom) = split(/:/, $tail);
3777: my @secs = &localenroll::get_sections($coursecode,$cdom);
3778: my $seclist = &escape(join(':',@secs));
3779:
3780: &Reply($client, "$seclist\n", $userinput);
3781:
3782:
3783: return 1;
3784: }
3785: ®ister_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
3786:
3787: # Validate the owner of a new course section.
3788: #
3789: # Formal Parameters:
3790: # $cmd - Command that got us dispatched.
3791: # $tail - the remainder of the command. For us this consists of a
3792: # colon separated string containing:
3793: # $inst - Course Id from the institutions point of view.
3794: # $owner - Proposed owner of the course.
3795: # $cdom - Domain of the course (from the institutions
3796: # point of view?)..
3797: # $client - Socket open on the client.
3798: #
3799: # Returns:
3800: # 1 - Processing should continue.
3801: #
3802: sub validate_course_owner_handler {
3803: my ($cmd, $tail, $client) = @_;
3804: my $userinput = "$cmd:$tail";
3805: my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
3806:
3807: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
3808: &Reply($client, "$outcome\n", $userinput);
3809:
3810:
3811:
3812: return 1;
3813: }
3814: ®ister_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263 albertel 3815:
1.248 foxr 3816: #
3817: # Validate a course section in the official schedule of classes
3818: # from the institutions point of view (part of autoenrollment).
3819: #
3820: # Formal Parameters:
3821: # $cmd - The command request that got us dispatched.
3822: # $tail - The tail of the command. In this case,
3823: # this is a colon separated set of words that will be split
3824: # into:
3825: # $inst_course_id - The course/section id from the
3826: # institutions point of view.
3827: # $cdom - The domain from the institutions
3828: # point of view.
3829: # $client - Socket open on the client.
3830: # Returns:
3831: # 1 - Indicating processing should continue.
3832: #
3833: sub validate_course_section_handler {
3834: my ($cmd, $tail, $client) = @_;
3835: my $userinput = "$cmd:$tail";
3836: my ($inst_course_id, $cdom) = split(/:/, $tail);
3837:
3838: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
3839: &Reply($client, "$outcome\n", $userinput);
3840:
3841:
3842: return 1;
3843: }
3844: ®ister_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
3845:
3846: #
3847: # Create a password for a new auto-enrollment user.
3848: # I think/guess, this password allows access to the institutions
3849: # AIS class list server/services. Stuart can correct this comment
3850: # when he finds out how wrong I am.
3851: #
3852: # Formal Parameters:
3853: # $cmd - The command request that got us dispatched.
3854: # $tail - The tail of the command. In this case this is a colon separated
3855: # set of words that will be split into:
3856: # $authparam - An authentication parameter (username??).
3857: # $cdom - The domain of the course from the institution's
3858: # point of view.
3859: # $client - The socket open on the client.
3860: # Returns:
3861: # 1 - continue processing.
3862: #
3863: sub create_auto_enroll_password_handler {
3864: my ($cmd, $tail, $client) = @_;
3865: my $userinput = "$cmd:$tail";
3866:
3867: my ($authparam, $cdom) = split(/:/, $userinput);
3868:
3869: my ($create_passwd,$authchk);
3870: ($authparam,
3871: $create_passwd,
3872: $authchk) = &localenroll::create_password($authparam,$cdom);
3873:
3874: &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
3875: $userinput);
3876:
3877:
3878: return 1;
3879: }
3880: ®ister_handler("autocreatepassword", \&create_auto_enroll_password_handler,
3881: 0, 1, 0);
3882:
3883: # Retrieve and remove temporary files created by/during autoenrollment.
3884: #
3885: # Formal Parameters:
3886: # $cmd - The command that got us dispatched.
3887: # $tail - The tail of the command. In our case this is a colon
3888: # separated list that will be split into:
3889: # $filename - The name of the file to remove.
3890: # The filename is given as a path relative to
3891: # the LonCAPA temp file directory.
3892: # $client - Socket open on the client.
3893: #
3894: # Returns:
3895: # 1 - Continue processing.
3896: sub retrieve_auto_file_handler {
3897: my ($cmd, $tail, $client) = @_;
3898: my $userinput = "cmd:$tail";
3899:
3900: my ($filename) = split(/:/, $tail);
3901:
3902: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
3903: if ( (-e $source) && ($filename ne '') ) {
3904: my $reply = '';
3905: if (open(my $fh,$source)) {
3906: while (<$fh>) {
3907: chomp($_);
3908: $_ =~ s/^\s+//g;
3909: $_ =~ s/\s+$//g;
3910: $reply .= $_;
3911: }
3912: close($fh);
3913: &Reply($client, &escape($reply)."\n", $userinput);
3914:
3915: # Does this have to be uncommented??!? (RF).
3916: #
3917: # unlink($source);
3918: } else {
3919: &Failure($client, "error\n", $userinput);
3920: }
3921: } else {
3922: &Failure($client, "error\n", $userinput);
3923: }
3924:
3925:
3926: return 1;
3927: }
3928: ®ister_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
3929:
3930: #
3931: # Read and retrieve institutional code format (for support form).
3932: # Formal Parameters:
3933: # $cmd - Command that dispatched us.
3934: # $tail - Tail of the command. In this case it conatins
3935: # the course domain and the coursename.
3936: # $client - Socket open on the client.
3937: # Returns:
3938: # 1 - Continue processing.
3939: #
3940: sub get_institutional_code_format_handler {
3941: my ($cmd, $tail, $client) = @_;
3942: my $userinput = "$cmd:$tail";
3943:
3944: my $reply;
3945: my($cdom,$course) = split(/:/,$tail);
3946: my @pairs = split/\&/,$course;
3947: my %instcodes = ();
3948: my %codes = ();
3949: my @codetitles = ();
3950: my %cat_titles = ();
3951: my %cat_order = ();
3952: foreach (@pairs) {
3953: my ($key,$value) = split/=/,$_;
3954: $instcodes{&unescape($key)} = &unescape($value);
3955: }
3956: my $formatreply = &localenroll::instcode_format($cdom,
3957: \%instcodes,
3958: \%codes,
3959: \@codetitles,
3960: \%cat_titles,
3961: \%cat_order);
3962: if ($formatreply eq 'ok') {
3963: my $codes_str = &hash2str(%codes);
3964: my $codetitles_str = &array2str(@codetitles);
3965: my $cat_titles_str = &hash2str(%cat_titles);
3966: my $cat_order_str = &hash2str(%cat_order);
3967: &Reply($client,
3968: $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
3969: .$cat_order_str."\n",
3970: $userinput);
3971: } else {
3972: # this else branch added by RF since if not ok, lonc will
3973: # hang waiting on reply until timeout.
3974: #
3975: &Reply($client, "format_error\n", $userinput);
3976: }
3977:
3978: return 1;
3979: }
1.265 albertel 3980: ®ister_handler("autoinstcodeformat",
3981: \&get_institutional_code_format_handler,0,1,0);
1.246 foxr 3982:
1.265 albertel 3983: #
3984: # Gets a student's photo to exist (in the correct image type) in the user's
3985: # directory.
3986: # Formal Parameters:
3987: # $cmd - The command request that got us dispatched.
3988: # $tail - A colon separated set of words that will be split into:
3989: # $domain - student's domain
3990: # $uname - student username
3991: # $type - image type desired
3992: # $client - The socket open on the client.
3993: # Returns:
3994: # 1 - continue processing.
3995: sub student_photo_handler {
3996: my ($cmd, $tail, $client) = @_;
3997: my ($domain,$uname,$type) = split(/:/, $tail);
3998:
3999: my $path=&propath($domain,$uname).
4000: '/userfiles/internal/studentphoto.'.$type;
4001: if (-e $path) {
4002: &Reply($client,"ok\n","$cmd:$tail");
4003: return 1;
4004: }
4005: &mkpath($path);
4006: my $file=&localstudentphoto::fetch($domain,$uname);
4007: if (!$file) {
4008: &Failure($client,"unavailable\n","$cmd:$tail");
4009: return 1;
4010: }
4011: if (!-e $path) { &convert_photo($file,$path); }
4012: if (-e $path) {
4013: &Reply($client,"ok\n","$cmd:$tail");
4014: return 1;
4015: }
4016: &Failure($client,"unable_to_convert\n","$cmd:$tail");
4017: return 1;
4018: }
4019: ®ister_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246 foxr 4020:
1.264 albertel 4021: # mkpath makes all directories for a file, expects an absolute path with a
4022: # file or a trailing / if just a dir is passed
4023: # returns 1 on success 0 on failure
4024: sub mkpath {
4025: my ($file)=@_;
4026: my @parts=split(/\//,$file,-1);
4027: my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
4028: for (my $i=3;$i<= ($#parts-1);$i++) {
1.265 albertel 4029: $now.='/'.$parts[$i];
1.264 albertel 4030: if (!-e $now) {
4031: if (!mkdir($now,0770)) { return 0; }
4032: }
4033: }
4034: return 1;
4035: }
4036:
1.207 foxr 4037: #---------------------------------------------------------------
4038: #
4039: # Getting, decoding and dispatching requests:
4040: #
4041: #
4042: # Get a Request:
4043: # Gets a Request message from the client. The transaction
4044: # is defined as a 'line' of text. We remove the new line
4045: # from the text line.
1.226 foxr 4046: #
1.211 albertel 4047: sub get_request {
1.207 foxr 4048: my $input = <$client>;
4049: chomp($input);
1.226 foxr 4050:
1.234 foxr 4051: &Debug("get_request: Request = $input\n");
1.207 foxr 4052:
4053: &status('Processing '.$clientname.':'.$input);
4054:
4055: return $input;
4056: }
1.212 foxr 4057: #---------------------------------------------------------------
4058: #
4059: # Process a request. This sub should shrink as each action
4060: # gets farmed out into a separat sub that is registered
4061: # with the dispatch hash.
4062: #
4063: # Parameters:
4064: # user_input - The request received from the client (lonc).
4065: # Returns:
4066: # true to keep processing, false if caller should exit.
4067: #
4068: sub process_request {
4069: my ($userinput) = @_; # Easier for now to break style than to
4070: # fix all the userinput -> user_input.
4071: my $wasenc = 0; # True if request was encrypted.
4072: # ------------------------------------------------------------ See if encrypted
4073: if ($userinput =~ /^enc/) {
4074: $userinput = decipher($userinput);
4075: $wasenc=1;
4076: if(!$userinput) { # Cipher not defined.
1.251 foxr 4077: &Failure($client, "error: Encrypted data without negotated key\n");
1.212 foxr 4078: return 0;
4079: }
4080: }
4081: Debug("process_request: $userinput\n");
4082:
1.213 foxr 4083: #
4084: # The 'correct way' to add a command to lond is now to
4085: # write a sub to execute it and Add it to the command dispatch
4086: # hash via a call to register_handler.. The comments to that
4087: # sub should give you enough to go on to show how to do this
4088: # along with the examples that are building up as this code
4089: # is getting refactored. Until all branches of the
4090: # if/elseif monster below have been factored out into
4091: # separate procesor subs, if the dispatch hash is missing
4092: # the command keyword, we will fall through to the remainder
4093: # of the if/else chain below in order to keep this thing in
4094: # working order throughout the transmogrification.
4095:
4096: my ($command, $tail) = split(/:/, $userinput, 2);
4097: chomp($command);
4098: chomp($tail);
4099: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
1.214 foxr 4100: $command =~ s/(\r)//; # And this too for parameterless commands.
4101: if(!$tail) {
4102: $tail =""; # defined but blank.
4103: }
1.213 foxr 4104:
4105: &Debug("Command received: $command, encoded = $wasenc");
4106:
4107: if(defined $Dispatcher{$command}) {
4108:
4109: my $dispatch_info = $Dispatcher{$command};
4110: my $handler = $$dispatch_info[0];
4111: my $need_encode = $$dispatch_info[1];
4112: my $client_types = $$dispatch_info[2];
4113: Debug("Matched dispatch hash: mustencode: $need_encode "
4114: ."ClientType $client_types");
4115:
4116: # Validate the request:
4117:
4118: my $ok = 1;
4119: my $requesterprivs = 0;
4120: if(&isClient()) {
4121: $requesterprivs |= $CLIENT_OK;
4122: }
4123: if(&isManager()) {
4124: $requesterprivs |= $MANAGER_OK;
4125: }
4126: if($need_encode && (!$wasenc)) {
4127: Debug("Must encode but wasn't: $need_encode $wasenc");
4128: $ok = 0;
4129: }
4130: if(($client_types & $requesterprivs) == 0) {
4131: Debug("Client not privileged to do this operation");
4132: $ok = 0;
4133: }
4134:
4135: if($ok) {
4136: Debug("Dispatching to handler $command $tail");
4137: my $keep_going = &$handler($command, $tail, $client);
4138: return $keep_going;
4139: } else {
4140: Debug("Refusing to dispatch because client did not match requirements");
4141: Failure($client, "refused\n", $userinput);
4142: return 1;
4143: }
4144:
4145: }
4146:
1.262 foxr 4147: print $client "unknown_cmd\n";
1.212 foxr 4148: # -------------------------------------------------------------------- complete
4149: Debug("process_request - returning 1");
4150: return 1;
4151: }
1.207 foxr 4152: #
4153: # Decipher encoded traffic
4154: # Parameters:
4155: # input - Encoded data.
4156: # Returns:
4157: # Decoded data or undef if encryption key was not yet negotiated.
4158: # Implicit input:
4159: # cipher - This global holds the negotiated encryption key.
4160: #
1.211 albertel 4161: sub decipher {
1.207 foxr 4162: my ($input) = @_;
4163: my $output = '';
1.212 foxr 4164:
4165:
1.207 foxr 4166: if($cipher) {
4167: my($enc, $enclength, $encinput) = split(/:/, $input);
4168: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
4169: $output .=
4170: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
4171: }
4172: return substr($output, 0, $enclength);
4173: } else {
4174: return undef;
4175: }
4176: }
4177:
4178: #
4179: # Register a command processor. This function is invoked to register a sub
4180: # to process a request. Once registered, the ProcessRequest sub can automatically
4181: # dispatch requests to an appropriate sub, and do the top level validity checking
4182: # as well:
4183: # - Is the keyword recognized.
4184: # - Is the proper client type attempting the request.
4185: # - Is the request encrypted if it has to be.
4186: # Parameters:
4187: # $request_name - Name of the request being registered.
4188: # This is the command request that will match
4189: # against the hash keywords to lookup the information
4190: # associated with the dispatch information.
4191: # $procedure - Reference to a sub to call to process the request.
4192: # All subs get called as follows:
4193: # Procedure($cmd, $tail, $replyfd, $key)
4194: # $cmd - the actual keyword that invoked us.
4195: # $tail - the tail of the request that invoked us.
4196: # $replyfd- File descriptor connected to the client
4197: # $must_encode - True if the request must be encoded to be good.
4198: # $client_ok - True if it's ok for a client to request this.
4199: # $manager_ok - True if it's ok for a manager to request this.
4200: # Side effects:
4201: # - On success, the Dispatcher hash has an entry added for the key $RequestName
4202: # - On failure, the program will die as it's a bad internal bug to try to
4203: # register a duplicate command handler.
4204: #
1.211 albertel 4205: sub register_handler {
1.212 foxr 4206: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
1.207 foxr 4207:
4208: # Don't allow duplication#
4209:
4210: if (defined $Dispatcher{$request_name}) {
4211: die "Attempting to define a duplicate request handler for $request_name\n";
4212: }
4213: # Build the client type mask:
4214:
4215: my $client_type_mask = 0;
4216: if($client_ok) {
4217: $client_type_mask |= $CLIENT_OK;
4218: }
4219: if($manager_ok) {
4220: $client_type_mask |= $MANAGER_OK;
4221: }
4222:
4223: # Enter the hash:
4224:
4225: my @entry = ($procedure, $must_encode, $client_type_mask);
4226:
4227: $Dispatcher{$request_name} = \@entry;
4228:
4229: }
4230:
4231:
4232: #------------------------------------------------------------------
4233:
4234:
4235:
4236:
1.141 foxr 4237: #
1.96 foxr 4238: # Convert an error return code from lcpasswd to a string value.
4239: #
4240: sub lcpasswdstrerror {
4241: my $ErrorCode = shift;
1.97 foxr 4242: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 4243: return "lcpasswd Unrecognized error return value ".$ErrorCode;
4244: } else {
1.98 foxr 4245: return $passwderrors[$ErrorCode];
1.96 foxr 4246: }
4247: }
4248:
1.97 foxr 4249: #
4250: # Convert an error return code from lcuseradd to a string value:
4251: #
4252: sub lcuseraddstrerror {
4253: my $ErrorCode = shift;
4254: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
4255: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
4256: } else {
1.98 foxr 4257: return $adderrors[$ErrorCode];
1.97 foxr 4258: }
4259: }
4260:
1.23 harris41 4261: # grabs exception and records it to log before exiting
4262: sub catchexception {
1.27 albertel 4263: my ($error)=@_;
1.25 www 4264: $SIG{'QUIT'}='DEFAULT';
4265: $SIG{__DIE__}='DEFAULT';
1.165 albertel 4266: &status("Catching exception");
1.190 albertel 4267: &logthis("<font color='red'>CRITICAL: "
1.134 albertel 4268: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27 albertel 4269: ."a crash with this error msg->[$error]</font>");
1.57 www 4270: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 4271: if ($client) { print $client "error: $error\n"; }
1.59 www 4272: $server->close();
1.27 albertel 4273: die($error);
1.23 harris41 4274: }
1.63 www 4275: sub timeout {
1.165 albertel 4276: &status("Handling Timeout");
1.190 albertel 4277: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63 www 4278: &catchexception('Timeout');
4279: }
1.22 harris41 4280: # -------------------------------- Set signal handlers to record abnormal exits
4281:
1.226 foxr 4282:
1.22 harris41 4283: $SIG{'QUIT'}=\&catchexception;
4284: $SIG{__DIE__}=\&catchexception;
4285:
1.81 matthew 4286: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 4287: &status("Read loncapa.conf and loncapa_apache.conf");
4288: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 4289: %perlvar=%{$perlvarref};
1.80 harris41 4290: undef $perlvarref;
1.19 www 4291:
1.35 harris41 4292: # ----------------------------- Make sure this process is running from user=www
4293: my $wwwid=getpwnam('www');
4294: if ($wwwid!=$<) {
1.134 albertel 4295: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
4296: my $subj="LON: $currenthostid User ID mismatch";
1.37 harris41 4297: system("echo 'User ID mismatch. lond must be run as user www.' |\
1.35 harris41 4298: mailto $emailto -s '$subj' > /dev/null");
4299: exit 1;
4300: }
4301:
1.19 www 4302: # --------------------------------------------- Check if other instance running
4303:
4304: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
4305:
4306: if (-e $pidfile) {
4307: my $lfh=IO::File->new("$pidfile");
4308: my $pide=<$lfh>;
4309: chomp($pide);
1.29 harris41 4310: if (kill 0 => $pide) { die "already running"; }
1.19 www 4311: }
1.1 albertel 4312:
4313: # ------------------------------------------------------------- Read hosts file
4314:
4315:
4316:
4317: # establish SERVER socket, bind and listen.
4318: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
4319: Type => SOCK_STREAM,
4320: Proto => 'tcp',
4321: Reuse => 1,
4322: Listen => 10 )
1.29 harris41 4323: or die "making socket: $@\n";
1.1 albertel 4324:
4325: # --------------------------------------------------------- Do global variables
4326:
4327: # global variables
4328:
1.134 albertel 4329: my %children = (); # keys are current child process IDs
1.1 albertel 4330:
4331: sub REAPER { # takes care of dead children
4332: $SIG{CHLD} = \&REAPER;
1.165 albertel 4333: &status("Handling child death");
1.178 foxr 4334: my $pid;
4335: do {
4336: $pid = waitpid(-1,&WNOHANG());
4337: if (defined($children{$pid})) {
4338: &logthis("Child $pid died");
4339: delete($children{$pid});
1.183 albertel 4340: } elsif ($pid > 0) {
1.178 foxr 4341: &logthis("Unknown Child $pid died");
4342: }
4343: } while ( $pid > 0 );
4344: foreach my $child (keys(%children)) {
4345: $pid = waitpid($child,&WNOHANG());
4346: if ($pid > 0) {
4347: &logthis("Child $child - $pid looks like we missed it's death");
4348: delete($children{$pid});
4349: }
1.176 albertel 4350: }
1.165 albertel 4351: &status("Finished Handling child death");
1.1 albertel 4352: }
4353:
4354: sub HUNTSMAN { # signal handler for SIGINT
1.165 albertel 4355: &status("Killing children (INT)");
1.1 albertel 4356: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
4357: kill 'INT' => keys %children;
1.59 www 4358: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 4359: my $execdir=$perlvar{'lonDaemons'};
4360: unlink("$execdir/logs/lond.pid");
1.190 albertel 4361: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165 albertel 4362: &status("Done killing children");
1.1 albertel 4363: exit; # clean up with dignity
4364: }
4365:
4366: sub HUPSMAN { # signal handler for SIGHUP
4367: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.165 albertel 4368: &status("Killing children for restart (HUP)");
1.1 albertel 4369: kill 'INT' => keys %children;
1.59 www 4370: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190 albertel 4371: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134 albertel 4372: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 4373: unlink("$execdir/logs/lond.pid");
1.165 albertel 4374: &status("Restarting self (HUP)");
1.1 albertel 4375: exec("$execdir/lond"); # here we go again
4376: }
4377:
1.144 foxr 4378: #
1.148 foxr 4379: # Kill off hashes that describe the host table prior to re-reading it.
4380: # Hashes affected are:
1.200 matthew 4381: # %hostid, %hostdom %hostip %hostdns.
1.148 foxr 4382: #
4383: sub KillHostHashes {
4384: foreach my $key (keys %hostid) {
4385: delete $hostid{$key};
4386: }
4387: foreach my $key (keys %hostdom) {
4388: delete $hostdom{$key};
4389: }
4390: foreach my $key (keys %hostip) {
4391: delete $hostip{$key};
4392: }
1.200 matthew 4393: foreach my $key (keys %hostdns) {
4394: delete $hostdns{$key};
4395: }
1.148 foxr 4396: }
4397: #
4398: # Read in the host table from file and distribute it into the various hashes:
4399: #
4400: # - %hostid - Indexed by IP, the loncapa hostname.
4401: # - %hostdom - Indexed by loncapa hostname, the domain.
4402: # - %hostip - Indexed by hostid, the Ip address of the host.
4403: sub ReadHostTable {
4404:
4405: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200 matthew 4406: my $myloncapaname = $perlvar{'lonHostID'};
4407: Debug("My loncapa name is : $myloncapaname");
1.296 albertel 4408: my %name_to_ip;
1.148 foxr 4409: while (my $configline=<CONFIG>) {
1.277 albertel 4410: if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
4411: my ($id,$domain,$role,$name)=split(/:/,$configline);
4412: $name=~s/\s//g;
1.296 albertel 4413: my $ip;
4414: if (!exists($name_to_ip{$name})) {
4415: $ip = gethostbyname($name);
4416: if (!$ip || length($ip) ne 4) {
4417: &logthis("Skipping host $id name $name no IP found\n");
4418: next;
4419: }
4420: $ip=inet_ntoa($ip);
4421: $name_to_ip{$name} = $ip;
4422: } else {
4423: $ip = $name_to_ip{$name};
1.277 albertel 4424: }
1.200 matthew 4425: $hostid{$ip}=$id; # LonCAPA name of host by IP.
4426: $hostdom{$id}=$domain; # LonCAPA domain name of host.
1.277 albertel 4427: $hostip{$id}=$ip; # IP address of host.
1.200 matthew 4428: $hostdns{$name} = $id; # LonCAPA name of host by DNS.
4429:
4430: if ($id eq $perlvar{'lonHostID'}) {
4431: Debug("Found me in the host table: $name");
4432: $thisserver=$name;
4433: }
1.178 foxr 4434: }
1.148 foxr 4435: }
4436: close(CONFIG);
4437: }
4438: #
4439: # Reload the Apache daemon's state.
1.150 foxr 4440: # This is done by invoking /home/httpd/perl/apachereload
4441: # a setuid perl script that can be root for us to do this job.
1.148 foxr 4442: #
4443: sub ReloadApache {
1.150 foxr 4444: my $execdir = $perlvar{'lonDaemons'};
4445: my $script = $execdir."/apachereload";
4446: system($script);
1.148 foxr 4447: }
4448:
4449: #
1.144 foxr 4450: # Called in response to a USR2 signal.
4451: # - Reread hosts.tab
4452: # - All children connected to hosts that were removed from hosts.tab
4453: # are killed via SIGINT
4454: # - All children connected to previously existing hosts are sent SIGUSR1
4455: # - Our internal hosts hash is updated to reflect the new contents of
4456: # hosts.tab causing connections from hosts added to hosts.tab to
4457: # now be honored.
4458: #
4459: sub UpdateHosts {
1.165 albertel 4460: &status("Reload hosts.tab");
1.147 foxr 4461: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 4462: #
4463: # The %children hash has the set of IP's we currently have children
4464: # on. These need to be matched against records in the hosts.tab
4465: # Any ip's no longer in the table get killed off they correspond to
4466: # either dropped or changed hosts. Note that the re-read of the table
4467: # will take care of new and changed hosts as connections come into being.
4468:
4469:
4470: KillHostHashes;
4471: ReadHostTable;
4472:
4473: foreach my $child (keys %children) {
4474: my $childip = $children{$child};
4475: if(!$hostid{$childip}) {
1.149 foxr 4476: logthis('<font color="blue"> UpdateHosts killing child '
4477: ." $child for ip $childip </font>");
1.148 foxr 4478: kill('INT', $child);
1.149 foxr 4479: } else {
4480: logthis('<font color="green"> keeping child for ip '
4481: ." $childip (pid=$child) </font>");
1.148 foxr 4482: }
4483: }
4484: ReloadApache;
1.165 albertel 4485: &status("Finished reloading hosts.tab");
1.144 foxr 4486: }
4487:
1.148 foxr 4488:
1.57 www 4489: sub checkchildren {
1.165 albertel 4490: &status("Checking on the children (sending signals)");
1.57 www 4491: &initnewstatus();
4492: &logstatus();
4493: &logthis('Going to check on the children');
1.134 albertel 4494: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 4495: foreach (sort keys %children) {
1.221 albertel 4496: #sleep 1;
1.57 www 4497: unless (kill 'USR1' => $_) {
4498: &logthis ('Child '.$_.' is dead');
4499: &logstatus($$.' is dead');
1.221 albertel 4500: delete($children{$_});
1.57 www 4501: }
1.61 harris41 4502: }
1.63 www 4503: sleep 5;
1.212 foxr 4504: $SIG{ALRM} = sub { Debug("timeout");
4505: die "timeout"; };
1.113 albertel 4506: $SIG{__DIE__} = 'DEFAULT';
1.165 albertel 4507: &status("Checking on the children (waiting for reports)");
1.63 www 4508: foreach (sort keys %children) {
4509: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 4510: eval {
4511: alarm(300);
1.63 www 4512: &logthis('Child '.$_.' did not respond');
1.67 albertel 4513: kill 9 => $_;
1.131 albertel 4514: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
4515: #$subj="LON: $currenthostid killed lond process $_";
4516: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
4517: #$execdir=$perlvar{'lonDaemons'};
4518: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221 albertel 4519: delete($children{$_});
1.113 albertel 4520: alarm(0);
4521: }
1.63 www 4522: }
4523: }
1.113 albertel 4524: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 4525: $SIG{__DIE__} = \&catchexception;
1.165 albertel 4526: &status("Finished checking children");
1.221 albertel 4527: &logthis('Finished Checking children');
1.57 www 4528: }
4529:
1.1 albertel 4530: # --------------------------------------------------------------------- Logging
4531:
4532: sub logthis {
4533: my $message=shift;
4534: my $execdir=$perlvar{'lonDaemons'};
4535: my $fh=IO::File->new(">>$execdir/logs/lond.log");
4536: my $now=time;
4537: my $local=localtime($now);
1.58 www 4538: $lastlog=$local.': '.$message;
1.1 albertel 4539: print $fh "$local ($$): $message\n";
4540: }
4541:
1.77 foxr 4542: # ------------------------- Conditional log if $DEBUG true.
4543: sub Debug {
4544: my $message = shift;
4545: if($DEBUG) {
4546: &logthis($message);
4547: }
4548: }
1.161 foxr 4549:
4550: #
4551: # Sub to do replies to client.. this gives a hook for some
4552: # debug tracing too:
4553: # Parameters:
4554: # fd - File open on client.
4555: # reply - Text to send to client.
4556: # request - Original request from client.
4557: #
4558: sub Reply {
1.192 foxr 4559: my ($fd, $reply, $request) = @_;
1.161 foxr 4560: print $fd $reply;
4561: Debug("Request was $request Reply was $reply");
4562:
1.212 foxr 4563: $Transactions++;
4564: }
4565:
4566:
4567: #
4568: # Sub to report a failure.
4569: # This function:
4570: # - Increments the failure statistic counters.
4571: # - Invokes Reply to send the error message to the client.
4572: # Parameters:
4573: # fd - File descriptor open on the client
4574: # reply - Reply text to emit.
4575: # request - The original request message (used by Reply
4576: # to debug if that's enabled.
4577: # Implicit outputs:
4578: # $Failures- The number of failures is incremented.
4579: # Reply (invoked here) sends a message to the
4580: # client:
4581: #
4582: sub Failure {
4583: my $fd = shift;
4584: my $reply = shift;
4585: my $request = shift;
4586:
4587: $Failures++;
4588: Reply($fd, $reply, $request); # That's simple eh?
1.161 foxr 4589: }
1.57 www 4590: # ------------------------------------------------------------------ Log status
4591:
4592: sub logstatus {
1.178 foxr 4593: &status("Doing logging");
4594: my $docdir=$perlvar{'lonDocRoot'};
4595: {
4596: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200 matthew 4597: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178 foxr 4598: $fh->close();
4599: }
1.221 albertel 4600: &status("Finished $$.txt");
4601: {
4602: open(LOG,">>$docdir/lon-status/londstatus.txt");
4603: flock(LOG,LOCK_EX);
4604: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
4605: .$status."\t".$lastlog."\t $keymode\n";
1.275 albertel 4606: flock(LOG,LOCK_UN);
1.221 albertel 4607: close(LOG);
4608: }
1.178 foxr 4609: &status("Finished logging");
1.57 www 4610: }
4611:
4612: sub initnewstatus {
4613: my $docdir=$perlvar{'lonDocRoot'};
4614: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
4615: my $now=time;
4616: my $local=localtime($now);
4617: print $fh "LOND status $local - parent $$\n\n";
1.64 www 4618: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 4619: while (my $filename=readdir(DIR)) {
1.64 www 4620: unlink("$docdir/lon-status/londchld/$filename");
4621: }
4622: closedir(DIR);
1.57 www 4623: }
4624:
4625: # -------------------------------------------------------------- Status setting
4626:
4627: sub status {
4628: my $what=shift;
4629: my $now=time;
4630: my $local=localtime($now);
1.178 foxr 4631: $status=$local.': '.$what;
4632: $0='lond: '.$what.' '.$local;
1.57 www 4633: }
1.11 www 4634:
4635: # -------------------------------------------------------- Escape Special Chars
4636:
4637: sub escape {
4638: my $str=shift;
4639: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
4640: return $str;
4641: }
4642:
4643: # ----------------------------------------------------- Un-Escape Special Chars
4644:
4645: sub unescape {
4646: my $str=shift;
4647: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
4648: return $str;
4649: }
4650:
1.1 albertel 4651: # ----------------------------------------------------------- Send USR1 to lonc
4652:
4653: sub reconlonc {
4654: my $peerfile=shift;
4655: &logthis("Trying to reconnect for $peerfile");
4656: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
4657: if (my $fh=IO::File->new("$loncfile")) {
4658: my $loncpid=<$fh>;
4659: chomp($loncpid);
4660: if (kill 0 => $loncpid) {
4661: &logthis("lonc at pid $loncpid responding, sending USR1");
4662: kill USR1 => $loncpid;
4663: } else {
1.9 www 4664: &logthis(
1.190 albertel 4665: "<font color='red'>CRITICAL: "
1.9 www 4666: ."lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 4667: }
4668: } else {
1.190 albertel 4669: &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1 albertel 4670: }
4671: }
4672:
4673: # -------------------------------------------------- Non-critical communication
1.11 www 4674:
1.1 albertel 4675: sub subreply {
4676: my ($cmd,$server)=@_;
4677: my $peerfile="$perlvar{'lonSockDir'}/$server";
4678: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
4679: Type => SOCK_STREAM,
4680: Timeout => 10)
4681: or return "con_lost";
4682: print $sclient "$cmd\n";
4683: my $answer=<$sclient>;
4684: chomp($answer);
4685: if (!$answer) { $answer="con_lost"; }
4686: return $answer;
4687: }
4688:
4689: sub reply {
4690: my ($cmd,$server)=@_;
4691: my $answer;
1.115 albertel 4692: if ($server ne $currenthostid) {
1.1 albertel 4693: $answer=subreply($cmd,$server);
4694: if ($answer eq 'con_lost') {
4695: $answer=subreply("ping",$server);
4696: if ($answer ne $server) {
1.115 albertel 4697: &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1 albertel 4698: &reconlonc("$perlvar{'lonSockDir'}/$server");
4699: }
4700: $answer=subreply($cmd,$server);
4701: }
4702: } else {
4703: $answer='self_reply';
4704: }
4705: return $answer;
4706: }
4707:
1.13 www 4708: # -------------------------------------------------------------- Talk to lonsql
4709:
1.234 foxr 4710: sub sql_reply {
1.12 harris41 4711: my ($cmd)=@_;
1.234 foxr 4712: my $answer=&sub_sql_reply($cmd);
4713: if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12 harris41 4714: return $answer;
4715: }
4716:
1.234 foxr 4717: sub sub_sql_reply {
1.12 harris41 4718: my ($cmd)=@_;
4719: my $unixsock="mysqlsock";
4720: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
4721: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
4722: Type => SOCK_STREAM,
4723: Timeout => 10)
4724: or return "con_lost";
4725: print $sclient "$cmd\n";
4726: my $answer=<$sclient>;
4727: chomp($answer);
4728: if (!$answer) { $answer="con_lost"; }
4729: return $answer;
4730: }
4731:
1.1 albertel 4732: # -------------------------------------------- Return path to profile directory
1.11 www 4733:
1.1 albertel 4734: sub propath {
4735: my ($udom,$uname)=@_;
4736: $udom=~s/\W//g;
4737: $uname=~s/\W//g;
1.16 www 4738: my $subdir=$uname.'__';
1.1 albertel 4739: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
4740: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
4741: return $proname;
4742: }
4743:
4744: # --------------------------------------- Is this the home server of an author?
1.11 www 4745:
1.1 albertel 4746: sub ishome {
4747: my $author=shift;
4748: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
4749: my ($udom,$uname)=split(/\//,$author);
4750: my $proname=propath($udom,$uname);
4751: if (-e $proname) {
4752: return 'owner';
4753: } else {
4754: return 'not_owner';
4755: }
4756: }
4757:
4758: # ======================================================= Continue main program
4759: # ---------------------------------------------------- Fork once and dissociate
4760:
1.134 albertel 4761: my $fpid=fork;
1.1 albertel 4762: exit if $fpid;
1.29 harris41 4763: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 4764:
1.29 harris41 4765: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 4766:
4767: # ------------------------------------------------------- Write our PID on disk
4768:
1.134 albertel 4769: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 4770: open (PIDSAVE,">$execdir/logs/lond.pid");
4771: print PIDSAVE "$$\n";
4772: close(PIDSAVE);
1.190 albertel 4773: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57 www 4774: &status('Starting');
1.1 albertel 4775:
1.106 foxr 4776:
1.1 albertel 4777:
4778: # ----------------------------------------------------- Install signal handlers
4779:
1.57 www 4780:
1.1 albertel 4781: $SIG{CHLD} = \&REAPER;
4782: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
4783: $SIG{HUP} = \&HUPSMAN;
1.57 www 4784: $SIG{USR1} = \&checkchildren;
1.144 foxr 4785: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 4786:
1.148 foxr 4787: # Read the host hashes:
4788:
4789: ReadHostTable;
1.106 foxr 4790:
1.286 albertel 4791: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
4792:
1.106 foxr 4793: # --------------------------------------------------------------
4794: # Accept connections. When a connection comes in, it is validated
4795: # and if good, a child process is created to process transactions
4796: # along the connection.
4797:
1.1 albertel 4798: while (1) {
1.165 albertel 4799: &status('Starting accept');
1.106 foxr 4800: $client = $server->accept() or next;
1.165 albertel 4801: &status('Accepted '.$client.' off to spawn');
1.106 foxr 4802: make_new_child($client);
1.165 albertel 4803: &status('Finished spawning');
1.1 albertel 4804: }
4805:
1.212 foxr 4806: sub make_new_child {
4807: my $pid;
4808: # my $cipher; # Now global
4809: my $sigset;
1.178 foxr 4810:
1.212 foxr 4811: $client = shift;
4812: &status('Starting new child '.$client);
4813: &logthis('<font color="green"> Attempting to start child ('.$client.
4814: ")</font>");
4815: # block signal for fork
4816: $sigset = POSIX::SigSet->new(SIGINT);
4817: sigprocmask(SIG_BLOCK, $sigset)
4818: or die "Can't block SIGINT for fork: $!\n";
1.178 foxr 4819:
1.212 foxr 4820: die "fork: $!" unless defined ($pid = fork);
1.178 foxr 4821:
1.212 foxr 4822: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
4823: # connection liveness.
1.178 foxr 4824:
1.212 foxr 4825: #
4826: # Figure out who we're talking to so we can record the peer in
4827: # the pid hash.
4828: #
4829: my $caller = getpeername($client);
4830: my ($port,$iaddr);
4831: if (defined($caller) && length($caller) > 0) {
4832: ($port,$iaddr)=unpack_sockaddr_in($caller);
4833: } else {
4834: &logthis("Unable to determine who caller was, getpeername returned nothing");
4835: }
4836: if (defined($iaddr)) {
4837: $clientip = inet_ntoa($iaddr);
4838: Debug("Connected with $clientip");
4839: } else {
4840: &logthis("Unable to determine clientip");
4841: $clientip='Unavailable';
4842: }
4843:
4844: if ($pid) {
4845: # Parent records the child's birth and returns.
4846: sigprocmask(SIG_UNBLOCK, $sigset)
4847: or die "Can't unblock SIGINT for fork: $!\n";
4848: $children{$pid} = $clientip;
4849: &status('Started child '.$pid);
4850: return;
4851: } else {
4852: # Child can *not* return from this subroutine.
4853: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
4854: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
4855: #don't get intercepted
4856: $SIG{USR1}= \&logstatus;
4857: $SIG{ALRM}= \&timeout;
4858: $lastlog='Forked ';
4859: $status='Forked';
1.178 foxr 4860:
1.212 foxr 4861: # unblock signals
4862: sigprocmask(SIG_UNBLOCK, $sigset)
4863: or die "Can't unblock SIGINT for fork: $!\n";
1.178 foxr 4864:
1.212 foxr 4865: # my $tmpsnum=0; # Now global
4866: #---------------------------------------------------- kerberos 5 initialization
4867: &Authen::Krb5::init_context();
1.297 ! raeburn 4868: unless (($dist eq 'fedora4') || ($dist eq 'suse9.3')) {
1.286 albertel 4869: &Authen::Krb5::init_ets();
4870: }
1.209 albertel 4871:
1.212 foxr 4872: &status('Accepted connection');
4873: # =============================================================================
4874: # do something with the connection
4875: # -----------------------------------------------------------------------------
4876: # see if we know client and 'check' for spoof IP by ineffective challenge
1.178 foxr 4877:
1.212 foxr 4878: ReadManagerTable; # May also be a manager!!
4879:
1.278 albertel 4880: my $outsideip=$clientip;
4881: if ($clientip eq '127.0.0.1') {
4882: $outsideip=$hostip{$perlvar{'lonHostID'}};
4883: }
4884:
4885: my $clientrec=($hostid{$outsideip} ne undef);
4886: my $ismanager=($managers{$outsideip} ne undef);
1.212 foxr 4887: $clientname = "[unknonwn]";
4888: if($clientrec) { # Establish client type.
4889: $ConnectionType = "client";
1.278 albertel 4890: $clientname = $hostid{$outsideip};
1.212 foxr 4891: if($ismanager) {
4892: $ConnectionType = "both";
4893: }
4894: } else {
4895: $ConnectionType = "manager";
1.278 albertel 4896: $clientname = $managers{$outsideip};
1.212 foxr 4897: }
4898: my $clientok;
1.178 foxr 4899:
1.212 foxr 4900: if ($clientrec || $ismanager) {
4901: &status("Waiting for init from $clientip $clientname");
4902: &logthis('<font color="yellow">INFO: Connection, '.
4903: $clientip.
4904: " ($clientname) connection type = $ConnectionType </font>" );
4905: &status("Connecting $clientip ($clientname))");
4906: my $remotereq=<$client>;
4907: chomp($remotereq);
4908: Debug("Got init: $remotereq");
4909: my $inikeyword = split(/:/, $remotereq);
4910: if ($remotereq =~ /^init/) {
4911: &sethost("sethost:$perlvar{'lonHostID'}");
4912: #
4913: # If the remote is attempting a local init... give that a try:
4914: #
4915: my ($i, $inittype) = split(/:/, $remotereq);
1.209 albertel 4916:
1.212 foxr 4917: # If the connection type is ssl, but I didn't get my
4918: # certificate files yet, then I'll drop back to
4919: # insecure (if allowed).
4920:
4921: if($inittype eq "ssl") {
4922: my ($ca, $cert) = lonssl::CertificateFile;
4923: my $kfile = lonssl::KeyFile;
4924: if((!$ca) ||
4925: (!$cert) ||
4926: (!$kfile)) {
4927: $inittype = ""; # This forces insecure attempt.
4928: &logthis("<font color=\"blue\"> Certificates not "
4929: ."installed -- trying insecure auth</font>");
1.224 foxr 4930: } else { # SSL certificates are in place so
1.212 foxr 4931: } # Leave the inittype alone.
4932: }
4933:
4934: if($inittype eq "local") {
4935: my $key = LocalConnection($client, $remotereq);
4936: if($key) {
4937: Debug("Got local key $key");
4938: $clientok = 1;
4939: my $cipherkey = pack("H32", $key);
4940: $cipher = new IDEA($cipherkey);
4941: print $client "ok:local\n";
4942: &logthis('<font color="green"'
4943: . "Successful local authentication </font>");
4944: $keymode = "local"
1.178 foxr 4945: } else {
1.212 foxr 4946: Debug("Failed to get local key");
4947: $clientok = 0;
4948: shutdown($client, 3);
4949: close $client;
1.178 foxr 4950: }
1.212 foxr 4951: } elsif ($inittype eq "ssl") {
4952: my $key = SSLConnection($client);
4953: if ($key) {
4954: $clientok = 1;
4955: my $cipherkey = pack("H32", $key);
4956: $cipher = new IDEA($cipherkey);
4957: &logthis('<font color="green">'
4958: ."Successfull ssl authentication with $clientname </font>");
4959: $keymode = "ssl";
4960:
1.178 foxr 4961: } else {
1.212 foxr 4962: $clientok = 0;
4963: close $client;
1.178 foxr 4964: }
1.212 foxr 4965:
4966: } else {
4967: my $ok = InsecureConnection($client);
4968: if($ok) {
4969: $clientok = 1;
4970: &logthis('<font color="green">'
4971: ."Successful insecure authentication with $clientname </font>");
4972: print $client "ok\n";
4973: $keymode = "insecure";
1.178 foxr 4974: } else {
1.212 foxr 4975: &logthis('<font color="yellow">'
4976: ."Attempted insecure connection disallowed </font>");
4977: close $client;
4978: $clientok = 0;
1.178 foxr 4979:
4980: }
4981: }
1.212 foxr 4982: } else {
4983: &logthis(
4984: "<font color='blue'>WARNING: "
4985: ."$clientip failed to initialize: >$remotereq< </font>");
4986: &status('No init '.$clientip);
4987: }
4988:
4989: } else {
4990: &logthis(
4991: "<font color='blue'>WARNING: Unknown client $clientip</font>");
4992: &status('Hung up on '.$clientip);
4993: }
4994:
4995: if ($clientok) {
4996: # ---------------- New known client connecting, could mean machine online again
4997:
4998: foreach my $id (keys(%hostip)) {
4999: if ($hostip{$id} ne $clientip ||
5000: $hostip{$currenthostid} eq $clientip) {
5001: # no need to try to do recon's to myself
5002: next;
5003: }
5004: &reconlonc("$perlvar{'lonSockDir'}/$id");
5005: }
5006: &logthis("<font color='green'>Established connection: $clientname</font>");
5007: &status('Will listen to '.$clientname);
5008: # ------------------------------------------------------------ Process requests
5009: my $keep_going = 1;
5010: my $user_input;
5011: while(($user_input = get_request) && $keep_going) {
5012: alarm(120);
5013: Debug("Main: Got $user_input\n");
5014: $keep_going = &process_request($user_input);
1.178 foxr 5015: alarm(0);
1.212 foxr 5016: &status('Listening to '.$clientname." ($keymode)");
1.161 foxr 5017: }
1.212 foxr 5018:
1.59 www 5019: # --------------------------------------------- client unknown or fishy, refuse
1.212 foxr 5020: } else {
1.161 foxr 5021: print $client "refused\n";
5022: $client->close();
1.190 albertel 5023: &logthis("<font color='blue'>WARNING: "
1.161 foxr 5024: ."Rejected client $clientip, closing connection</font>");
5025: }
1.212 foxr 5026: }
1.161 foxr 5027:
1.1 albertel 5028: # =============================================================================
1.161 foxr 5029:
1.190 albertel 5030: &logthis("<font color='red'>CRITICAL: "
1.161 foxr 5031: ."Disconnect from $clientip ($clientname)</font>");
5032:
5033:
5034: # this exit is VERY important, otherwise the child will become
5035: # a producer of more and more children, forking yourself into
5036: # process death.
5037: exit;
1.106 foxr 5038:
1.78 foxr 5039: }
1.261 foxr 5040: #
5041: # Determine if a user is an author for the indicated domain.
5042: #
5043: # Parameters:
5044: # domain - domain to check in .
5045: # user - Name of user to check.
5046: #
5047: # Return:
5048: # 1 - User is an author for domain.
5049: # 0 - User is not an author for domain.
5050: sub is_author {
5051: my ($domain, $user) = @_;
5052:
5053: &Debug("is_author: $user @ $domain");
5054:
5055: my $hashref = &tie_user_hash($domain, $user, "roles",
5056: &GDBM_READER());
5057:
5058: # Author role should show up as a key /domain/_au
1.78 foxr 5059:
1.261 foxr 5060: my $key = "/$domain/_au";
5061: my $value = $hashref->{$key};
1.78 foxr 5062:
1.261 foxr 5063: if(defined($value)) {
5064: &Debug("$user @ $domain is an author");
5065: }
5066:
5067: return defined($value);
5068: }
1.78 foxr 5069: #
5070: # Checks to see if the input roleput request was to set
5071: # an author role. If so, invokes the lchtmldir script to set
5072: # up a correct public_html
5073: # Parameters:
5074: # request - The request sent to the rolesput subchunk.
5075: # We're looking for /domain/_au
5076: # domain - The domain in which the user is having roles doctored.
5077: # user - Name of the user for which the role is being put.
5078: # authtype - The authentication type associated with the user.
5079: #
1.289 albertel 5080: sub manage_permissions {
1.192 foxr 5081: my ($request, $domain, $user, $authtype) = @_;
1.78 foxr 5082:
1.261 foxr 5083: &Debug("manage_permissions: $request $domain $user $authtype");
5084:
1.78 foxr 5085: # See if the request is of the form /$domain/_au
1.289 albertel 5086: if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.78 foxr 5087: my $execdir = $perlvar{'lonDaemons'};
5088: my $userhome= "/home/$user" ;
1.134 albertel 5089: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261 foxr 5090: &Debug("Setting homedir permissions for $userhome");
1.78 foxr 5091: system("$execdir/lchtmldir $userhome $user $authtype");
5092: }
5093: }
1.222 foxr 5094:
5095:
5096: #
5097: # Return the full path of a user password file, whether it exists or not.
5098: # Parameters:
5099: # domain - Domain in which the password file lives.
5100: # user - name of the user.
5101: # Returns:
5102: # Full passwd path:
5103: #
5104: sub password_path {
5105: my ($domain, $user) = @_;
1.264 albertel 5106: return &propath($domain, $user).'/passwd';
1.222 foxr 5107: }
5108:
5109: # Password Filename
5110: # Returns the path to a passwd file given domain and user... only if
5111: # it exists.
5112: # Parameters:
5113: # domain - Domain in which to search.
5114: # user - username.
5115: # Returns:
5116: # - If the password file exists returns its path.
5117: # - If the password file does not exist, returns undefined.
5118: #
5119: sub password_filename {
5120: my ($domain, $user) = @_;
5121:
5122: Debug ("PasswordFilename called: dom = $domain user = $user");
5123:
5124: my $path = &password_path($domain, $user);
5125: Debug("PasswordFilename got path: $path");
5126: if(-e $path) {
5127: return $path;
5128: } else {
5129: return undef;
5130: }
5131: }
5132:
5133: #
5134: # Rewrite the contents of the user's passwd file.
5135: # Parameters:
5136: # domain - domain of the user.
5137: # name - User's name.
5138: # contents - New contents of the file.
5139: # Returns:
5140: # 0 - Failed.
5141: # 1 - Success.
5142: #
5143: sub rewrite_password_file {
5144: my ($domain, $user, $contents) = @_;
5145:
5146: my $file = &password_filename($domain, $user);
5147: if (defined $file) {
5148: my $pf = IO::File->new(">$file");
5149: if($pf) {
5150: print $pf "$contents\n";
5151: return 1;
5152: } else {
5153: return 0;
5154: }
5155: } else {
5156: return 0;
5157: }
5158:
5159: }
5160:
1.78 foxr 5161: #
1.222 foxr 5162: # get_auth_type - Determines the authorization type of a user in a domain.
1.78 foxr 5163:
5164: # Returns the authorization type or nouser if there is no such user.
5165: #
1.222 foxr 5166: sub get_auth_type
1.78 foxr 5167: {
1.192 foxr 5168:
5169: my ($domain, $user) = @_;
1.78 foxr 5170:
1.222 foxr 5171: Debug("get_auth_type( $domain, $user ) \n");
1.78 foxr 5172: my $proname = &propath($domain, $user);
5173: my $passwdfile = "$proname/passwd";
5174: if( -e $passwdfile ) {
5175: my $pf = IO::File->new($passwdfile);
5176: my $realpassword = <$pf>;
5177: chomp($realpassword);
1.79 foxr 5178: Debug("Password info = $realpassword\n");
1.78 foxr 5179: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 5180: Debug("Authtype = $authtype, content = $contentpwd\n");
1.259 raeburn 5181: return "$authtype:$contentpwd";
1.224 foxr 5182: } else {
1.79 foxr 5183: Debug("Returning nouser");
1.78 foxr 5184: return "nouser";
5185: }
1.1 albertel 5186: }
5187:
1.220 foxr 5188: #
5189: # Validate a user given their domain, name and password. This utility
5190: # function is used by both AuthenticateHandler and ChangePasswordHandler
5191: # to validate the login credentials of a user.
5192: # Parameters:
5193: # $domain - The domain being logged into (this is required due to
5194: # the capability for multihomed systems.
5195: # $user - The name of the user being validated.
5196: # $password - The user's propoposed password.
5197: #
5198: # Returns:
5199: # 1 - The domain,user,pasword triplet corresponds to a valid
5200: # user.
5201: # 0 - The domain,user,password triplet is not a valid user.
5202: #
5203: sub validate_user {
5204: my ($domain, $user, $password) = @_;
5205:
5206:
5207: # Why negative ~pi you may well ask? Well this function is about
5208: # authentication, and therefore very important to get right.
5209: # I've initialized the flag that determines whether or not I've
5210: # validated correctly to a value it's not supposed to get.
5211: # At the end of this function. I'll ensure that it's not still that
5212: # value so we don't just wind up returning some accidental value
5213: # as a result of executing an unforseen code path that
1.249 foxr 5214: # did not set $validated. At the end of valid execution paths,
5215: # validated shoule be 1 for success or 0 for failuer.
1.220 foxr 5216:
5217: my $validated = -3.14159;
5218:
5219: # How we authenticate is determined by the type of authentication
5220: # the user has been assigned. If the authentication type is
5221: # "nouser", the user does not exist so we will return 0.
5222:
1.222 foxr 5223: my $contents = &get_auth_type($domain, $user);
1.220 foxr 5224: my ($howpwd, $contentpwd) = split(/:/, $contents);
5225:
5226: my $null = pack("C",0); # Used by kerberos auth types.
5227:
5228: if ($howpwd ne 'nouser') {
5229:
5230: if($howpwd eq "internal") { # Encrypted is in local password file.
5231: $validated = (crypt($password, $contentpwd) eq $contentpwd);
5232: }
5233: elsif ($howpwd eq "unix") { # User is a normal unix user.
5234: $contentpwd = (getpwnam($user))[1];
5235: if($contentpwd) {
5236: if($contentpwd eq 'x') { # Shadow password file...
5237: my $pwauth_path = "/usr/local/sbin/pwauth";
5238: open PWAUTH, "|$pwauth_path" or
5239: die "Cannot invoke authentication";
5240: print PWAUTH "$user\n$password\n";
5241: close PWAUTH;
5242: $validated = ! $?;
5243:
5244: } else { # Passwords in /etc/passwd.
5245: $validated = (crypt($password,
5246: $contentpwd) eq $contentpwd);
5247: }
5248: } else {
5249: $validated = 0;
5250: }
5251: }
5252: elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
5253: if(! ($password =~ /$null/) ) {
5254: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
5255: "",
5256: $contentpwd,,
5257: 'krbtgt',
5258: $contentpwd,
5259: 1,
5260: $password);
5261: if(!$k4error) {
5262: $validated = 1;
1.224 foxr 5263: } else {
1.220 foxr 5264: $validated = 0;
5265: &logthis('krb4: '.$user.', '.$contentpwd.', '.
5266: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
5267: }
1.224 foxr 5268: } else {
1.220 foxr 5269: $validated = 0; # Password has a match with null.
5270: }
1.224 foxr 5271: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220 foxr 5272: if(!($password =~ /$null/)) { # Null password not allowed.
5273: my $krbclient = &Authen::Krb5::parse_name($user.'@'
5274: .$contentpwd);
5275: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
5276: my $krbserver = &Authen::Krb5::parse_name($krbservice);
5277: my $credentials= &Authen::Krb5::cc_default();
5278: $credentials->initialize($krbclient);
1.270 matthew 5279: my $krbreturn = &Authen::Krb5::get_in_tkt_with_password($krbclient,
1.220 foxr 5280: $krbserver,
5281: $password,
5282: $credentials);
5283: $validated = ($krbreturn == 1);
1.224 foxr 5284: } else {
1.220 foxr 5285: $validated = 0;
5286: }
1.224 foxr 5287: } elsif ($howpwd eq "localauth") {
1.220 foxr 5288: # Authenticate via installation specific authentcation method:
5289: $validated = &localauth::localauth($user,
5290: $password,
5291: $contentpwd);
1.224 foxr 5292: } else { # Unrecognized auth is also bad.
1.220 foxr 5293: $validated = 0;
5294: }
5295: } else {
5296: $validated = 0;
5297: }
5298: #
5299: # $validated has the correct stat of the authentication:
5300: #
5301:
5302: unless ($validated != -3.14159) {
1.249 foxr 5303: # I >really really< want to know if this happens.
5304: # since it indicates that user authentication is badly
5305: # broken in some code path.
5306: #
5307: die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220 foxr 5308: }
5309: return $validated;
5310: }
5311:
5312:
1.84 albertel 5313: sub addline {
5314: my ($fname,$hostid,$ip,$newline)=@_;
5315: my $contents;
5316: my $found=0;
5317: my $expr='^'.$hostid.':'.$ip.':';
5318: $expr =~ s/\./\\\./g;
1.134 albertel 5319: my $sh;
1.84 albertel 5320: if ($sh=IO::File->new("$fname.subscription")) {
5321: while (my $subline=<$sh>) {
5322: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
5323: }
5324: $sh->close();
5325: }
5326: $sh=IO::File->new(">$fname.subscription");
5327: if ($contents) { print $sh $contents; }
5328: if ($newline) { print $sh $newline; }
5329: $sh->close();
5330: return $found;
1.86 www 5331: }
5332:
1.234 foxr 5333: sub get_chat {
1.122 www 5334: my ($cdom,$cname,$udom,$uname)=@_;
1.87 www 5335: my %hash;
5336: my $proname=&propath($cdom,$cname);
5337: my @entries=();
1.88 albertel 5338: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
5339: &GDBM_READER(),0640)) {
5340: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
5341: untie %hash;
1.123 www 5342: }
1.124 www 5343: my @participants=();
1.134 albertel 5344: my $cutoff=time-60;
1.123 www 5345: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124 www 5346: &GDBM_WRCREAT(),0640)) {
5347: $hash{$uname.':'.$udom}=time;
1.123 www 5348: foreach (sort keys %hash) {
5349: if ($hash{$_}>$cutoff) {
1.124 www 5350: $participants[$#participants+1]='active_participant:'.$_;
1.123 www 5351: }
5352: }
5353: untie %hash;
1.86 www 5354: }
1.124 www 5355: return (@participants,@entries);
1.86 www 5356: }
5357:
1.234 foxr 5358: sub chat_add {
1.88 albertel 5359: my ($cdom,$cname,$newchat)=@_;
5360: my %hash;
5361: my $proname=&propath($cdom,$cname);
5362: my @entries=();
1.142 www 5363: my $time=time;
1.88 albertel 5364: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
5365: &GDBM_WRCREAT(),0640)) {
5366: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
5367: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
5368: my ($thentime,$idnum)=split(/\_/,$lastid);
5369: my $newid=$time.'_000000';
5370: if ($thentime==$time) {
5371: $idnum=~s/^0+//;
5372: $idnum++;
5373: $idnum=substr('000000'.$idnum,-6,6);
5374: $newid=$time.'_'.$idnum;
5375: }
5376: $hash{$newid}=$newchat;
5377: my $expired=$time-3600;
5378: foreach (keys %hash) {
5379: my ($thistime)=($_=~/(\d+)\_/);
5380: if ($thistime<$expired) {
1.89 www 5381: delete $hash{$_};
1.88 albertel 5382: }
5383: }
5384: untie %hash;
1.142 www 5385: }
5386: {
5387: my $hfh;
5388: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
5389: print $hfh "$time:".&unescape($newchat)."\n";
5390: }
1.86 www 5391: }
1.84 albertel 5392: }
5393:
5394: sub unsub {
5395: my ($fname,$clientip)=@_;
5396: my $result;
1.188 foxr 5397: my $unsubs = 0; # Number of successful unsubscribes:
5398:
5399:
5400: # An old way subscriptions were handled was to have a
5401: # subscription marker file:
5402:
5403: Debug("Attempting unlink of $fname.$clientname");
1.161 foxr 5404: if (unlink("$fname.$clientname")) {
1.188 foxr 5405: $unsubs++; # Successful unsub via marker file.
5406: }
5407:
5408: # The more modern way to do it is to have a subscription list
5409: # file:
5410:
1.84 albertel 5411: if (-e "$fname.subscription") {
1.161 foxr 5412: my $found=&addline($fname,$clientname,$clientip,'');
1.188 foxr 5413: if ($found) {
5414: $unsubs++;
5415: }
5416: }
5417:
5418: # If either or both of these mechanisms succeeded in unsubscribing a
5419: # resource we can return ok:
5420:
5421: if($unsubs) {
5422: $result = "ok\n";
1.84 albertel 5423: } else {
1.188 foxr 5424: $result = "not_subscribed\n";
1.84 albertel 5425: }
1.188 foxr 5426:
1.84 albertel 5427: return $result;
5428: }
5429:
1.101 www 5430: sub currentversion {
5431: my $fname=shift;
5432: my $version=-1;
5433: my $ulsdir='';
5434: if ($fname=~/^(.+)\/[^\/]+$/) {
5435: $ulsdir=$1;
5436: }
1.114 albertel 5437: my ($fnamere1,$fnamere2);
5438: # remove version if already specified
1.101 www 5439: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 5440: # get the bits that go before and after the version number
5441: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
5442: $fnamere1=$1;
5443: $fnamere2='.'.$2;
5444: }
1.101 www 5445: if (-e $fname) { $version=1; }
5446: if (-e $ulsdir) {
1.134 albertel 5447: if(-d $ulsdir) {
5448: if (opendir(LSDIR,$ulsdir)) {
5449: my $ulsfn;
5450: while ($ulsfn=readdir(LSDIR)) {
1.101 www 5451: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 5452: my $thisfile=$ulsdir.'/'.$ulsfn;
5453: unless (-l $thisfile) {
1.160 www 5454: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 5455: if ($1>$version) { $version=$1; }
5456: }
5457: }
5458: }
5459: closedir(LSDIR);
5460: $version++;
5461: }
5462: }
5463: }
5464: return $version;
1.101 www 5465: }
5466:
5467: sub thisversion {
5468: my $fname=shift;
5469: my $version=-1;
5470: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
5471: $version=$1;
5472: }
5473: return $version;
5474: }
5475:
1.84 albertel 5476: sub subscribe {
5477: my ($userinput,$clientip)=@_;
5478: my $result;
1.293 albertel 5479: my ($cmd,$fname)=split(/:/,$userinput,2);
1.84 albertel 5480: my $ownership=&ishome($fname);
5481: if ($ownership eq 'owner') {
1.101 www 5482: # explitly asking for the current version?
5483: unless (-e $fname) {
5484: my $currentversion=¤tversion($fname);
5485: if (&thisversion($fname)==$currentversion) {
5486: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
5487: my $root=$1;
5488: my $extension=$2;
5489: symlink($root.'.'.$extension,
5490: $root.'.'.$currentversion.'.'.$extension);
1.102 www 5491: unless ($extension=~/\.meta$/) {
5492: symlink($root.'.'.$extension.'.meta',
5493: $root.'.'.$currentversion.'.'.$extension.'.meta');
5494: }
1.101 www 5495: }
5496: }
5497: }
1.84 albertel 5498: if (-e $fname) {
5499: if (-d $fname) {
5500: $result="directory\n";
5501: } else {
1.161 foxr 5502: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 5503: my $now=time;
1.161 foxr 5504: my $found=&addline($fname,$clientname,$clientip,
5505: "$clientname:$clientip:$now\n");
1.84 albertel 5506: if ($found) { $result="$fname\n"; }
5507: # if they were subscribed to only meta data, delete that
5508: # subscription, when you subscribe to a file you also get
5509: # the metadata
5510: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
5511: $fname=~s/\/home\/httpd\/html\/res/raw/;
5512: $fname="http://$thisserver/".$fname;
5513: $result="$fname\n";
5514: }
5515: } else {
5516: $result="not_found\n";
5517: }
5518: } else {
5519: $result="rejected\n";
5520: }
5521: return $result;
5522: }
1.287 foxr 5523: # Change the passwd of a unix user. The caller must have
5524: # first verified that the user is a loncapa user.
5525: #
5526: # Parameters:
5527: # user - Unix user name to change.
5528: # pass - New password for the user.
5529: # Returns:
5530: # ok - if success
5531: # other - Some meaningfule error message string.
5532: # NOTE:
5533: # invokes a setuid script to change the passwd.
5534: sub change_unix_password {
5535: my ($user, $pass) = @_;
5536:
5537: &Debug("change_unix_password");
5538: my $execdir=$perlvar{'lonDaemons'};
5539: &Debug("Opening lcpasswd pipeline");
5540: my $pf = IO::File->new("|$execdir/lcpasswd > "
5541: ."$perlvar{'lonDaemons'}"
5542: ."/logs/lcpasswd.log");
5543: print $pf "$user\n$pass\n$pass\n";
5544: close $pf;
5545: my $err = $?;
5546: return ($err < @passwderrors) ? $passwderrors[$err] :
5547: "pwchange_falure - unknown error";
5548:
5549:
5550: }
5551:
1.91 albertel 5552:
5553: sub make_passwd_file {
1.98 foxr 5554: my ($uname, $umode,$npass,$passfilename)=@_;
1.91 albertel 5555: my $result="ok\n";
5556: if ($umode eq 'krb4' or $umode eq 'krb5') {
5557: {
5558: my $pf = IO::File->new(">$passfilename");
1.261 foxr 5559: if ($pf) {
5560: print $pf "$umode:$npass\n";
5561: } else {
5562: $result = "pass_file_failed_error";
5563: }
1.91 albertel 5564: }
5565: } elsif ($umode eq 'internal') {
5566: my $salt=time;
5567: $salt=substr($salt,6,2);
5568: my $ncpass=crypt($npass,$salt);
5569: {
5570: &Debug("Creating internal auth");
5571: my $pf = IO::File->new(">$passfilename");
1.261 foxr 5572: if($pf) {
5573: print $pf "internal:$ncpass\n";
5574: } else {
5575: $result = "pass_file_failed_error";
5576: }
1.91 albertel 5577: }
5578: } elsif ($umode eq 'localauth') {
5579: {
5580: my $pf = IO::File->new(">$passfilename");
1.261 foxr 5581: if($pf) {
5582: print $pf "localauth:$npass\n";
5583: } else {
5584: $result = "pass_file_failed_error";
5585: }
1.91 albertel 5586: }
5587: } elsif ($umode eq 'unix') {
5588: {
1.186 foxr 5589: #
5590: # Don't allow the creation of privileged accounts!!! that would
5591: # be real bad!!!
5592: #
5593: my $uid = getpwnam($uname);
5594: if((defined $uid) && ($uid == 0)) {
5595: &logthis(">>>Attempted to create privilged account blocked");
5596: return "no_priv_account_error\n";
5597: }
5598:
1.223 foxr 5599: my $execpath ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224 foxr 5600:
5601: my $lc_error_file = $execdir."/tmp/lcuseradd".$$.".status";
1.91 albertel 5602: {
5603: &Debug("Executing external: ".$execpath);
1.98 foxr 5604: &Debug("user = ".$uname.", Password =". $npass);
1.132 matthew 5605: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91 albertel 5606: print $se "$uname\n";
5607: print $se "$npass\n";
5608: print $se "$npass\n";
1.223 foxr 5609: print $se "$lc_error_file\n"; # Status -> unique file.
1.97 foxr 5610: }
1.285 foxr 5611: if (-r $lc_error_file) {
5612: &Debug("Opening error file: $lc_error_file");
5613: my $error = IO::File->new("< $lc_error_file");
5614: my $useraddok = <$error>;
5615: $error->close;
5616: unlink($lc_error_file);
5617:
5618: chomp $useraddok;
5619:
5620: if($useraddok > 0) {
5621: my $error_text = &lcuseraddstrerror($useraddok);
5622: &logthis("Failed lcuseradd: $error_text");
5623: $result = "lcuseradd_failed:$error_text\n";
5624: } else {
5625: my $pf = IO::File->new(">$passfilename");
5626: if($pf) {
5627: print $pf "unix:\n";
5628: } else {
5629: $result = "pass_file_failed_error";
5630: }
5631: }
1.224 foxr 5632: } else {
1.285 foxr 5633: &Debug("Could not locate lcuseradd error: $lc_error_file");
5634: $result="bug_lcuseradd_no_output_file";
1.91 albertel 5635: }
5636: }
5637: } elsif ($umode eq 'none') {
5638: {
1.223 foxr 5639: my $pf = IO::File->new("> $passfilename");
1.261 foxr 5640: if($pf) {
5641: print $pf "none:\n";
5642: } else {
5643: $result = "pass_file_failed_error";
5644: }
1.91 albertel 5645: }
5646: } else {
5647: $result="auth_mode_error\n";
5648: }
5649: return $result;
1.121 albertel 5650: }
5651:
1.265 albertel 5652: sub convert_photo {
5653: my ($start,$dest)=@_;
5654: system("convert $start $dest");
5655: }
5656:
1.121 albertel 5657: sub sethost {
5658: my ($remotereq) = @_;
5659: my (undef,$hostid)=split(/:/,$remotereq);
5660: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
5661: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200 matthew 5662: $currenthostid =$hostid;
1.121 albertel 5663: $currentdomainid=$hostdom{$hostid};
5664: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
5665: } else {
5666: &logthis("Requested host id $hostid not an alias of ".
5667: $perlvar{'lonHostID'}." refusing connection");
5668: return 'unable_to_set';
5669: }
5670: return 'ok';
5671: }
5672:
5673: sub version {
5674: my ($userinput)=@_;
5675: $remoteVERSION=(split(/:/,$userinput))[1];
5676: return "version:$VERSION";
1.127 albertel 5677: }
1.178 foxr 5678:
1.128 albertel 5679: #There is a copy of this in lonnet.pm
1.127 albertel 5680: sub userload {
5681: my $numusers=0;
5682: {
5683: opendir(LONIDS,$perlvar{'lonIDsDir'});
5684: my $filename;
5685: my $curtime=time;
5686: while ($filename=readdir(LONIDS)) {
5687: if ($filename eq '.' || $filename eq '..') {next;}
1.138 albertel 5688: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159 albertel 5689: if ($curtime-$mtime < 1800) { $numusers++; }
1.127 albertel 5690: }
5691: closedir(LONIDS);
5692: }
5693: my $userloadpercent=0;
5694: my $maxuserload=$perlvar{'lonUserLoadLim'};
5695: if ($maxuserload) {
1.129 albertel 5696: $userloadpercent=100*$numusers/$maxuserload;
1.127 albertel 5697: }
1.130 albertel 5698: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127 albertel 5699: return $userloadpercent;
1.91 albertel 5700: }
5701:
1.205 raeburn 5702: # Routines for serializing arrays and hashes (copies from lonnet)
5703:
5704: sub array2str {
5705: my (@array) = @_;
5706: my $result=&arrayref2str(\@array);
5707: $result=~s/^__ARRAY_REF__//;
5708: $result=~s/__END_ARRAY_REF__$//;
5709: return $result;
5710: }
5711:
5712: sub arrayref2str {
5713: my ($arrayref) = @_;
5714: my $result='__ARRAY_REF__';
5715: foreach my $elem (@$arrayref) {
5716: if(ref($elem) eq 'ARRAY') {
5717: $result.=&arrayref2str($elem).'&';
5718: } elsif(ref($elem) eq 'HASH') {
5719: $result.=&hashref2str($elem).'&';
5720: } elsif(ref($elem)) {
5721: #print("Got a ref of ".(ref($elem))." skipping.");
5722: } else {
5723: $result.=&escape($elem).'&';
5724: }
5725: }
5726: $result=~s/\&$//;
5727: $result .= '__END_ARRAY_REF__';
5728: return $result;
5729: }
5730:
5731: sub hash2str {
5732: my (%hash) = @_;
5733: my $result=&hashref2str(\%hash);
5734: $result=~s/^__HASH_REF__//;
5735: $result=~s/__END_HASH_REF__$//;
5736: return $result;
5737: }
5738:
5739: sub hashref2str {
5740: my ($hashref)=@_;
5741: my $result='__HASH_REF__';
5742: foreach (sort(keys(%$hashref))) {
5743: if (ref($_) eq 'ARRAY') {
5744: $result.=&arrayref2str($_).'=';
5745: } elsif (ref($_) eq 'HASH') {
5746: $result.=&hashref2str($_).'=';
5747: } elsif (ref($_)) {
5748: $result.='=';
5749: #print("Got a ref of ".(ref($_))." skipping.");
5750: } else {
5751: if ($_) {$result.=&escape($_).'=';} else { last; }
5752: }
5753:
5754: if(ref($hashref->{$_}) eq 'ARRAY') {
5755: $result.=&arrayref2str($hashref->{$_}).'&';
5756: } elsif(ref($hashref->{$_}) eq 'HASH') {
5757: $result.=&hashref2str($hashref->{$_}).'&';
5758: } elsif(ref($hashref->{$_})) {
5759: $result.='&';
5760: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
5761: } else {
5762: $result.=&escape($hashref->{$_}).'&';
5763: }
5764: }
5765: $result=~s/\&$//;
5766: $result .= '__END_HASH_REF__';
5767: return $result;
5768: }
1.200 matthew 5769:
1.61 harris41 5770: # ----------------------------------- POD (plain old documentation, CPAN style)
5771:
5772: =head1 NAME
5773:
5774: lond - "LON Daemon" Server (port "LOND" 5663)
5775:
5776: =head1 SYNOPSIS
5777:
1.74 harris41 5778: Usage: B<lond>
5779:
5780: Should only be run as user=www. This is a command-line script which
5781: is invoked by B<loncron>. There is no expectation that a typical user
5782: will manually start B<lond> from the command-line. (In other words,
5783: DO NOT START B<lond> YOURSELF.)
1.61 harris41 5784:
5785: =head1 DESCRIPTION
5786:
1.74 harris41 5787: There are two characteristics associated with the running of B<lond>,
5788: PROCESS MANAGEMENT (starting, stopping, handling child processes)
5789: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
5790: subscriptions, etc). These are described in two large
5791: sections below.
5792:
5793: B<PROCESS MANAGEMENT>
5794:
1.61 harris41 5795: Preforker - server who forks first. Runs as a daemon. HUPs.
5796: Uses IDEA encryption
5797:
1.74 harris41 5798: B<lond> forks off children processes that correspond to the other servers
5799: in the network. Management of these processes can be done at the
5800: parent process level or the child process level.
5801:
5802: B<logs/lond.log> is the location of log messages.
5803:
5804: The process management is now explained in terms of linux shell commands,
5805: subroutines internal to this code, and signal assignments:
5806:
5807: =over 4
5808:
5809: =item *
5810:
5811: PID is stored in B<logs/lond.pid>
5812:
5813: This is the process id number of the parent B<lond> process.
5814:
5815: =item *
5816:
5817: SIGTERM and SIGINT
5818:
5819: Parent signal assignment:
5820: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
5821:
5822: Child signal assignment:
5823: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
5824: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
5825: to restart a new child.)
5826:
5827: Command-line invocations:
5828: B<kill> B<-s> SIGTERM I<PID>
5829: B<kill> B<-s> SIGINT I<PID>
5830:
5831: Subroutine B<HUNTSMAN>:
5832: This is only invoked for the B<lond> parent I<PID>.
5833: This kills all the children, and then the parent.
5834: The B<lonc.pid> file is cleared.
5835:
5836: =item *
5837:
5838: SIGHUP
5839:
5840: Current bug:
5841: This signal can only be processed the first time
5842: on the parent process. Subsequent SIGHUP signals
5843: have no effect.
5844:
5845: Parent signal assignment:
5846: $SIG{HUP} = \&HUPSMAN;
5847:
5848: Child signal assignment:
5849: none (nothing happens)
5850:
5851: Command-line invocations:
5852: B<kill> B<-s> SIGHUP I<PID>
5853:
5854: Subroutine B<HUPSMAN>:
5855: This is only invoked for the B<lond> parent I<PID>,
5856: This kills all the children, and then the parent.
5857: The B<lond.pid> file is cleared.
5858:
5859: =item *
5860:
5861: SIGUSR1
5862:
5863: Parent signal assignment:
5864: $SIG{USR1} = \&USRMAN;
5865:
5866: Child signal assignment:
5867: $SIG{USR1}= \&logstatus;
5868:
5869: Command-line invocations:
5870: B<kill> B<-s> SIGUSR1 I<PID>
5871:
5872: Subroutine B<USRMAN>:
5873: When invoked for the B<lond> parent I<PID>,
5874: SIGUSR1 is sent to all the children, and the status of
5875: each connection is logged.
1.144 foxr 5876:
5877: =item *
5878:
5879: SIGUSR2
5880:
5881: Parent Signal assignment:
5882: $SIG{USR2} = \&UpdateHosts
5883:
5884: Child signal assignment:
5885: NONE
5886:
1.74 harris41 5887:
5888: =item *
5889:
5890: SIGCHLD
5891:
5892: Parent signal assignment:
5893: $SIG{CHLD} = \&REAPER;
5894:
5895: Child signal assignment:
5896: none
5897:
5898: Command-line invocations:
5899: B<kill> B<-s> SIGCHLD I<PID>
5900:
5901: Subroutine B<REAPER>:
5902: This is only invoked for the B<lond> parent I<PID>.
5903: Information pertaining to the child is removed.
5904: The socket port is cleaned up.
5905:
5906: =back
5907:
5908: B<SERVER-SIDE ACTIVITIES>
5909:
5910: Server-side information can be accepted in an encrypted or non-encrypted
5911: method.
5912:
5913: =over 4
5914:
5915: =item ping
5916:
5917: Query a client in the hosts.tab table; "Are you there?"
5918:
5919: =item pong
5920:
5921: Respond to a ping query.
5922:
5923: =item ekey
5924:
5925: Read in encrypted key, make cipher. Respond with a buildkey.
5926:
5927: =item load
5928:
5929: Respond with CPU load based on a computation upon /proc/loadavg.
5930:
5931: =item currentauth
5932:
5933: Reply with current authentication information (only over an
5934: encrypted channel).
5935:
5936: =item auth
5937:
5938: Only over an encrypted channel, reply as to whether a user's
5939: authentication information can be validated.
5940:
5941: =item passwd
5942:
5943: Allow for a password to be set.
5944:
5945: =item makeuser
5946:
5947: Make a user.
5948:
5949: =item passwd
5950:
5951: Allow for authentication mechanism and password to be changed.
5952:
5953: =item home
1.61 harris41 5954:
1.74 harris41 5955: Respond to a question "are you the home for a given user?"
5956:
5957: =item update
5958:
5959: Update contents of a subscribed resource.
5960:
5961: =item unsubscribe
5962:
5963: The server is unsubscribing from a resource.
5964:
5965: =item subscribe
5966:
5967: The server is subscribing to a resource.
5968:
5969: =item log
5970:
5971: Place in B<logs/lond.log>
5972:
5973: =item put
5974:
5975: stores hash in namespace
5976:
1.230 foxr 5977: =item rolesputy
1.74 harris41 5978:
5979: put a role into a user's environment
5980:
5981: =item get
5982:
5983: returns hash with keys from array
5984: reference filled in from namespace
5985:
5986: =item eget
5987:
5988: returns hash with keys from array
5989: reference filled in from namesp (encrypts the return communication)
5990:
5991: =item rolesget
5992:
5993: get a role from a user's environment
5994:
5995: =item del
5996:
5997: deletes keys out of array from namespace
5998:
5999: =item keys
6000:
6001: returns namespace keys
6002:
6003: =item dump
6004:
6005: dumps the complete (or key matching regexp) namespace into a hash
6006:
6007: =item store
6008:
6009: stores hash permanently
6010: for this url; hashref needs to be given and should be a \%hashname; the
6011: remaining args aren't required and if they aren't passed or are '' they will
6012: be derived from the ENV
6013:
6014: =item restore
6015:
6016: returns a hash for a given url
6017:
6018: =item querysend
6019:
6020: Tells client about the lonsql process that has been launched in response
6021: to a sent query.
6022:
6023: =item queryreply
6024:
6025: Accept information from lonsql and make appropriate storage in temporary
6026: file space.
6027:
6028: =item idput
6029:
6030: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
6031: for each student, defined perhaps by the institutional Registrar.)
6032:
6033: =item idget
6034:
6035: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
6036: for each student, defined perhaps by the institutional Registrar.)
6037:
6038: =item tmpput
6039:
6040: Accept and store information in temporary space.
6041:
6042: =item tmpget
6043:
6044: Send along temporarily stored information.
6045:
6046: =item ls
6047:
6048: List part of a user's directory.
6049:
1.135 foxr 6050: =item pushtable
6051:
6052: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
6053: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
6054: must be restored manually in case of a problem with the new table file.
6055: pushtable requires that the request be encrypted and validated via
6056: ValidateManager. The form of the command is:
6057: enc:pushtable tablename <tablecontents> \n
6058: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
6059: cleartext newline.
6060:
1.74 harris41 6061: =item Hanging up (exit or init)
6062:
6063: What to do when a client tells the server that they (the client)
6064: are leaving the network.
6065:
6066: =item unknown command
6067:
6068: If B<lond> is sent an unknown command (not in the list above),
6069: it replys to the client "unknown_cmd".
1.135 foxr 6070:
1.74 harris41 6071:
6072: =item UNKNOWN CLIENT
6073:
6074: If the anti-spoofing algorithm cannot verify the client,
6075: the client is rejected (with a "refused" message sent
6076: to the client, and the connection is closed.
6077:
6078: =back
1.61 harris41 6079:
6080: =head1 PREREQUISITES
6081:
6082: IO::Socket
6083: IO::File
6084: Apache::File
6085: Symbol
6086: POSIX
6087: Crypt::IDEA
6088: LWP::UserAgent()
6089: GDBM_File
6090: Authen::Krb4
1.91 albertel 6091: Authen::Krb5
1.61 harris41 6092:
6093: =head1 COREQUISITES
6094:
6095: =head1 OSNAMES
6096:
6097: linux
6098:
6099: =head1 SCRIPT CATEGORIES
6100:
6101: Server/Process
6102:
6103: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>