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