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