Annotation of loncom/lond, revision 1.229
1.1 albertel 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60 www 4: #
1.229 ! foxr 5: # $Id: lond,v 1.228 2004/08/10 22:55:31 foxr Exp $
1.60 www 6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
1.167 foxr 13: # the Free Software Foundation; either version 2 of the License, or
1.60 www 14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
1.178 foxr 23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1.60 www 24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
1.161 foxr 27:
28:
1.60 www 29: # http://www.lon-capa.org/
30: #
1.54 harris41 31:
1.134 albertel 32: use strict;
1.80 harris41 33: use lib '/home/httpd/lib/perl/';
34: use LONCAPA::Configuration;
35:
1.1 albertel 36: use IO::Socket;
37: use IO::File;
1.126 albertel 38: #use Apache::File;
1.1 albertel 39: use Symbol;
40: use POSIX;
41: use Crypt::IDEA;
42: use LWP::UserAgent();
1.3 www 43: use GDBM_File;
44: use Authen::Krb4;
1.91 albertel 45: use Authen::Krb5;
1.49 albertel 46: use lib '/home/httpd/lib/perl/';
47: use localauth;
1.193 raeburn 48: use localenroll;
1.143 foxr 49: use File::Copy;
1.169 foxr 50: use LONCAPA::ConfigFileEdit;
1.200 matthew 51: use LONCAPA::lonlocal;
52: use LONCAPA::lonssl;
1.221 albertel 53: use Fcntl qw(:flock);
1.1 albertel 54:
1.225 foxr 55: my $DEBUG = 0; # Non zero to enable debug log entries.
1.77 foxr 56:
1.57 www 57: my $status='';
58: my $lastlog='';
59:
1.229 ! foxr 60: my $VERSION='$Revision: 1.228 $'; #' 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:
1287: # Process a reinit request. Reinit requests that either
1288: # lonc or lond be reinitialized so that an updated
1289: # host.tab or domain.tab can be processed.
1290: #
1291: # Parameters:
1292: # $cmd - the actual keyword that invoked us.
1293: # $tail - the tail of the request that invoked us.
1294: # $client - File descriptor connected to the client
1295: # Returns:
1296: # 1 - Ok to continue processing.
1297: # 0 - Program should exit
1298: # Implicit output:
1299: # a reply is sent to the client.
1300: #
1301: sub reinit_process_handler {
1302: my ($cmd, $tail, $client) = @_;
1303:
1304: my $userinput = "$cmd:$tail";
1305:
1306: my $cert = &GetCertificate($userinput);
1307: if(&ValidManager($cert)) {
1308: chomp($userinput);
1309: my $reply = &ReinitProcess($userinput);
1310: &Reply( $client, "$reply\n", $userinput);
1311: } else {
1312: &Failure( $client, "refused\n", $userinput);
1313: }
1314: return 1;
1315: }
1316:
1317: ®ister_handler("reinit", \&reinit_process_handler, 1, 0, 1);
1318:
1319: # Process the editing script for a table edit operation.
1320: # the editing operation must be encrypted and requested by
1321: # a manager host.
1322: #
1323: # Parameters:
1324: # $cmd - the actual keyword that invoked us.
1325: # $tail - the tail of the request that invoked us.
1326: # $client - File descriptor connected to the client
1327: # Returns:
1328: # 1 - Ok to continue processing.
1329: # 0 - Program should exit
1330: # Implicit output:
1331: # a reply is sent to the client.
1332: #
1333: sub edit_table_handler {
1334: my ($command, $tail, $client) = @_;
1335:
1336: my $userinput = "$command:$tail";
1337:
1338: my $cert = &GetCertificate($userinput);
1339: if(&ValidManager($cert)) {
1340: my($filetype, $script) = split(/:/, $tail);
1341: if (($filetype eq "hosts") ||
1342: ($filetype eq "domain")) {
1343: if($script ne "") {
1344: &Reply($client, # BUGBUG - EditFile
1345: &EditFile($userinput), # could fail.
1346: $userinput);
1347: } else {
1348: &Failure($client,"refused\n",$userinput);
1349: }
1350: } else {
1351: &Failure($client,"refused\n",$userinput);
1352: }
1353: } else {
1354: &Failure($client,"refused\n",$userinput);
1355: }
1356: return 1;
1357: }
1358: register_handler("edit", \&edit_table_handler, 1, 0, 1);
1359:
1360:
1.220 foxr 1361: #
1362: # Authenticate a user against the LonCAPA authentication
1363: # database. Note that there are several authentication
1364: # possibilities:
1365: # - unix - The user can be authenticated against the unix
1366: # password file.
1367: # - internal - The user can be authenticated against a purely
1368: # internal per user password file.
1369: # - kerberos - The user can be authenticated against either a kerb4 or kerb5
1370: # ticket granting authority.
1371: # - user - The person tailoring LonCAPA can supply a user authentication
1372: # mechanism that is per system.
1373: #
1374: # Parameters:
1375: # $cmd - The command that got us here.
1376: # $tail - Tail of the command (remaining parameters).
1377: # $client - File descriptor connected to client.
1378: # Returns
1379: # 0 - Requested to exit, caller should shut down.
1380: # 1 - Continue processing.
1381: # Implicit inputs:
1382: # The authentication systems describe above have their own forms of implicit
1383: # input into the authentication process that are described above.
1384: #
1385: sub authenticate_handler {
1386: my ($cmd, $tail, $client) = @_;
1387:
1388:
1389: # Regenerate the full input line
1390:
1391: my $userinput = $cmd.":".$tail;
1392:
1393: # udom - User's domain.
1394: # uname - Username.
1395: # upass - User's password.
1396:
1397: my ($udom,$uname,$upass)=split(/:/,$tail);
1398: &Debug(" Authenticate domain = $udom, user = $uname, password = $upass");
1399: chomp($upass);
1400: $upass=&unescape($upass);
1401:
1402: my $pwdcorrect = &validate_user($udom, $uname, $upass);
1403: if($pwdcorrect) {
1404: &Reply( $client, "authorized\n", $userinput);
1405: #
1406: # Bad credentials: Failed to authorize
1407: #
1408: } else {
1409: &Failure( $client, "non_authorized\n", $userinput);
1410: }
1411:
1412: return 1;
1413: }
1.218 foxr 1414:
1.220 foxr 1415: register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214 foxr 1416:
1.222 foxr 1417: #
1418: # Change a user's password. Note that this function is complicated by
1419: # the fact that a user may be authenticated in more than one way:
1420: # At present, we are not able to change the password for all types of
1421: # authentication methods. Only for:
1422: # unix - unix password or shadow passoword style authentication.
1423: # local - Locally written authentication mechanism.
1424: # For now, kerb4 and kerb5 password changes are not supported and result
1425: # in an error.
1426: # FUTURE WORK:
1427: # Support kerberos passwd changes?
1428: # Parameters:
1429: # $cmd - The command that got us here.
1430: # $tail - Tail of the command (remaining parameters).
1431: # $client - File descriptor connected to client.
1432: # Returns
1433: # 0 - Requested to exit, caller should shut down.
1434: # 1 - Continue processing.
1435: # Implicit inputs:
1436: # The authentication systems describe above have their own forms of implicit
1437: # input into the authentication process that are described above.
1438: sub change_password_handler {
1439: my ($cmd, $tail, $client) = @_;
1440:
1441: my $userinput = $cmd.":".$tail; # Reconstruct client's string.
1442:
1443: #
1444: # udom - user's domain.
1445: # uname - Username.
1446: # upass - Current password.
1447: # npass - New password.
1448:
1449: my ($udom,$uname,$upass,$npass)=split(/:/,$tail);
1450:
1451: $upass=&unescape($upass);
1452: $npass=&unescape($npass);
1453: &Debug("Trying to change password for $uname");
1454:
1455: # First require that the user can be authenticated with their
1456: # old password:
1457:
1458: my $validated = &validate_user($udom, $uname, $upass);
1459: if($validated) {
1460: my $realpasswd = &get_auth_type($udom, $uname); # Defined since authd.
1461:
1462: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1463: if ($howpwd eq 'internal') {
1464: &Debug("internal auth");
1465: my $salt=time;
1466: $salt=substr($salt,6,2);
1467: my $ncpass=crypt($npass,$salt);
1468: if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1469: &logthis("Result of password change for "
1470: ."$uname: pwchange_success");
1471: &Reply($client, "ok\n", $userinput);
1472: } else {
1473: &logthis("Unable to open $uname passwd "
1474: ."to change password");
1475: &Failure( $client, "non_authorized\n",$userinput);
1476: }
1477: } elsif ($howpwd eq 'unix') {
1478: # Unix means we have to access /etc/password
1479: &Debug("auth is unix");
1480: my $execdir=$perlvar{'lonDaemons'};
1481: &Debug("Opening lcpasswd pipeline");
1482: my $pf = IO::File->new("|$execdir/lcpasswd > "
1483: ."$perlvar{'lonDaemons'}"
1484: ."/logs/lcpasswd.log");
1485: print $pf "$uname\n$npass\n$npass\n";
1486: close $pf;
1487: my $err = $?;
1488: my $result = ($err>0 ? 'pwchange_failure' : 'ok');
1489: &logthis("Result of password change for $uname: ".
1490: &lcpasswdstrerror($?));
1491: &Reply($client, "$result\n", $userinput);
1492: } else {
1493: # this just means that the current password mode is not
1494: # one we know how to change (e.g the kerberos auth modes or
1495: # locally written auth handler).
1496: #
1497: &Failure( $client, "auth_mode_error\n", $userinput);
1498: }
1499:
1.224 foxr 1500: } else {
1.222 foxr 1501: &Failure( $client, "non_authorized\n", $userinput);
1502: }
1503:
1504: return 1;
1505: }
1506: register_handler("passwd", \&change_password_handler, 1, 1, 0);
1507:
1508:
1.225 foxr 1509: #
1510: # Create a new user. User in this case means a lon-capa user.
1511: # The user must either already exist in some authentication realm
1512: # like kerberos or the /etc/passwd. If not, a user completely local to
1513: # this loncapa system is created.
1514: #
1515: # Parameters:
1516: # $cmd - The command that got us here.
1517: # $tail - Tail of the command (remaining parameters).
1518: # $client - File descriptor connected to client.
1519: # Returns
1520: # 0 - Requested to exit, caller should shut down.
1521: # 1 - Continue processing.
1522: # Implicit inputs:
1523: # The authentication systems describe above have their own forms of implicit
1524: # input into the authentication process that are described above.
1525: sub add_user_handler {
1526:
1527: my ($cmd, $tail, $client) = @_;
1528:
1529:
1530: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
1531: my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
1532:
1533: &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
1534:
1535:
1536: if($udom eq $currentdomainid) { # Reject new users for other domains...
1537:
1538: my $oldumask=umask(0077);
1539: chomp($npass);
1540: $npass=&unescape($npass);
1541: my $passfilename = &password_path($udom, $uname);
1542: &Debug("Password file created will be:".$passfilename);
1543: if (-e $passfilename) {
1544: &Failure( $client, "already_exists\n", $userinput);
1545: } else {
1546: my @fpparts=split(/\//,$passfilename);
1547: my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
1548: my $fperror='';
1549: for (my $i=3;$i<= ($#fpparts-1);$i++) {
1550: $fpnow.='/'.$fpparts[$i];
1551: unless (-e $fpnow) {
1552: &logthis("mkdir $fpnow");
1553: unless (mkdir($fpnow,0777)) {
1554: $fperror="error: ".($!+0)." mkdir failed while attempting "
1555: ."makeuser";
1556: }
1557: }
1558: }
1559: unless ($fperror) {
1560: my $result=&make_passwd_file($uname, $umode,$npass, $passfilename);
1561: &Reply($client, $result, $userinput); #BUGBUG - could be fail
1562: } else {
1563: &Failure($client, "$fperror\n", $userinput);
1564: }
1565: }
1566: umask($oldumask);
1567: } else {
1568: &Failure($client, "not_right_domain\n",
1569: $userinput); # Even if we are multihomed.
1570:
1571: }
1572: return 1;
1573:
1574: }
1575: ®ister_handler("makeuser", \&add_user_handler, 1, 1, 0);
1576:
1577: #
1578: # Change the authentication method of a user. Note that this may
1579: # also implicitly change the user's password if, for example, the user is
1580: # joining an existing authentication realm. Known authentication realms at
1581: # this time are:
1582: # internal - Purely internal password file (only loncapa knows this user)
1583: # local - Institutionally written authentication module.
1584: # unix - Unix user (/etc/passwd with or without /etc/shadow).
1585: # kerb4 - kerberos version 4
1586: # kerb5 - kerberos version 5
1587: #
1588: # Parameters:
1589: # $cmd - The command that got us here.
1590: # $tail - Tail of the command (remaining parameters).
1591: # $client - File descriptor connected to client.
1592: # Returns
1593: # 0 - Requested to exit, caller should shut down.
1594: # 1 - Continue processing.
1595: # Implicit inputs:
1596: # The authentication systems describe above have their own forms of implicit
1597: # input into the authentication process that are described above.
1598: #
1599: sub change_authentication_handler {
1600:
1601: my ($cmd, $tail, $client) = @_;
1602:
1603: my $userinput = "$cmd:$tail"; # Reconstruct user input.
1604:
1605: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
1606: &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
1607: if ($udom ne $currentdomainid) {
1608: &Failure( $client, "not_right_domain\n", $client);
1609: } else {
1610:
1611: chomp($npass);
1612:
1613: $npass=&unescape($npass);
1614: my $passfilename = &password_path($udom, $uname);
1615: if ($passfilename) { # Not allowed to create a new user!!
1616: my $result=&make_passwd_file($uname, $umode,$npass,$passfilename);
1617: &Reply($client, $result, $userinput);
1618: } else {
1619: &Failure($client, "non_authorized", $userinput); # Fail the user now.
1620: }
1621: }
1622: return 1;
1623: }
1624: ®ister_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
1625:
1626: #
1627: # Determines if this is the home server for a user. The home server
1628: # for a user will have his/her lon-capa passwd file. Therefore all we need
1629: # to do is determine if this file exists.
1630: #
1631: # Parameters:
1632: # $cmd - The command that got us here.
1633: # $tail - Tail of the command (remaining parameters).
1634: # $client - File descriptor connected to client.
1635: # Returns
1636: # 0 - Requested to exit, caller should shut down.
1637: # 1 - Continue processing.
1638: # Implicit inputs:
1639: # The authentication systems describe above have their own forms of implicit
1640: # input into the authentication process that are described above.
1641: #
1642: sub is_home_handler {
1643: my ($cmd, $tail, $client) = @_;
1644:
1645: my $userinput = "$cmd:$tail";
1646:
1647: my ($udom,$uname)=split(/:/,$tail);
1648: chomp($uname);
1649: my $passfile = &password_filename($udom, $uname);
1650: if($passfile) {
1651: &Reply( $client, "found\n", $userinput);
1652: } else {
1653: &Failure($client, "not_found\n", $userinput);
1654: }
1655: return 1;
1656: }
1657: ®ister_handler("home", \&is_home_handler, 0,1,0);
1658:
1659: #
1660: # Process an update request for a resource?? I think what's going on here is
1661: # that a resource has been modified that we hold a subscription to.
1662: # If the resource is not local, then we must update, or at least invalidate our
1663: # cached copy of the resource.
1664: # FUTURE WORK:
1665: # I need to look at this logic carefully. My druthers would be to follow
1666: # typical caching logic, and simple invalidate the cache, drop any subscription
1667: # an let the next fetch start the ball rolling again... however that may
1668: # actually be more difficult than it looks given the complex web of
1669: # proxy servers.
1670: # Parameters:
1671: # $cmd - The command that got us here.
1672: # $tail - Tail of the command (remaining parameters).
1673: # $client - File descriptor connected to client.
1674: # Returns
1675: # 0 - Requested to exit, caller should shut down.
1676: # 1 - Continue processing.
1677: # Implicit inputs:
1678: # The authentication systems describe above have their own forms of implicit
1679: # input into the authentication process that are described above.
1680: #
1681: sub update_resource_handler {
1682:
1683: my ($cmd, $tail, $client) = @_;
1684:
1685: my $userinput = "$cmd:$tail";
1686:
1687: my $fname= $tail; # This allows interactive testing
1688:
1689:
1690: my $ownership=ishome($fname);
1691: if ($ownership eq 'not_owner') {
1692: if (-e $fname) {
1693: my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
1694: $atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
1695: my $now=time;
1696: my $since=$now-$atime;
1697: if ($since>$perlvar{'lonExpire'}) {
1698: my $reply=&reply("unsub:$fname","$clientname");
1699: unlink("$fname");
1700: } else {
1701: my $transname="$fname.in.transfer";
1702: my $remoteurl=&reply("sub:$fname","$clientname");
1703: my $response;
1704: alarm(120);
1705: {
1706: my $ua=new LWP::UserAgent;
1707: my $request=new HTTP::Request('GET',"$remoteurl");
1708: $response=$ua->request($request,$transname);
1709: }
1710: alarm(0);
1711: if ($response->is_error()) {
1712: unlink($transname);
1713: my $message=$response->status_line;
1714: &logthis("LWP GET: $message for $fname ($remoteurl)");
1715: } else {
1716: if ($remoteurl!~/\.meta$/) {
1717: alarm(120);
1718: {
1719: my $ua=new LWP::UserAgent;
1720: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1721: my $mresponse=$ua->request($mrequest,$fname.'.meta');
1722: if ($mresponse->is_error()) {
1723: unlink($fname.'.meta');
1724: }
1725: }
1726: alarm(0);
1727: }
1728: rename($transname,$fname);
1729: }
1730: }
1731: &Reply( $client, "ok\n", $userinput);
1732: } else {
1733: &Failure($client, "not_found\n", $userinput);
1734: }
1735: } else {
1736: &Failure($client, "rejected\n", $userinput);
1737: }
1738: return 1;
1739: }
1740: ®ister_handler("update", \&update_resource_handler, 0 ,1, 0);
1741:
1742: #
1.226 foxr 1743: # Fetch a user file from a remote server to the user's home directory
1744: # userfiles subdir.
1.225 foxr 1745: # Parameters:
1746: # $cmd - The command that got us here.
1747: # $tail - Tail of the command (remaining parameters).
1748: # $client - File descriptor connected to client.
1749: # Returns
1750: # 0 - Requested to exit, caller should shut down.
1751: # 1 - Continue processing.
1752: #
1753: sub fetch_user_file_handler {
1754:
1755: my ($cmd, $tail, $client) = @_;
1756:
1757: my $userinput = "$cmd:$tail";
1758: my $fname = $tail;
1759: my ($udom,$uname,$ufile)=split(/\//,$fname);
1760: my $udir=&propath($udom,$uname).'/userfiles';
1761: unless (-e $udir) {
1762: mkdir($udir,0770);
1763: }
1764: if (-e $udir) {
1765: $ufile=~s/^[\.\~]+//;
1766: $ufile=~s/\///g;
1767: my $destname=$udir.'/'.$ufile;
1768: my $transname=$udir.'/'.$ufile.'.in.transit';
1769: my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
1770: my $response;
1771: alarm(120);
1772: {
1773: my $ua=new LWP::UserAgent;
1774: my $request=new HTTP::Request('GET',"$remoteurl");
1775: $response=$ua->request($request,$transname);
1776: }
1777: alarm(0);
1778: if ($response->is_error()) {
1779: unlink($transname);
1780: my $message=$response->status_line;
1781: &logthis("LWP GET: $message for $fname ($remoteurl)");
1782: &Failure($client, "failed\n", $userinput);
1783: } else {
1784: if (!rename($transname,$destname)) {
1785: &logthis("Unable to move $transname to $destname");
1786: unlink($transname);
1787: &Failure($client, "failed\n", $userinput);
1788: } else {
1789: &Reply($client, "ok\n", $userinput);
1790: }
1791: }
1792: } else {
1793: &Failure($client, "not_home\n", $userinput);
1794: }
1795: return 1;
1796: }
1797: ®ister_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
1798:
1.226 foxr 1799: #
1800: # Remove a file from a user's home directory userfiles subdirectory.
1801: # Parameters:
1802: # cmd - the Lond request keyword that got us here.
1803: # tail - the part of the command past the keyword.
1804: # client- File descriptor connected with the client.
1805: #
1806: # Returns:
1807: # 1 - Continue processing.
1808:
1809: sub remove_user_file_handler {
1810: my ($cmd, $tail, $client) = @_;
1811:
1812: my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
1813:
1814: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1815: if ($ufile =~m|/\.\./|) {
1816: # any files paths with /../ in them refuse
1817: # to deal with
1818: &Failure($client, "refused\n", "$cmd:$tail");
1819: } else {
1820: my $udir = &propath($udom,$uname);
1821: if (-e $udir) {
1822: my $file=$udir.'/userfiles/'.$ufile;
1823: if (-e $file) {
1824: unlink($file);
1825: if (-e $file) {
1826: &Failure($client, "failed\n", "$cmd:$tail");
1827: } else {
1828: &Reply($client, "ok\n", "$cmd:$tail");
1829: }
1830: } else {
1831: &Failure($client, "not_found\n", "$cmd:$tail");
1832: }
1833: } else {
1834: &Failure($client, "not_home\n", "$cmd:$tail");
1835: }
1836: }
1837: return 1;
1838: }
1839: ®ister_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
1840:
1.227 foxr 1841:
1842: #
1843: # Authenticate access to a user file by checking the user's
1844: # session token(?)
1845: #
1846: # Parameters:
1847: # cmd - The request keyword that dispatched to tus.
1848: # tail - The tail of the request (colon separated parameters).
1849: # client - Filehandle open on the client.
1850: # Return:
1851: # 1.
1852:
1853: sub token_auth_user_file_handler {
1854: my ($cmd, $tail, $client) = @_;
1855:
1856: my ($fname, $session) = split(/:/, $tail);
1857:
1858: chomp($session);
1859: my $reply='non_auth';
1860: if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
1861: $session.'.id')) {
1862: while (my $line=<ENVIN>) {
1863: if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply='ok'; }
1864: }
1865: close(ENVIN);
1866: &Reply($client, $reply);
1867: } else {
1868: &Failure($client, "invalid_token\n", "$cmd:$tail");
1869: }
1870: return 1;
1871:
1872: }
1873:
1874: ®ister_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229 ! foxr 1875:
! 1876:
! 1877: #
! 1878: # Unsubscribe from a resource.
! 1879: #
! 1880: # Parameters:
! 1881: # $cmd - The command that got us here.
! 1882: # $tail - Tail of the command (remaining parameters).
! 1883: # $client - File descriptor connected to client.
! 1884: # Returns
! 1885: # 0 - Requested to exit, caller should shut down.
! 1886: # 1 - Continue processing.
! 1887: #
! 1888: sub unsubscribe_handler {
! 1889: my ($cmd, $tail, $client) = @_;
! 1890:
! 1891: my $userinput= "$cmd:$tail";
! 1892:
! 1893: my ($fname) = split(/:/,$tail); # Split in case there's extrs.
! 1894:
! 1895: &Debug("Unsubscribing $fname");
! 1896: if (-e $fname) {
! 1897: &Debug("Exists");
! 1898: &Reply($client, &unsub($fname,$clientip), $userinput);
! 1899: } else {
! 1900: &Failure($client, "not_found\n", $userinput);
! 1901: }
! 1902: return 1;
! 1903: }
! 1904: ®ister_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
! 1905:
1.207 foxr 1906: #---------------------------------------------------------------
1907: #
1908: # Getting, decoding and dispatching requests:
1909: #
1910:
1911: #
1912: # Get a Request:
1913: # Gets a Request message from the client. The transaction
1914: # is defined as a 'line' of text. We remove the new line
1915: # from the text line.
1.226 foxr 1916: #
1.211 albertel 1917: sub get_request {
1.207 foxr 1918: my $input = <$client>;
1919: chomp($input);
1.226 foxr 1920:
1.212 foxr 1921: Debug("get_request: Request = $input\n");
1.207 foxr 1922:
1923: &status('Processing '.$clientname.':'.$input);
1924:
1925: return $input;
1926: }
1.212 foxr 1927: #---------------------------------------------------------------
1928: #
1929: # Process a request. This sub should shrink as each action
1930: # gets farmed out into a separat sub that is registered
1931: # with the dispatch hash.
1932: #
1933: # Parameters:
1934: # user_input - The request received from the client (lonc).
1935: # Returns:
1936: # true to keep processing, false if caller should exit.
1937: #
1938: sub process_request {
1939: my ($userinput) = @_; # Easier for now to break style than to
1940: # fix all the userinput -> user_input.
1941: my $wasenc = 0; # True if request was encrypted.
1942: # ------------------------------------------------------------ See if encrypted
1943: if ($userinput =~ /^enc/) {
1944: $userinput = decipher($userinput);
1945: $wasenc=1;
1946: if(!$userinput) { # Cipher not defined.
1947: &Failure($client, "error: Encrypted data without negotated key");
1948: return 0;
1949: }
1950: }
1951: Debug("process_request: $userinput\n");
1952:
1.213 foxr 1953: #
1954: # The 'correct way' to add a command to lond is now to
1955: # write a sub to execute it and Add it to the command dispatch
1956: # hash via a call to register_handler.. The comments to that
1957: # sub should give you enough to go on to show how to do this
1958: # along with the examples that are building up as this code
1959: # is getting refactored. Until all branches of the
1960: # if/elseif monster below have been factored out into
1961: # separate procesor subs, if the dispatch hash is missing
1962: # the command keyword, we will fall through to the remainder
1963: # of the if/else chain below in order to keep this thing in
1964: # working order throughout the transmogrification.
1965:
1966: my ($command, $tail) = split(/:/, $userinput, 2);
1967: chomp($command);
1968: chomp($tail);
1969: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
1.214 foxr 1970: $command =~ s/(\r)//; # And this too for parameterless commands.
1971: if(!$tail) {
1972: $tail =""; # defined but blank.
1973: }
1.213 foxr 1974:
1975: &Debug("Command received: $command, encoded = $wasenc");
1976:
1977: if(defined $Dispatcher{$command}) {
1978:
1979: my $dispatch_info = $Dispatcher{$command};
1980: my $handler = $$dispatch_info[0];
1981: my $need_encode = $$dispatch_info[1];
1982: my $client_types = $$dispatch_info[2];
1983: Debug("Matched dispatch hash: mustencode: $need_encode "
1984: ."ClientType $client_types");
1985:
1986: # Validate the request:
1987:
1988: my $ok = 1;
1989: my $requesterprivs = 0;
1990: if(&isClient()) {
1991: $requesterprivs |= $CLIENT_OK;
1992: }
1993: if(&isManager()) {
1994: $requesterprivs |= $MANAGER_OK;
1995: }
1996: if($need_encode && (!$wasenc)) {
1997: Debug("Must encode but wasn't: $need_encode $wasenc");
1998: $ok = 0;
1999: }
2000: if(($client_types & $requesterprivs) == 0) {
2001: Debug("Client not privileged to do this operation");
2002: $ok = 0;
2003: }
2004:
2005: if($ok) {
2006: Debug("Dispatching to handler $command $tail");
2007: my $keep_going = &$handler($command, $tail, $client);
2008: return $keep_going;
2009: } else {
2010: Debug("Refusing to dispatch because client did not match requirements");
2011: Failure($client, "refused\n", $userinput);
2012: return 1;
2013: }
2014:
2015: }
2016:
1.215 foxr 2017: #------------------- Commands not yet in spearate handlers. --------------
2018:
1.218 foxr 2019:
1.226 foxr 2020:
1.229 ! foxr 2021:
1.212 foxr 2022: # ------------------------------------------------------------------- subscribe
1.229 ! foxr 2023: if ($userinput =~ /^sub/) {
1.212 foxr 2024: if(isClient) {
2025: print $client &subscribe($userinput,$clientip);
2026: } else {
2027: Reply($client, "refused\n", $userinput);
2028:
2029: }
2030: # ------------------------------------------------------------- current version
2031: } elsif ($userinput =~ /^currentversion/) {
2032: if(isClient) {
2033: my ($cmd,$fname)=split(/:/,$userinput);
2034: print $client ¤tversion($fname)."\n";
2035: } else {
2036: Reply($client, "refused\n", $userinput);
2037:
2038: }
2039: # ------------------------------------------------------------------------- log
2040: } elsif ($userinput =~ /^log/) {
2041: if(isClient) {
2042: my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
2043: chomp($what);
2044: my $proname=propath($udom,$uname);
2045: my $now=time;
2046: {
2047: my $hfh;
2048: if ($hfh=IO::File->new(">>$proname/activity.log")) {
2049: print $hfh "$now:$clientname:$what\n";
2050: print $client "ok\n";
2051: } else {
2052: print $client "error: ".($!+0)
2053: ." IO::File->new Failed "
2054: ."while attempting log\n";
2055: }
2056: }
2057: } else {
2058: Reply($client, "refused\n", $userinput);
2059:
2060: }
2061: # ------------------------------------------------------------------------- put
2062: } elsif ($userinput =~ /^put/) {
2063: if(isClient) {
2064: my ($cmd,$udom,$uname,$namespace,$what)
2065: =split(/:/,$userinput,5);
2066: $namespace=~s/\//\_/g;
2067: $namespace=~s/\W//g;
2068: if ($namespace ne 'roles') {
2069: chomp($what);
2070: my $proname=propath($udom,$uname);
2071: my $now=time;
2072: my @pairs=split(/\&/,$what);
2073: my %hash;
2074: if (tie(%hash,'GDBM_File',
2075: "$proname/$namespace.db",
2076: &GDBM_WRCREAT(),0640)) {
2077: unless ($namespace=~/^nohist\_/) {
2078: my $hfh;
2079: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
2080: }
2081:
2082: foreach my $pair (@pairs) {
2083: my ($key,$value)=split(/=/,$pair);
2084: $hash{$key}=$value;
2085: }
2086: if (untie(%hash)) {
2087: print $client "ok\n";
2088: } else {
2089: print $client "error: ".($!+0)
2090: ." untie(GDBM) failed ".
2091: "while attempting put\n";
2092: }
2093: } else {
2094: print $client "error: ".($!)
2095: ." tie(GDBM) Failed ".
2096: "while attempting put\n";
2097: }
2098: } else {
2099: print $client "refused\n";
2100: }
2101: } else {
2102: Reply($client, "refused\n", $userinput);
2103:
2104: }
2105: # ------------------------------------------------------------------- inc
2106: } elsif ($userinput =~ /^inc:/) {
2107: if(isClient) {
2108: my ($cmd,$udom,$uname,$namespace,$what)
2109: =split(/:/,$userinput);
2110: $namespace=~s/\//\_/g;
2111: $namespace=~s/\W//g;
2112: if ($namespace ne 'roles') {
2113: chomp($what);
2114: my $proname=propath($udom,$uname);
2115: my $now=time;
2116: my @pairs=split(/\&/,$what);
2117: my %hash;
2118: if (tie(%hash,'GDBM_File',
2119: "$proname/$namespace.db",
2120: &GDBM_WRCREAT(),0640)) {
2121: unless ($namespace=~/^nohist\_/) {
2122: my $hfh;
2123: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
2124: }
2125: foreach my $pair (@pairs) {
2126: my ($key,$value)=split(/=/,$pair);
2127: # We could check that we have a number...
2128: if (! defined($value) || $value eq '') {
2129: $value = 1;
2130: }
2131: $hash{$key}+=$value;
2132: }
2133: if (untie(%hash)) {
2134: print $client "ok\n";
2135: } else {
2136: print $client "error: ".($!+0)
2137: ." untie(GDBM) failed ".
2138: "while attempting inc\n";
2139: }
2140: } else {
2141: print $client "error: ".($!)
2142: ." tie(GDBM) Failed ".
2143: "while attempting inc\n";
2144: }
2145: } else {
2146: print $client "refused\n";
2147: }
2148: } else {
2149: Reply($client, "refused\n", $userinput);
2150:
2151: }
2152: # -------------------------------------------------------------------- rolesput
2153: } elsif ($userinput =~ /^rolesput/) {
2154: if(isClient) {
2155: &Debug("rolesput");
2156: if ($wasenc==1) {
2157: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
2158: =split(/:/,$userinput);
2159: &Debug("cmd = ".$cmd." exedom= ".$exedom.
2160: "user = ".$exeuser." udom=".$udom.
2161: "what = ".$what);
2162: my $namespace='roles';
2163: chomp($what);
2164: my $proname=propath($udom,$uname);
2165: my $now=time;
2166: my @pairs=split(/\&/,$what);
2167: my %hash;
2168: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2169: {
2170: my $hfh;
2171: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
2172: print $hfh "P:$now:$exedom:$exeuser:$what\n";
2173: }
2174: }
2175:
2176: foreach my $pair (@pairs) {
2177: my ($key,$value)=split(/=/,$pair);
2178: &ManagePermissions($key, $udom, $uname,
1.222 foxr 2179: &get_auth_type( $udom,
1.212 foxr 2180: $uname));
2181: $hash{$key}=$value;
2182: }
2183: if (untie(%hash)) {
2184: print $client "ok\n";
2185: } else {
2186: print $client "error: ".($!+0)
2187: ." untie(GDBM) Failed ".
2188: "while attempting rolesput\n";
2189: }
2190: } else {
2191: print $client "error: ".($!+0)
2192: ." tie(GDBM) Failed ".
2193: "while attempting rolesput\n";
2194: }
2195: } else {
2196: print $client "refused\n";
2197: }
2198: } else {
2199: Reply($client, "refused\n", $userinput);
2200:
2201: }
2202: # -------------------------------------------------------------------- rolesdel
2203: } elsif ($userinput =~ /^rolesdel/) {
2204: if(isClient) {
2205: &Debug("rolesdel");
2206: if ($wasenc==1) {
2207: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
2208: =split(/:/,$userinput);
2209: &Debug("cmd = ".$cmd." exedom= ".$exedom.
2210: "user = ".$exeuser." udom=".$udom.
2211: "what = ".$what);
2212: my $namespace='roles';
2213: chomp($what);
2214: my $proname=propath($udom,$uname);
2215: my $now=time;
2216: my @rolekeys=split(/\&/,$what);
2217: my %hash;
2218: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2219: {
2220: my $hfh;
2221: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
2222: print $hfh "D:$now:$exedom:$exeuser:$what\n";
2223: }
2224: }
2225: foreach my $key (@rolekeys) {
2226: delete $hash{$key};
2227: }
2228: if (untie(%hash)) {
2229: print $client "ok\n";
2230: } else {
2231: print $client "error: ".($!+0)
2232: ." untie(GDBM) Failed ".
2233: "while attempting rolesdel\n";
2234: }
2235: } else {
2236: print $client "error: ".($!+0)
2237: ." tie(GDBM) Failed ".
2238: "while attempting rolesdel\n";
2239: }
2240: } else {
2241: print $client "refused\n";
2242: }
2243: } else {
2244: Reply($client, "refused\n", $userinput);
2245:
2246: }
2247: # ------------------------------------------------------------------------- get
2248: } elsif ($userinput =~ /^get/) {
2249: if(isClient) {
2250: my ($cmd,$udom,$uname,$namespace,$what)
2251: =split(/:/,$userinput);
2252: $namespace=~s/\//\_/g;
2253: $namespace=~s/\W//g;
2254: chomp($what);
2255: my @queries=split(/\&/,$what);
2256: my $proname=propath($udom,$uname);
2257: my $qresult='';
2258: my %hash;
2259: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2260: for (my $i=0;$i<=$#queries;$i++) {
2261: $qresult.="$hash{$queries[$i]}&";
2262: }
2263: if (untie(%hash)) {
2264: $qresult=~s/\&$//;
2265: print $client "$qresult\n";
2266: } else {
2267: print $client "error: ".($!+0)
2268: ." untie(GDBM) Failed ".
2269: "while attempting get\n";
2270: }
2271: } else {
2272: if ($!+0 == 2) {
2273: print $client "error:No such file or ".
2274: "GDBM reported bad block error\n";
2275: } else {
2276: print $client "error: ".($!+0)
2277: ." tie(GDBM) Failed ".
2278: "while attempting get\n";
2279: }
2280: }
2281: } else {
2282: Reply($client, "refused\n", $userinput);
2283:
2284: }
2285: # ------------------------------------------------------------------------ eget
2286: } elsif ($userinput =~ /^eget/) {
2287: if (isClient) {
2288: my ($cmd,$udom,$uname,$namespace,$what)
2289: =split(/:/,$userinput);
2290: $namespace=~s/\//\_/g;
2291: $namespace=~s/\W//g;
2292: chomp($what);
2293: my @queries=split(/\&/,$what);
2294: my $proname=propath($udom,$uname);
2295: my $qresult='';
2296: my %hash;
2297: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2298: for (my $i=0;$i<=$#queries;$i++) {
2299: $qresult.="$hash{$queries[$i]}&";
2300: }
2301: if (untie(%hash)) {
2302: $qresult=~s/\&$//;
2303: if ($cipher) {
2304: my $cmdlength=length($qresult);
2305: $qresult.=" ";
2306: my $encqresult='';
2307: for
2308: (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
2309: $encqresult.=
2310: unpack("H16",
2311: $cipher->encrypt(substr($qresult,$encidx,8)));
2312: }
2313: print $client "enc:$cmdlength:$encqresult\n";
2314: } else {
2315: print $client "error:no_key\n";
2316: }
2317: } else {
2318: print $client "error: ".($!+0)
2319: ." untie(GDBM) Failed ".
2320: "while attempting eget\n";
2321: }
2322: } else {
2323: print $client "error: ".($!+0)
2324: ." tie(GDBM) Failed ".
2325: "while attempting eget\n";
2326: }
2327: } else {
2328: Reply($client, "refused\n", $userinput);
2329:
2330: }
2331: # ------------------------------------------------------------------------- del
2332: } elsif ($userinput =~ /^del/) {
2333: if(isClient) {
2334: my ($cmd,$udom,$uname,$namespace,$what)
2335: =split(/:/,$userinput);
2336: $namespace=~s/\//\_/g;
2337: $namespace=~s/\W//g;
2338: chomp($what);
2339: my $proname=propath($udom,$uname);
2340: my $now=time;
2341: my @keys=split(/\&/,$what);
2342: my %hash;
2343: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2344: unless ($namespace=~/^nohist\_/) {
2345: my $hfh;
2346: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "D:$now:$what\n"; }
2347: }
2348: foreach my $key (@keys) {
2349: delete($hash{$key});
2350: }
2351: if (untie(%hash)) {
2352: print $client "ok\n";
2353: } else {
2354: print $client "error: ".($!+0)
2355: ." untie(GDBM) Failed ".
2356: "while attempting del\n";
2357: }
2358: } else {
2359: print $client "error: ".($!+0)
2360: ." tie(GDBM) Failed ".
2361: "while attempting del\n";
2362: }
2363: } else {
2364: Reply($client, "refused\n", $userinput);
2365:
2366: }
2367: # ------------------------------------------------------------------------ keys
2368: } elsif ($userinput =~ /^keys/) {
2369: if(isClient) {
2370: my ($cmd,$udom,$uname,$namespace)
2371: =split(/:/,$userinput);
2372: $namespace=~s/\//\_/g;
2373: $namespace=~s/\W//g;
2374: my $proname=propath($udom,$uname);
2375: my $qresult='';
2376: my %hash;
2377: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2378: foreach my $key (keys %hash) {
2379: $qresult.="$key&";
2380: }
2381: if (untie(%hash)) {
2382: $qresult=~s/\&$//;
2383: print $client "$qresult\n";
2384: } else {
2385: print $client "error: ".($!+0)
2386: ." untie(GDBM) Failed ".
2387: "while attempting keys\n";
2388: }
2389: } else {
2390: print $client "error: ".($!+0)
2391: ." tie(GDBM) Failed ".
2392: "while attempting keys\n";
2393: }
2394: } else {
2395: Reply($client, "refused\n", $userinput);
2396:
2397: }
2398: # ----------------------------------------------------------------- dumpcurrent
2399: } elsif ($userinput =~ /^currentdump/) {
2400: if (isClient) {
2401: my ($cmd,$udom,$uname,$namespace)
2402: =split(/:/,$userinput);
2403: $namespace=~s/\//\_/g;
2404: $namespace=~s/\W//g;
2405: my $qresult='';
2406: my $proname=propath($udom,$uname);
2407: my %hash;
2408: if (tie(%hash,'GDBM_File',
2409: "$proname/$namespace.db",
2410: &GDBM_READER(),0640)) {
2411: # Structure of %data:
2412: # $data{$symb}->{$parameter}=$value;
2413: # $data{$symb}->{'v.'.$parameter}=$version;
2414: # since $parameter will be unescaped, we do not
2415: # have to worry about silly parameter names...
2416: my %data = ();
2417: while (my ($key,$value) = each(%hash)) {
2418: my ($v,$symb,$param) = split(/:/,$key);
2419: next if ($v eq 'version' || $symb eq 'keys');
2420: next if (exists($data{$symb}) &&
2421: exists($data{$symb}->{$param}) &&
2422: $data{$symb}->{'v.'.$param} > $v);
2423: $data{$symb}->{$param}=$value;
2424: $data{$symb}->{'v.'.$param}=$v;
2425: }
2426: if (untie(%hash)) {
2427: while (my ($symb,$param_hash) = each(%data)) {
2428: while(my ($param,$value) = each (%$param_hash)){
2429: next if ($param =~ /^v\./);
2430: $qresult.=$symb.':'.$param.'='.$value.'&';
2431: }
2432: }
2433: chop($qresult);
2434: print $client "$qresult\n";
2435: } else {
2436: print $client "error: ".($!+0)
2437: ." untie(GDBM) Failed ".
2438: "while attempting currentdump\n";
2439: }
2440: } else {
2441: print $client "error: ".($!+0)
2442: ." tie(GDBM) Failed ".
2443: "while attempting currentdump\n";
2444: }
2445: } else {
2446: Reply($client, "refused\n", $userinput);
2447: }
2448: # ------------------------------------------------------------------------ dump
2449: } elsif ($userinput =~ /^dump/) {
2450: if(isClient) {
2451: my ($cmd,$udom,$uname,$namespace,$regexp)
2452: =split(/:/,$userinput);
2453: $namespace=~s/\//\_/g;
2454: $namespace=~s/\W//g;
2455: if (defined($regexp)) {
2456: $regexp=&unescape($regexp);
2457: } else {
2458: $regexp='.';
2459: }
2460: my $qresult='';
2461: my $proname=propath($udom,$uname);
2462: my %hash;
2463: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2464: while (my ($key,$value) = each(%hash)) {
2465: if ($regexp eq '.') {
2466: $qresult.=$key.'='.$value.'&';
2467: } else {
2468: my $unescapeKey = &unescape($key);
2469: if (eval('$unescapeKey=~/$regexp/')) {
2470: $qresult.="$key=$value&";
2471: }
2472: }
2473: }
2474: if (untie(%hash)) {
2475: chop($qresult);
2476: print $client "$qresult\n";
2477: } else {
2478: print $client "error: ".($!+0)
2479: ." untie(GDBM) Failed ".
2480: "while attempting dump\n";
2481: }
2482: } else {
2483: print $client "error: ".($!+0)
2484: ." tie(GDBM) Failed ".
2485: "while attempting dump\n";
2486: }
2487: } else {
2488: Reply($client, "refused\n", $userinput);
2489:
2490: }
2491: # ----------------------------------------------------------------------- store
2492: } elsif ($userinput =~ /^store/) {
2493: if(isClient) {
2494: my ($cmd,$udom,$uname,$namespace,$rid,$what)
2495: =split(/:/,$userinput);
2496: $namespace=~s/\//\_/g;
2497: $namespace=~s/\W//g;
2498: if ($namespace ne 'roles') {
2499: chomp($what);
2500: my $proname=propath($udom,$uname);
2501: my $now=time;
2502: my @pairs=split(/\&/,$what);
2503: my %hash;
2504: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2505: unless ($namespace=~/^nohist\_/) {
2506: my $hfh;
2507: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
2508: print $hfh "P:$now:$rid:$what\n";
2509: }
2510: }
2511: my @previouskeys=split(/&/,$hash{"keys:$rid"});
2512: my $key;
2513: $hash{"version:$rid"}++;
2514: my $version=$hash{"version:$rid"};
2515: my $allkeys='';
2516: foreach my $pair (@pairs) {
2517: my ($key,$value)=split(/=/,$pair);
2518: $allkeys.=$key.':';
2519: $hash{"$version:$rid:$key"}=$value;
2520: }
2521: $hash{"$version:$rid:timestamp"}=$now;
2522: $allkeys.='timestamp';
2523: $hash{"$version:keys:$rid"}=$allkeys;
2524: if (untie(%hash)) {
2525: print $client "ok\n";
2526: } else {
2527: print $client "error: ".($!+0)
2528: ." untie(GDBM) Failed ".
2529: "while attempting store\n";
2530: }
2531: } else {
2532: print $client "error: ".($!+0)
2533: ." tie(GDBM) Failed ".
2534: "while attempting store\n";
2535: }
2536: } else {
2537: print $client "refused\n";
2538: }
2539: } else {
2540: Reply($client, "refused\n", $userinput);
2541:
2542: }
2543: # --------------------------------------------------------------------- restore
2544: } elsif ($userinput =~ /^restore/) {
2545: if(isClient) {
2546: my ($cmd,$udom,$uname,$namespace,$rid)
2547: =split(/:/,$userinput);
2548: $namespace=~s/\//\_/g;
2549: $namespace=~s/\W//g;
2550: chomp($rid);
2551: my $proname=propath($udom,$uname);
2552: my $qresult='';
2553: my %hash;
2554: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2555: my $version=$hash{"version:$rid"};
2556: $qresult.="version=$version&";
2557: my $scope;
2558: for ($scope=1;$scope<=$version;$scope++) {
2559: my $vkeys=$hash{"$scope:keys:$rid"};
2560: my @keys=split(/:/,$vkeys);
2561: my $key;
2562: $qresult.="$scope:keys=$vkeys&";
2563: foreach $key (@keys) {
2564: $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
2565: }
2566: }
2567: if (untie(%hash)) {
2568: $qresult=~s/\&$//;
2569: print $client "$qresult\n";
2570: } else {
2571: print $client "error: ".($!+0)
2572: ." untie(GDBM) Failed ".
2573: "while attempting restore\n";
2574: }
2575: } else {
2576: print $client "error: ".($!+0)
2577: ." tie(GDBM) Failed ".
2578: "while attempting restore\n";
2579: }
2580: } else {
2581: Reply($client, "refused\n", $userinput);
2582:
2583: }
2584: # -------------------------------------------------------------------- chatsend
2585: } elsif ($userinput =~ /^chatsend/) {
2586: if(isClient) {
2587: my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
2588: &chatadd($cdom,$cnum,$newpost);
2589: print $client "ok\n";
2590: } else {
2591: Reply($client, "refused\n", $userinput);
2592:
2593: }
2594: # -------------------------------------------------------------------- chatretr
2595: } elsif ($userinput =~ /^chatretr/) {
2596: if(isClient) {
2597: my
2598: ($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
2599: my $reply='';
2600: foreach (&getchat($cdom,$cnum,$udom,$uname)) {
2601: $reply.=&escape($_).':';
2602: }
2603: $reply=~s/\:$//;
2604: print $client $reply."\n";
2605: } else {
2606: Reply($client, "refused\n", $userinput);
2607:
2608: }
2609: # ------------------------------------------------------------------- querysend
2610: } elsif ($userinput =~ /^querysend/) {
2611: if (isClient) {
2612: my ($cmd,$query,
2613: $arg1,$arg2,$arg3)=split(/\:/,$userinput);
2614: $query=~s/\n*$//g;
2615: print $client "".
2616: sqlreply("$clientname\&$query".
2617: "\&$arg1"."\&$arg2"."\&$arg3")."\n";
2618: } else {
2619: Reply($client, "refused\n", $userinput);
2620:
2621: }
2622: # ------------------------------------------------------------------ queryreply
2623: } elsif ($userinput =~ /^queryreply/) {
2624: if(isClient) {
2625: my ($cmd,$id,$reply)=split(/:/,$userinput);
2626: my $store;
2627: my $execdir=$perlvar{'lonDaemons'};
2628: if ($store=IO::File->new(">$execdir/tmp/$id")) {
2629: $reply=~s/\&/\n/g;
2630: print $store $reply;
2631: close $store;
2632: my $store2=IO::File->new(">$execdir/tmp/$id.end");
2633: print $store2 "done\n";
2634: close $store2;
2635: print $client "ok\n";
1.224 foxr 2636: } else {
1.212 foxr 2637: print $client "error: ".($!+0)
2638: ." IO::File->new Failed ".
2639: "while attempting queryreply\n";
2640: }
2641: } else {
2642: Reply($client, "refused\n", $userinput);
2643:
2644: }
2645: # ----------------------------------------------------------------- courseidput
2646: } elsif ($userinput =~ /^courseidput/) {
2647: if(isClient) {
2648: my ($cmd,$udom,$what)=split(/:/,$userinput);
2649: chomp($what);
2650: $udom=~s/\W//g;
2651: my $proname=
2652: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
2653: my $now=time;
2654: my @pairs=split(/\&/,$what);
2655: my %hash;
2656: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
2657: foreach my $pair (@pairs) {
2658: my ($key,$descr,$inst_code)=split(/=/,$pair);
2659: $hash{$key}=$descr.':'.$inst_code.':'.$now;
2660: }
2661: if (untie(%hash)) {
2662: print $client "ok\n";
2663: } else {
2664: print $client "error: ".($!+0)
2665: ." untie(GDBM) Failed ".
2666: "while attempting courseidput\n";
2667: }
2668: } else {
2669: print $client "error: ".($!+0)
2670: ." tie(GDBM) Failed ".
2671: "while attempting courseidput\n";
2672: }
2673: } else {
2674: Reply($client, "refused\n", $userinput);
2675:
2676: }
2677: # ---------------------------------------------------------------- courseiddump
2678: } elsif ($userinput =~ /^courseiddump/) {
2679: if(isClient) {
2680: my ($cmd,$udom,$since,$description)
2681: =split(/:/,$userinput);
2682: if (defined($description)) {
2683: $description=&unescape($description);
2684: } else {
2685: $description='.';
2686: }
2687: unless (defined($since)) { $since=0; }
2688: my $qresult='';
2689: my $proname=
2690: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
2691: my %hash;
2692: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
2693: while (my ($key,$value) = each(%hash)) {
2694: my ($descr,$lasttime,$inst_code);
2695: if ($value =~ m/^([^\:]*):([^\:]*):(\d+)$/) {
2696: ($descr,$inst_code,$lasttime)=($1,$2,$3);
2697: } else {
2698: ($descr,$lasttime) = split(/\:/,$value);
2699: }
2700: if ($lasttime<$since) { next; }
2701: if ($description eq '.') {
2702: $qresult.=$key.'='.$descr.':'.$inst_code.'&';
2703: } else {
2704: my $unescapeVal = &unescape($descr);
2705: if (eval('$unescapeVal=~/\Q$description\E/i')) {
2706: $qresult.=$key.'='.$descr.':'.$inst_code.'&';
2707: }
2708: }
2709: }
2710: if (untie(%hash)) {
2711: chop($qresult);
2712: print $client "$qresult\n";
2713: } else {
2714: print $client "error: ".($!+0)
2715: ." untie(GDBM) Failed ".
2716: "while attempting courseiddump\n";
2717: }
2718: } else {
2719: print $client "error: ".($!+0)
2720: ." tie(GDBM) Failed ".
2721: "while attempting courseiddump\n";
2722: }
2723: } else {
2724: Reply($client, "refused\n", $userinput);
2725:
2726: }
2727: # ----------------------------------------------------------------------- idput
2728: } elsif ($userinput =~ /^idput/) {
2729: if(isClient) {
2730: my ($cmd,$udom,$what)=split(/:/,$userinput);
2731: chomp($what);
2732: $udom=~s/\W//g;
2733: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
2734: my $now=time;
2735: my @pairs=split(/\&/,$what);
2736: my %hash;
2737: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
2738: {
2739: my $hfh;
2740: if ($hfh=IO::File->new(">>$proname.hist")) {
2741: print $hfh "P:$now:$what\n";
2742: }
2743: }
2744: foreach my $pair (@pairs) {
2745: my ($key,$value)=split(/=/,$pair);
2746: $hash{$key}=$value;
2747: }
2748: if (untie(%hash)) {
2749: print $client "ok\n";
2750: } else {
2751: print $client "error: ".($!+0)
2752: ." untie(GDBM) Failed ".
2753: "while attempting idput\n";
2754: }
2755: } else {
2756: print $client "error: ".($!+0)
2757: ." tie(GDBM) Failed ".
2758: "while attempting idput\n";
2759: }
2760: } else {
2761: Reply($client, "refused\n", $userinput);
2762:
2763: }
2764: # ----------------------------------------------------------------------- idget
2765: } elsif ($userinput =~ /^idget/) {
2766: if(isClient) {
2767: my ($cmd,$udom,$what)=split(/:/,$userinput);
2768: chomp($what);
2769: $udom=~s/\W//g;
2770: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
2771: my @queries=split(/\&/,$what);
2772: my $qresult='';
2773: my %hash;
2774: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
2775: for (my $i=0;$i<=$#queries;$i++) {
2776: $qresult.="$hash{$queries[$i]}&";
2777: }
2778: if (untie(%hash)) {
2779: $qresult=~s/\&$//;
2780: print $client "$qresult\n";
2781: } else {
2782: print $client "error: ".($!+0)
2783: ." untie(GDBM) Failed ".
2784: "while attempting idget\n";
2785: }
2786: } else {
2787: print $client "error: ".($!+0)
2788: ." tie(GDBM) Failed ".
2789: "while attempting idget\n";
2790: }
2791: } else {
2792: Reply($client, "refused\n", $userinput);
2793:
2794: }
2795: # ---------------------------------------------------------------------- tmpput
2796: } elsif ($userinput =~ /^tmpput/) {
2797: if(isClient) {
2798: my ($cmd,$what)=split(/:/,$userinput);
2799: my $store;
2800: $tmpsnum++;
2801: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
2802: $id=~s/\W/\_/g;
2803: $what=~s/\n//g;
2804: my $execdir=$perlvar{'lonDaemons'};
2805: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
2806: print $store $what;
2807: close $store;
2808: print $client "$id\n";
2809: }
2810: else {
2811: print $client "error: ".($!+0)
2812: ."IO::File->new Failed ".
2813: "while attempting tmpput\n";
2814: }
2815: } else {
2816: Reply($client, "refused\n", $userinput);
2817:
2818: }
2819:
2820: # ---------------------------------------------------------------------- tmpget
2821: } elsif ($userinput =~ /^tmpget/) {
2822: if(isClient) {
2823: my ($cmd,$id)=split(/:/,$userinput);
2824: chomp($id);
2825: $id=~s/\W/\_/g;
2826: my $store;
2827: my $execdir=$perlvar{'lonDaemons'};
2828: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
2829: my $reply=<$store>;
2830: print $client "$reply\n";
2831: close $store;
2832: }
2833: else {
2834: print $client "error: ".($!+0)
2835: ."IO::File->new Failed ".
2836: "while attempting tmpget\n";
2837: }
2838: } else {
2839: Reply($client, "refused\n", $userinput);
2840:
2841: }
2842: # ---------------------------------------------------------------------- tmpdel
2843: } elsif ($userinput =~ /^tmpdel/) {
2844: if(isClient) {
2845: my ($cmd,$id)=split(/:/,$userinput);
2846: chomp($id);
2847: $id=~s/\W/\_/g;
2848: my $execdir=$perlvar{'lonDaemons'};
2849: if (unlink("$execdir/tmp/$id.tmp")) {
2850: print $client "ok\n";
2851: } else {
2852: print $client "error: ".($!+0)
2853: ."Unlink tmp Failed ".
2854: "while attempting tmpdel\n";
2855: }
2856: } else {
2857: Reply($client, "refused\n", $userinput);
2858:
2859: }
2860: # ----------------------------------------- portfolio directory list (portls)
2861: } elsif ($userinput =~ /^portls/) {
2862: if(isClient) {
2863: my ($cmd,$uname,$udom)=split(/:/,$userinput);
2864: my $udir=propath($udom,$uname).'/userfiles/portfolio';
2865: my $dirLine='';
2866: my $dirContents='';
2867: if (opendir(LSDIR,$udir.'/')){
2868: while ($dirLine = readdir(LSDIR)){
2869: $dirContents = $dirContents.$dirLine.'<br />';
2870: }
2871: } else {
2872: $dirContents = "No directory found\n";
2873: }
2874: print $client $dirContents."\n";
2875: } else {
2876: Reply($client, "refused\n", $userinput);
2877: }
2878: # -------------------------------------------------------------------------- ls
2879: } elsif ($userinput =~ /^ls/) {
2880: if(isClient) {
2881: my $obs;
2882: my $rights;
2883: my ($cmd,$ulsdir)=split(/:/,$userinput);
2884: my $ulsout='';
2885: my $ulsfn;
2886: if (-e $ulsdir) {
2887: if(-d $ulsdir) {
2888: if (opendir(LSDIR,$ulsdir)) {
2889: while ($ulsfn=readdir(LSDIR)) {
2890: undef $obs, $rights;
2891: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
2892: #We do some obsolete checking here
2893: if(-e $ulsdir.'/'.$ulsfn.".meta") {
2894: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
2895: my @obsolete=<FILE>;
2896: foreach my $obsolete (@obsolete) {
2897: if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; }
2898: if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
2899: }
2900: }
2901: $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
2902: if($obs eq '1') { $ulsout.="&1"; }
2903: else { $ulsout.="&0"; }
2904: if($rights eq '1') { $ulsout.="&1:"; }
2905: else { $ulsout.="&0:"; }
2906: }
2907: closedir(LSDIR);
2908: }
2909: } else {
2910: my @ulsstats=stat($ulsdir);
2911: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
2912: }
2913: } else {
2914: $ulsout='no_such_dir';
2915: }
2916: if ($ulsout eq '') { $ulsout='empty'; }
2917: print $client "$ulsout\n";
2918: } else {
2919: Reply($client, "refused\n", $userinput);
2920:
2921: }
2922: # ----------------------------------------------------------------- setannounce
2923: } elsif ($userinput =~ /^setannounce/) {
2924: if (isClient) {
2925: my ($cmd,$announcement)=split(/:/,$userinput);
2926: chomp($announcement);
2927: $announcement=&unescape($announcement);
2928: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
2929: '/announcement.txt')) {
2930: print $store $announcement;
2931: close $store;
2932: print $client "ok\n";
2933: } else {
2934: print $client "error: ".($!+0)."\n";
2935: }
2936: } else {
2937: Reply($client, "refused\n", $userinput);
2938:
2939: }
2940: # ------------------------------------------------------------------ Hanging up
2941: } elsif (($userinput =~ /^exit/) ||
2942: ($userinput =~ /^init/)) { # no restrictions.
2943: &logthis(
2944: "Client $clientip ($clientname) hanging up: $userinput");
2945: print $client "bye\n";
2946: $client->shutdown(2); # shutdown the socket forcibly.
2947: $client->close();
2948: return 0;
2949:
2950: # ---------------------------------- set current host/domain
2951: } elsif ($userinput =~ /^sethost:/) {
2952: if (isClient) {
2953: print $client &sethost($userinput)."\n";
2954: } else {
2955: print $client "refused\n";
2956: }
2957: #---------------------------------- request file (?) version.
2958: } elsif ($userinput =~/^version:/) {
2959: if (isClient) {
2960: print $client &version($userinput)."\n";
2961: } else {
2962: print $client "refused\n";
2963: }
2964: #------------------------------- is auto-enrollment enabled?
2965: } elsif ($userinput =~/^autorun:/) {
2966: if (isClient) {
2967: my ($cmd,$cdom) = split(/:/,$userinput);
2968: my $outcome = &localenroll::run($cdom);
2969: print $client "$outcome\n";
2970: } else {
2971: print $client "0\n";
2972: }
2973: #------------------------------- get official sections (for auto-enrollment).
2974: } elsif ($userinput =~/^autogetsections:/) {
2975: if (isClient) {
2976: my ($cmd,$coursecode,$cdom)=split(/:/,$userinput);
2977: my @secs = &localenroll::get_sections($coursecode,$cdom);
2978: my $seclist = &escape(join(':',@secs));
2979: print $client "$seclist\n";
2980: } else {
2981: print $client "refused\n";
2982: }
2983: #----------------------- validate owner of new course section (for auto-enrollment).
2984: } elsif ($userinput =~/^autonewcourse:/) {
2985: if (isClient) {
2986: my ($cmd,$inst_course_id,$owner,$cdom)=split(/:/,$userinput);
2987: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
2988: print $client "$outcome\n";
2989: } else {
2990: print $client "refused\n";
2991: }
2992: #-------------- validate course section in schedule of classes (for auto-enrollment).
2993: } elsif ($userinput =~/^autovalidatecourse:/) {
2994: if (isClient) {
2995: my ($cmd,$inst_course_id,$cdom)=split(/:/,$userinput);
2996: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
2997: print $client "$outcome\n";
2998: } else {
2999: print $client "refused\n";
3000: }
3001: #--------------------------- create password for new user (for auto-enrollment).
3002: } elsif ($userinput =~/^autocreatepassword:/) {
3003: if (isClient) {
3004: my ($cmd,$authparam,$cdom)=split(/:/,$userinput);
3005: my ($create_passwd,$authchk);
3006: ($authparam,$create_passwd,$authchk) = &localenroll::create_password($authparam,$cdom);
3007: print $client &escape($authparam.':'.$create_passwd.':'.$authchk)."\n";
3008: } else {
3009: print $client "refused\n";
3010: }
3011: #--------------------------- read and remove temporary files (for auto-enrollment).
3012: } elsif ($userinput =~/^autoretrieve:/) {
3013: if (isClient) {
3014: my ($cmd,$filename) = split(/:/,$userinput);
3015: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
3016: if ( (-e $source) && ($filename ne '') ) {
3017: my $reply = '';
3018: if (open(my $fh,$source)) {
3019: while (<$fh>) {
3020: chomp($_);
3021: $_ =~ s/^\s+//g;
3022: $_ =~ s/\s+$//g;
3023: $reply .= $_;
3024: }
3025: close($fh);
3026: print $client &escape($reply)."\n";
3027: # unlink($source);
3028: } else {
3029: print $client "error\n";
3030: }
3031: } else {
3032: print $client "error\n";
3033: }
3034: } else {
3035: print $client "refused\n";
3036: }
3037: #--------------------- read and retrieve institutional code format (for support form).
3038: } elsif ($userinput =~/^autoinstcodeformat:/) {
3039: if (isClient) {
3040: my $reply;
3041: my($cmd,$cdom,$course) = split(/:/,$userinput);
3042: my @pairs = split/\&/,$course;
3043: my %instcodes = ();
3044: my %codes = ();
3045: my @codetitles = ();
3046: my %cat_titles = ();
3047: my %cat_order = ();
3048: foreach (@pairs) {
3049: my ($key,$value) = split/=/,$_;
3050: $instcodes{&unescape($key)} = &unescape($value);
3051: }
3052: my $formatreply = &localenroll::instcode_format($cdom,\%instcodes,\%codes,\@codetitles,\%cat_titles,\%cat_order);
3053: if ($formatreply eq 'ok') {
3054: my $codes_str = &hash2str(%codes);
3055: my $codetitles_str = &array2str(@codetitles);
3056: my $cat_titles_str = &hash2str(%cat_titles);
3057: my $cat_order_str = &hash2str(%cat_order);
3058: print $client $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'.$cat_order_str."\n";
3059: }
3060: } else {
3061: print $client "refused\n";
3062: }
3063: # ------------------------------------------------------------- unknown command
3064:
3065: } else {
3066: # unknown command
3067: print $client "unknown_cmd\n";
3068: }
3069: # -------------------------------------------------------------------- complete
3070: Debug("process_request - returning 1");
3071: return 1;
3072: }
1.207 foxr 3073: #
3074: # Decipher encoded traffic
3075: # Parameters:
3076: # input - Encoded data.
3077: # Returns:
3078: # Decoded data or undef if encryption key was not yet negotiated.
3079: # Implicit input:
3080: # cipher - This global holds the negotiated encryption key.
3081: #
1.211 albertel 3082: sub decipher {
1.207 foxr 3083: my ($input) = @_;
3084: my $output = '';
1.212 foxr 3085:
3086:
1.207 foxr 3087: if($cipher) {
3088: my($enc, $enclength, $encinput) = split(/:/, $input);
3089: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
3090: $output .=
3091: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
3092: }
3093: return substr($output, 0, $enclength);
3094: } else {
3095: return undef;
3096: }
3097: }
3098:
3099: #
3100: # Register a command processor. This function is invoked to register a sub
3101: # to process a request. Once registered, the ProcessRequest sub can automatically
3102: # dispatch requests to an appropriate sub, and do the top level validity checking
3103: # as well:
3104: # - Is the keyword recognized.
3105: # - Is the proper client type attempting the request.
3106: # - Is the request encrypted if it has to be.
3107: # Parameters:
3108: # $request_name - Name of the request being registered.
3109: # This is the command request that will match
3110: # against the hash keywords to lookup the information
3111: # associated with the dispatch information.
3112: # $procedure - Reference to a sub to call to process the request.
3113: # All subs get called as follows:
3114: # Procedure($cmd, $tail, $replyfd, $key)
3115: # $cmd - the actual keyword that invoked us.
3116: # $tail - the tail of the request that invoked us.
3117: # $replyfd- File descriptor connected to the client
3118: # $must_encode - True if the request must be encoded to be good.
3119: # $client_ok - True if it's ok for a client to request this.
3120: # $manager_ok - True if it's ok for a manager to request this.
3121: # Side effects:
3122: # - On success, the Dispatcher hash has an entry added for the key $RequestName
3123: # - On failure, the program will die as it's a bad internal bug to try to
3124: # register a duplicate command handler.
3125: #
1.211 albertel 3126: sub register_handler {
1.212 foxr 3127: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
1.207 foxr 3128:
3129: # Don't allow duplication#
3130:
3131: if (defined $Dispatcher{$request_name}) {
3132: die "Attempting to define a duplicate request handler for $request_name\n";
3133: }
3134: # Build the client type mask:
3135:
3136: my $client_type_mask = 0;
3137: if($client_ok) {
3138: $client_type_mask |= $CLIENT_OK;
3139: }
3140: if($manager_ok) {
3141: $client_type_mask |= $MANAGER_OK;
3142: }
3143:
3144: # Enter the hash:
3145:
3146: my @entry = ($procedure, $must_encode, $client_type_mask);
3147:
3148: $Dispatcher{$request_name} = \@entry;
3149:
3150: }
3151:
3152:
3153: #------------------------------------------------------------------
3154:
3155:
3156:
3157:
1.141 foxr 3158: #
1.96 foxr 3159: # Convert an error return code from lcpasswd to a string value.
3160: #
3161: sub lcpasswdstrerror {
3162: my $ErrorCode = shift;
1.97 foxr 3163: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 3164: return "lcpasswd Unrecognized error return value ".$ErrorCode;
3165: } else {
1.98 foxr 3166: return $passwderrors[$ErrorCode];
1.96 foxr 3167: }
3168: }
3169:
1.97 foxr 3170: #
3171: # Convert an error return code from lcuseradd to a string value:
3172: #
3173: sub lcuseraddstrerror {
3174: my $ErrorCode = shift;
3175: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
3176: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
3177: } else {
1.98 foxr 3178: return $adderrors[$ErrorCode];
1.97 foxr 3179: }
3180: }
3181:
1.23 harris41 3182: # grabs exception and records it to log before exiting
3183: sub catchexception {
1.27 albertel 3184: my ($error)=@_;
1.25 www 3185: $SIG{'QUIT'}='DEFAULT';
3186: $SIG{__DIE__}='DEFAULT';
1.165 albertel 3187: &status("Catching exception");
1.190 albertel 3188: &logthis("<font color='red'>CRITICAL: "
1.134 albertel 3189: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27 albertel 3190: ."a crash with this error msg->[$error]</font>");
1.57 www 3191: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 3192: if ($client) { print $client "error: $error\n"; }
1.59 www 3193: $server->close();
1.27 albertel 3194: die($error);
1.23 harris41 3195: }
1.63 www 3196: sub timeout {
1.165 albertel 3197: &status("Handling Timeout");
1.190 albertel 3198: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63 www 3199: &catchexception('Timeout');
3200: }
1.22 harris41 3201: # -------------------------------- Set signal handlers to record abnormal exits
3202:
1.226 foxr 3203:
1.22 harris41 3204: $SIG{'QUIT'}=\&catchexception;
3205: $SIG{__DIE__}=\&catchexception;
3206:
1.81 matthew 3207: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 3208: &status("Read loncapa.conf and loncapa_apache.conf");
3209: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 3210: %perlvar=%{$perlvarref};
1.80 harris41 3211: undef $perlvarref;
1.19 www 3212:
1.35 harris41 3213: # ----------------------------- Make sure this process is running from user=www
3214: my $wwwid=getpwnam('www');
3215: if ($wwwid!=$<) {
1.134 albertel 3216: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
3217: my $subj="LON: $currenthostid User ID mismatch";
1.37 harris41 3218: system("echo 'User ID mismatch. lond must be run as user www.' |\
1.35 harris41 3219: mailto $emailto -s '$subj' > /dev/null");
3220: exit 1;
3221: }
3222:
1.19 www 3223: # --------------------------------------------- Check if other instance running
3224:
3225: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
3226:
3227: if (-e $pidfile) {
3228: my $lfh=IO::File->new("$pidfile");
3229: my $pide=<$lfh>;
3230: chomp($pide);
1.29 harris41 3231: if (kill 0 => $pide) { die "already running"; }
1.19 www 3232: }
1.1 albertel 3233:
3234: # ------------------------------------------------------------- Read hosts file
3235:
3236:
3237:
3238: # establish SERVER socket, bind and listen.
3239: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
3240: Type => SOCK_STREAM,
3241: Proto => 'tcp',
3242: Reuse => 1,
3243: Listen => 10 )
1.29 harris41 3244: or die "making socket: $@\n";
1.1 albertel 3245:
3246: # --------------------------------------------------------- Do global variables
3247:
3248: # global variables
3249:
1.134 albertel 3250: my %children = (); # keys are current child process IDs
1.1 albertel 3251:
3252: sub REAPER { # takes care of dead children
3253: $SIG{CHLD} = \&REAPER;
1.165 albertel 3254: &status("Handling child death");
1.178 foxr 3255: my $pid;
3256: do {
3257: $pid = waitpid(-1,&WNOHANG());
3258: if (defined($children{$pid})) {
3259: &logthis("Child $pid died");
3260: delete($children{$pid});
1.183 albertel 3261: } elsif ($pid > 0) {
1.178 foxr 3262: &logthis("Unknown Child $pid died");
3263: }
3264: } while ( $pid > 0 );
3265: foreach my $child (keys(%children)) {
3266: $pid = waitpid($child,&WNOHANG());
3267: if ($pid > 0) {
3268: &logthis("Child $child - $pid looks like we missed it's death");
3269: delete($children{$pid});
3270: }
1.176 albertel 3271: }
1.165 albertel 3272: &status("Finished Handling child death");
1.1 albertel 3273: }
3274:
3275: sub HUNTSMAN { # signal handler for SIGINT
1.165 albertel 3276: &status("Killing children (INT)");
1.1 albertel 3277: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
3278: kill 'INT' => keys %children;
1.59 www 3279: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 3280: my $execdir=$perlvar{'lonDaemons'};
3281: unlink("$execdir/logs/lond.pid");
1.190 albertel 3282: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165 albertel 3283: &status("Done killing children");
1.1 albertel 3284: exit; # clean up with dignity
3285: }
3286:
3287: sub HUPSMAN { # signal handler for SIGHUP
3288: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.165 albertel 3289: &status("Killing children for restart (HUP)");
1.1 albertel 3290: kill 'INT' => keys %children;
1.59 www 3291: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190 albertel 3292: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134 albertel 3293: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 3294: unlink("$execdir/logs/lond.pid");
1.165 albertel 3295: &status("Restarting self (HUP)");
1.1 albertel 3296: exec("$execdir/lond"); # here we go again
3297: }
3298:
1.144 foxr 3299: #
1.148 foxr 3300: # Kill off hashes that describe the host table prior to re-reading it.
3301: # Hashes affected are:
1.200 matthew 3302: # %hostid, %hostdom %hostip %hostdns.
1.148 foxr 3303: #
3304: sub KillHostHashes {
3305: foreach my $key (keys %hostid) {
3306: delete $hostid{$key};
3307: }
3308: foreach my $key (keys %hostdom) {
3309: delete $hostdom{$key};
3310: }
3311: foreach my $key (keys %hostip) {
3312: delete $hostip{$key};
3313: }
1.200 matthew 3314: foreach my $key (keys %hostdns) {
3315: delete $hostdns{$key};
3316: }
1.148 foxr 3317: }
3318: #
3319: # Read in the host table from file and distribute it into the various hashes:
3320: #
3321: # - %hostid - Indexed by IP, the loncapa hostname.
3322: # - %hostdom - Indexed by loncapa hostname, the domain.
3323: # - %hostip - Indexed by hostid, the Ip address of the host.
3324: sub ReadHostTable {
3325:
3326: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200 matthew 3327: my $myloncapaname = $perlvar{'lonHostID'};
3328: Debug("My loncapa name is : $myloncapaname");
1.148 foxr 3329: while (my $configline=<CONFIG>) {
1.178 foxr 3330: if (!($configline =~ /^\s*\#/)) {
3331: my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
3332: chomp($ip); $ip=~s/\D+$//;
1.200 matthew 3333: $hostid{$ip}=$id; # LonCAPA name of host by IP.
3334: $hostdom{$id}=$domain; # LonCAPA domain name of host.
3335: $hostip{$id}=$ip; # IP address of host.
3336: $hostdns{$name} = $id; # LonCAPA name of host by DNS.
3337:
3338: if ($id eq $perlvar{'lonHostID'}) {
3339: Debug("Found me in the host table: $name");
3340: $thisserver=$name;
3341: }
1.178 foxr 3342: }
1.148 foxr 3343: }
3344: close(CONFIG);
3345: }
3346: #
3347: # Reload the Apache daemon's state.
1.150 foxr 3348: # This is done by invoking /home/httpd/perl/apachereload
3349: # a setuid perl script that can be root for us to do this job.
1.148 foxr 3350: #
3351: sub ReloadApache {
1.150 foxr 3352: my $execdir = $perlvar{'lonDaemons'};
3353: my $script = $execdir."/apachereload";
3354: system($script);
1.148 foxr 3355: }
3356:
3357: #
1.144 foxr 3358: # Called in response to a USR2 signal.
3359: # - Reread hosts.tab
3360: # - All children connected to hosts that were removed from hosts.tab
3361: # are killed via SIGINT
3362: # - All children connected to previously existing hosts are sent SIGUSR1
3363: # - Our internal hosts hash is updated to reflect the new contents of
3364: # hosts.tab causing connections from hosts added to hosts.tab to
3365: # now be honored.
3366: #
3367: sub UpdateHosts {
1.165 albertel 3368: &status("Reload hosts.tab");
1.147 foxr 3369: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 3370: #
3371: # The %children hash has the set of IP's we currently have children
3372: # on. These need to be matched against records in the hosts.tab
3373: # Any ip's no longer in the table get killed off they correspond to
3374: # either dropped or changed hosts. Note that the re-read of the table
3375: # will take care of new and changed hosts as connections come into being.
3376:
3377:
3378: KillHostHashes;
3379: ReadHostTable;
3380:
3381: foreach my $child (keys %children) {
3382: my $childip = $children{$child};
3383: if(!$hostid{$childip}) {
1.149 foxr 3384: logthis('<font color="blue"> UpdateHosts killing child '
3385: ." $child for ip $childip </font>");
1.148 foxr 3386: kill('INT', $child);
1.149 foxr 3387: } else {
3388: logthis('<font color="green"> keeping child for ip '
3389: ." $childip (pid=$child) </font>");
1.148 foxr 3390: }
3391: }
3392: ReloadApache;
1.165 albertel 3393: &status("Finished reloading hosts.tab");
1.144 foxr 3394: }
3395:
1.148 foxr 3396:
1.57 www 3397: sub checkchildren {
1.165 albertel 3398: &status("Checking on the children (sending signals)");
1.57 www 3399: &initnewstatus();
3400: &logstatus();
3401: &logthis('Going to check on the children');
1.134 albertel 3402: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 3403: foreach (sort keys %children) {
1.221 albertel 3404: #sleep 1;
1.57 www 3405: unless (kill 'USR1' => $_) {
3406: &logthis ('Child '.$_.' is dead');
3407: &logstatus($$.' is dead');
1.221 albertel 3408: delete($children{$_});
1.57 www 3409: }
1.61 harris41 3410: }
1.63 www 3411: sleep 5;
1.212 foxr 3412: $SIG{ALRM} = sub { Debug("timeout");
3413: die "timeout"; };
1.113 albertel 3414: $SIG{__DIE__} = 'DEFAULT';
1.165 albertel 3415: &status("Checking on the children (waiting for reports)");
1.63 www 3416: foreach (sort keys %children) {
3417: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 3418: eval {
3419: alarm(300);
1.63 www 3420: &logthis('Child '.$_.' did not respond');
1.67 albertel 3421: kill 9 => $_;
1.131 albertel 3422: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
3423: #$subj="LON: $currenthostid killed lond process $_";
3424: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
3425: #$execdir=$perlvar{'lonDaemons'};
3426: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221 albertel 3427: delete($children{$_});
1.113 albertel 3428: alarm(0);
3429: }
1.63 www 3430: }
3431: }
1.113 albertel 3432: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 3433: $SIG{__DIE__} = \&catchexception;
1.165 albertel 3434: &status("Finished checking children");
1.221 albertel 3435: &logthis('Finished Checking children');
1.57 www 3436: }
3437:
1.1 albertel 3438: # --------------------------------------------------------------------- Logging
3439:
3440: sub logthis {
3441: my $message=shift;
3442: my $execdir=$perlvar{'lonDaemons'};
3443: my $fh=IO::File->new(">>$execdir/logs/lond.log");
3444: my $now=time;
3445: my $local=localtime($now);
1.58 www 3446: $lastlog=$local.': '.$message;
1.1 albertel 3447: print $fh "$local ($$): $message\n";
3448: }
3449:
1.77 foxr 3450: # ------------------------- Conditional log if $DEBUG true.
3451: sub Debug {
3452: my $message = shift;
3453: if($DEBUG) {
3454: &logthis($message);
3455: }
3456: }
1.161 foxr 3457:
3458: #
3459: # Sub to do replies to client.. this gives a hook for some
3460: # debug tracing too:
3461: # Parameters:
3462: # fd - File open on client.
3463: # reply - Text to send to client.
3464: # request - Original request from client.
3465: #
3466: sub Reply {
1.192 foxr 3467: my ($fd, $reply, $request) = @_;
1.161 foxr 3468: print $fd $reply;
3469: Debug("Request was $request Reply was $reply");
3470:
1.212 foxr 3471: $Transactions++;
3472:
3473:
3474: }
3475:
3476:
3477: #
3478: # Sub to report a failure.
3479: # This function:
3480: # - Increments the failure statistic counters.
3481: # - Invokes Reply to send the error message to the client.
3482: # Parameters:
3483: # fd - File descriptor open on the client
3484: # reply - Reply text to emit.
3485: # request - The original request message (used by Reply
3486: # to debug if that's enabled.
3487: # Implicit outputs:
3488: # $Failures- The number of failures is incremented.
3489: # Reply (invoked here) sends a message to the
3490: # client:
3491: #
3492: sub Failure {
3493: my $fd = shift;
3494: my $reply = shift;
3495: my $request = shift;
3496:
3497: $Failures++;
3498: Reply($fd, $reply, $request); # That's simple eh?
1.161 foxr 3499: }
1.57 www 3500: # ------------------------------------------------------------------ Log status
3501:
3502: sub logstatus {
1.178 foxr 3503: &status("Doing logging");
3504: my $docdir=$perlvar{'lonDocRoot'};
3505: {
3506: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200 matthew 3507: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178 foxr 3508: $fh->close();
3509: }
1.221 albertel 3510: &status("Finished $$.txt");
3511: {
3512: open(LOG,">>$docdir/lon-status/londstatus.txt");
3513: flock(LOG,LOCK_EX);
3514: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
3515: .$status."\t".$lastlog."\t $keymode\n";
3516: flock(DB,LOCK_UN);
3517: close(LOG);
3518: }
1.178 foxr 3519: &status("Finished logging");
1.57 www 3520: }
3521:
3522: sub initnewstatus {
3523: my $docdir=$perlvar{'lonDocRoot'};
3524: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
3525: my $now=time;
3526: my $local=localtime($now);
3527: print $fh "LOND status $local - parent $$\n\n";
1.64 www 3528: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 3529: while (my $filename=readdir(DIR)) {
1.64 www 3530: unlink("$docdir/lon-status/londchld/$filename");
3531: }
3532: closedir(DIR);
1.57 www 3533: }
3534:
3535: # -------------------------------------------------------------- Status setting
3536:
3537: sub status {
3538: my $what=shift;
3539: my $now=time;
3540: my $local=localtime($now);
1.178 foxr 3541: $status=$local.': '.$what;
3542: $0='lond: '.$what.' '.$local;
1.57 www 3543: }
1.11 www 3544:
3545: # -------------------------------------------------------- Escape Special Chars
3546:
3547: sub escape {
3548: my $str=shift;
3549: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
3550: return $str;
3551: }
3552:
3553: # ----------------------------------------------------- Un-Escape Special Chars
3554:
3555: sub unescape {
3556: my $str=shift;
3557: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
3558: return $str;
3559: }
3560:
1.1 albertel 3561: # ----------------------------------------------------------- Send USR1 to lonc
3562:
3563: sub reconlonc {
3564: my $peerfile=shift;
3565: &logthis("Trying to reconnect for $peerfile");
3566: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
3567: if (my $fh=IO::File->new("$loncfile")) {
3568: my $loncpid=<$fh>;
3569: chomp($loncpid);
3570: if (kill 0 => $loncpid) {
3571: &logthis("lonc at pid $loncpid responding, sending USR1");
3572: kill USR1 => $loncpid;
3573: } else {
1.9 www 3574: &logthis(
1.190 albertel 3575: "<font color='red'>CRITICAL: "
1.9 www 3576: ."lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 3577: }
3578: } else {
1.190 albertel 3579: &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1 albertel 3580: }
3581: }
3582:
3583: # -------------------------------------------------- Non-critical communication
1.11 www 3584:
1.1 albertel 3585: sub subreply {
3586: my ($cmd,$server)=@_;
3587: my $peerfile="$perlvar{'lonSockDir'}/$server";
3588: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
3589: Type => SOCK_STREAM,
3590: Timeout => 10)
3591: or return "con_lost";
3592: print $sclient "$cmd\n";
3593: my $answer=<$sclient>;
3594: chomp($answer);
3595: if (!$answer) { $answer="con_lost"; }
3596: return $answer;
3597: }
3598:
3599: sub reply {
3600: my ($cmd,$server)=@_;
3601: my $answer;
1.115 albertel 3602: if ($server ne $currenthostid) {
1.1 albertel 3603: $answer=subreply($cmd,$server);
3604: if ($answer eq 'con_lost') {
3605: $answer=subreply("ping",$server);
3606: if ($answer ne $server) {
1.115 albertel 3607: &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1 albertel 3608: &reconlonc("$perlvar{'lonSockDir'}/$server");
3609: }
3610: $answer=subreply($cmd,$server);
3611: }
3612: } else {
3613: $answer='self_reply';
3614: }
3615: return $answer;
3616: }
3617:
1.13 www 3618: # -------------------------------------------------------------- Talk to lonsql
3619:
1.12 harris41 3620: sub sqlreply {
3621: my ($cmd)=@_;
3622: my $answer=subsqlreply($cmd);
3623: if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
3624: return $answer;
3625: }
3626:
3627: sub subsqlreply {
3628: my ($cmd)=@_;
3629: my $unixsock="mysqlsock";
3630: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
3631: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
3632: Type => SOCK_STREAM,
3633: Timeout => 10)
3634: or return "con_lost";
3635: print $sclient "$cmd\n";
3636: my $answer=<$sclient>;
3637: chomp($answer);
3638: if (!$answer) { $answer="con_lost"; }
3639: return $answer;
3640: }
3641:
1.1 albertel 3642: # -------------------------------------------- Return path to profile directory
1.11 www 3643:
1.1 albertel 3644: sub propath {
3645: my ($udom,$uname)=@_;
3646: $udom=~s/\W//g;
3647: $uname=~s/\W//g;
1.16 www 3648: my $subdir=$uname.'__';
1.1 albertel 3649: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3650: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
3651: return $proname;
3652: }
3653:
3654: # --------------------------------------- Is this the home server of an author?
1.11 www 3655:
1.1 albertel 3656: sub ishome {
3657: my $author=shift;
3658: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3659: my ($udom,$uname)=split(/\//,$author);
3660: my $proname=propath($udom,$uname);
3661: if (-e $proname) {
3662: return 'owner';
3663: } else {
3664: return 'not_owner';
3665: }
3666: }
3667:
3668: # ======================================================= Continue main program
3669: # ---------------------------------------------------- Fork once and dissociate
3670:
1.134 albertel 3671: my $fpid=fork;
1.1 albertel 3672: exit if $fpid;
1.29 harris41 3673: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 3674:
1.29 harris41 3675: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 3676:
3677: # ------------------------------------------------------- Write our PID on disk
3678:
1.134 albertel 3679: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 3680: open (PIDSAVE,">$execdir/logs/lond.pid");
3681: print PIDSAVE "$$\n";
3682: close(PIDSAVE);
1.190 albertel 3683: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57 www 3684: &status('Starting');
1.1 albertel 3685:
1.106 foxr 3686:
1.1 albertel 3687:
3688: # ----------------------------------------------------- Install signal handlers
3689:
1.57 www 3690:
1.1 albertel 3691: $SIG{CHLD} = \&REAPER;
3692: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
3693: $SIG{HUP} = \&HUPSMAN;
1.57 www 3694: $SIG{USR1} = \&checkchildren;
1.144 foxr 3695: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 3696:
1.148 foxr 3697: # Read the host hashes:
3698:
3699: ReadHostTable;
1.106 foxr 3700:
3701: # --------------------------------------------------------------
3702: # Accept connections. When a connection comes in, it is validated
3703: # and if good, a child process is created to process transactions
3704: # along the connection.
3705:
1.1 albertel 3706: while (1) {
1.165 albertel 3707: &status('Starting accept');
1.106 foxr 3708: $client = $server->accept() or next;
1.165 albertel 3709: &status('Accepted '.$client.' off to spawn');
1.106 foxr 3710: make_new_child($client);
1.165 albertel 3711: &status('Finished spawning');
1.1 albertel 3712: }
3713:
1.212 foxr 3714: sub make_new_child {
3715: my $pid;
3716: # my $cipher; # Now global
3717: my $sigset;
1.178 foxr 3718:
1.212 foxr 3719: $client = shift;
3720: &status('Starting new child '.$client);
3721: &logthis('<font color="green"> Attempting to start child ('.$client.
3722: ")</font>");
3723: # block signal for fork
3724: $sigset = POSIX::SigSet->new(SIGINT);
3725: sigprocmask(SIG_BLOCK, $sigset)
3726: or die "Can't block SIGINT for fork: $!\n";
1.178 foxr 3727:
1.212 foxr 3728: die "fork: $!" unless defined ($pid = fork);
1.178 foxr 3729:
1.212 foxr 3730: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
3731: # connection liveness.
1.178 foxr 3732:
1.212 foxr 3733: #
3734: # Figure out who we're talking to so we can record the peer in
3735: # the pid hash.
3736: #
3737: my $caller = getpeername($client);
3738: my ($port,$iaddr);
3739: if (defined($caller) && length($caller) > 0) {
3740: ($port,$iaddr)=unpack_sockaddr_in($caller);
3741: } else {
3742: &logthis("Unable to determine who caller was, getpeername returned nothing");
3743: }
3744: if (defined($iaddr)) {
3745: $clientip = inet_ntoa($iaddr);
3746: Debug("Connected with $clientip");
3747: $clientdns = gethostbyaddr($iaddr, AF_INET);
3748: Debug("Connected with $clientdns by name");
3749: } else {
3750: &logthis("Unable to determine clientip");
3751: $clientip='Unavailable';
3752: }
3753:
3754: if ($pid) {
3755: # Parent records the child's birth and returns.
3756: sigprocmask(SIG_UNBLOCK, $sigset)
3757: or die "Can't unblock SIGINT for fork: $!\n";
3758: $children{$pid} = $clientip;
3759: &status('Started child '.$pid);
3760: return;
3761: } else {
3762: # Child can *not* return from this subroutine.
3763: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
3764: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
3765: #don't get intercepted
3766: $SIG{USR1}= \&logstatus;
3767: $SIG{ALRM}= \&timeout;
3768: $lastlog='Forked ';
3769: $status='Forked';
1.178 foxr 3770:
1.212 foxr 3771: # unblock signals
3772: sigprocmask(SIG_UNBLOCK, $sigset)
3773: or die "Can't unblock SIGINT for fork: $!\n";
1.178 foxr 3774:
1.212 foxr 3775: # my $tmpsnum=0; # Now global
3776: #---------------------------------------------------- kerberos 5 initialization
3777: &Authen::Krb5::init_context();
3778: &Authen::Krb5::init_ets();
1.209 albertel 3779:
1.212 foxr 3780: &status('Accepted connection');
3781: # =============================================================================
3782: # do something with the connection
3783: # -----------------------------------------------------------------------------
3784: # see if we know client and 'check' for spoof IP by ineffective challenge
1.178 foxr 3785:
1.212 foxr 3786: ReadManagerTable; # May also be a manager!!
3787:
3788: my $clientrec=($hostid{$clientip} ne undef);
3789: my $ismanager=($managers{$clientip} ne undef);
3790: $clientname = "[unknonwn]";
3791: if($clientrec) { # Establish client type.
3792: $ConnectionType = "client";
3793: $clientname = $hostid{$clientip};
3794: if($ismanager) {
3795: $ConnectionType = "both";
3796: }
3797: } else {
3798: $ConnectionType = "manager";
3799: $clientname = $managers{$clientip};
3800: }
3801: my $clientok;
1.178 foxr 3802:
1.212 foxr 3803: if ($clientrec || $ismanager) {
3804: &status("Waiting for init from $clientip $clientname");
3805: &logthis('<font color="yellow">INFO: Connection, '.
3806: $clientip.
3807: " ($clientname) connection type = $ConnectionType </font>" );
3808: &status("Connecting $clientip ($clientname))");
3809: my $remotereq=<$client>;
3810: chomp($remotereq);
3811: Debug("Got init: $remotereq");
3812: my $inikeyword = split(/:/, $remotereq);
3813: if ($remotereq =~ /^init/) {
3814: &sethost("sethost:$perlvar{'lonHostID'}");
3815: #
3816: # If the remote is attempting a local init... give that a try:
3817: #
3818: my ($i, $inittype) = split(/:/, $remotereq);
1.209 albertel 3819:
1.212 foxr 3820: # If the connection type is ssl, but I didn't get my
3821: # certificate files yet, then I'll drop back to
3822: # insecure (if allowed).
3823:
3824: if($inittype eq "ssl") {
3825: my ($ca, $cert) = lonssl::CertificateFile;
3826: my $kfile = lonssl::KeyFile;
3827: if((!$ca) ||
3828: (!$cert) ||
3829: (!$kfile)) {
3830: $inittype = ""; # This forces insecure attempt.
3831: &logthis("<font color=\"blue\"> Certificates not "
3832: ."installed -- trying insecure auth</font>");
1.224 foxr 3833: } else { # SSL certificates are in place so
1.212 foxr 3834: } # Leave the inittype alone.
3835: }
3836:
3837: if($inittype eq "local") {
3838: my $key = LocalConnection($client, $remotereq);
3839: if($key) {
3840: Debug("Got local key $key");
3841: $clientok = 1;
3842: my $cipherkey = pack("H32", $key);
3843: $cipher = new IDEA($cipherkey);
3844: print $client "ok:local\n";
3845: &logthis('<font color="green"'
3846: . "Successful local authentication </font>");
3847: $keymode = "local"
1.178 foxr 3848: } else {
1.212 foxr 3849: Debug("Failed to get local key");
3850: $clientok = 0;
3851: shutdown($client, 3);
3852: close $client;
1.178 foxr 3853: }
1.212 foxr 3854: } elsif ($inittype eq "ssl") {
3855: my $key = SSLConnection($client);
3856: if ($key) {
3857: $clientok = 1;
3858: my $cipherkey = pack("H32", $key);
3859: $cipher = new IDEA($cipherkey);
3860: &logthis('<font color="green">'
3861: ."Successfull ssl authentication with $clientname </font>");
3862: $keymode = "ssl";
3863:
1.178 foxr 3864: } else {
1.212 foxr 3865: $clientok = 0;
3866: close $client;
1.178 foxr 3867: }
1.212 foxr 3868:
3869: } else {
3870: my $ok = InsecureConnection($client);
3871: if($ok) {
3872: $clientok = 1;
3873: &logthis('<font color="green">'
3874: ."Successful insecure authentication with $clientname </font>");
3875: print $client "ok\n";
3876: $keymode = "insecure";
1.178 foxr 3877: } else {
1.212 foxr 3878: &logthis('<font color="yellow">'
3879: ."Attempted insecure connection disallowed </font>");
3880: close $client;
3881: $clientok = 0;
1.178 foxr 3882:
3883: }
3884: }
1.212 foxr 3885: } else {
3886: &logthis(
3887: "<font color='blue'>WARNING: "
3888: ."$clientip failed to initialize: >$remotereq< </font>");
3889: &status('No init '.$clientip);
3890: }
3891:
3892: } else {
3893: &logthis(
3894: "<font color='blue'>WARNING: Unknown client $clientip</font>");
3895: &status('Hung up on '.$clientip);
3896: }
3897:
3898: if ($clientok) {
3899: # ---------------- New known client connecting, could mean machine online again
3900:
3901: foreach my $id (keys(%hostip)) {
3902: if ($hostip{$id} ne $clientip ||
3903: $hostip{$currenthostid} eq $clientip) {
3904: # no need to try to do recon's to myself
3905: next;
3906: }
3907: &reconlonc("$perlvar{'lonSockDir'}/$id");
3908: }
3909: &logthis("<font color='green'>Established connection: $clientname</font>");
3910: &status('Will listen to '.$clientname);
3911: # ------------------------------------------------------------ Process requests
3912: my $keep_going = 1;
3913: my $user_input;
3914: while(($user_input = get_request) && $keep_going) {
3915: alarm(120);
3916: Debug("Main: Got $user_input\n");
3917: $keep_going = &process_request($user_input);
1.178 foxr 3918: alarm(0);
1.212 foxr 3919: &status('Listening to '.$clientname." ($keymode)");
1.161 foxr 3920: }
1.212 foxr 3921:
1.59 www 3922: # --------------------------------------------- client unknown or fishy, refuse
1.212 foxr 3923: } else {
1.161 foxr 3924: print $client "refused\n";
3925: $client->close();
1.190 albertel 3926: &logthis("<font color='blue'>WARNING: "
1.161 foxr 3927: ."Rejected client $clientip, closing connection</font>");
3928: }
1.212 foxr 3929: }
1.161 foxr 3930:
1.1 albertel 3931: # =============================================================================
1.161 foxr 3932:
1.190 albertel 3933: &logthis("<font color='red'>CRITICAL: "
1.161 foxr 3934: ."Disconnect from $clientip ($clientname)</font>");
3935:
3936:
3937: # this exit is VERY important, otherwise the child will become
3938: # a producer of more and more children, forking yourself into
3939: # process death.
3940: exit;
1.106 foxr 3941:
1.78 foxr 3942: }
3943:
3944:
3945: #
3946: # Checks to see if the input roleput request was to set
3947: # an author role. If so, invokes the lchtmldir script to set
3948: # up a correct public_html
3949: # Parameters:
3950: # request - The request sent to the rolesput subchunk.
3951: # We're looking for /domain/_au
3952: # domain - The domain in which the user is having roles doctored.
3953: # user - Name of the user for which the role is being put.
3954: # authtype - The authentication type associated with the user.
3955: #
3956: sub ManagePermissions
3957: {
1.192 foxr 3958:
3959: my ($request, $domain, $user, $authtype) = @_;
1.78 foxr 3960:
3961: # See if the request is of the form /$domain/_au
3962: if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
3963: my $execdir = $perlvar{'lonDaemons'};
3964: my $userhome= "/home/$user" ;
1.134 albertel 3965: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.78 foxr 3966: system("$execdir/lchtmldir $userhome $user $authtype");
3967: }
3968: }
1.222 foxr 3969:
3970:
3971: #
3972: # Return the full path of a user password file, whether it exists or not.
3973: # Parameters:
3974: # domain - Domain in which the password file lives.
3975: # user - name of the user.
3976: # Returns:
3977: # Full passwd path:
3978: #
3979: sub password_path {
3980: my ($domain, $user) = @_;
3981:
3982:
3983: my $path = &propath($domain, $user);
3984: $path .= "/passwd";
3985:
3986: return $path;
3987: }
3988:
3989: # Password Filename
3990: # Returns the path to a passwd file given domain and user... only if
3991: # it exists.
3992: # Parameters:
3993: # domain - Domain in which to search.
3994: # user - username.
3995: # Returns:
3996: # - If the password file exists returns its path.
3997: # - If the password file does not exist, returns undefined.
3998: #
3999: sub password_filename {
4000: my ($domain, $user) = @_;
4001:
4002: Debug ("PasswordFilename called: dom = $domain user = $user");
4003:
4004: my $path = &password_path($domain, $user);
4005: Debug("PasswordFilename got path: $path");
4006: if(-e $path) {
4007: return $path;
4008: } else {
4009: return undef;
4010: }
4011: }
4012:
4013: #
4014: # Rewrite the contents of the user's passwd file.
4015: # Parameters:
4016: # domain - domain of the user.
4017: # name - User's name.
4018: # contents - New contents of the file.
4019: # Returns:
4020: # 0 - Failed.
4021: # 1 - Success.
4022: #
4023: sub rewrite_password_file {
4024: my ($domain, $user, $contents) = @_;
4025:
4026: my $file = &password_filename($domain, $user);
4027: if (defined $file) {
4028: my $pf = IO::File->new(">$file");
4029: if($pf) {
4030: print $pf "$contents\n";
4031: return 1;
4032: } else {
4033: return 0;
4034: }
4035: } else {
4036: return 0;
4037: }
4038:
4039: }
4040:
1.78 foxr 4041: #
1.222 foxr 4042: # get_auth_type - Determines the authorization type of a user in a domain.
1.78 foxr 4043:
4044: # Returns the authorization type or nouser if there is no such user.
4045: #
1.222 foxr 4046: sub get_auth_type
1.78 foxr 4047: {
1.192 foxr 4048:
4049: my ($domain, $user) = @_;
1.78 foxr 4050:
1.222 foxr 4051: Debug("get_auth_type( $domain, $user ) \n");
1.78 foxr 4052: my $proname = &propath($domain, $user);
4053: my $passwdfile = "$proname/passwd";
4054: if( -e $passwdfile ) {
4055: my $pf = IO::File->new($passwdfile);
4056: my $realpassword = <$pf>;
4057: chomp($realpassword);
1.79 foxr 4058: Debug("Password info = $realpassword\n");
1.78 foxr 4059: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 4060: Debug("Authtype = $authtype, content = $contentpwd\n");
1.78 foxr 4061: my $availinfo = '';
1.91 albertel 4062: if($authtype eq 'krb4' or $authtype eq 'krb5') {
1.78 foxr 4063: $availinfo = $contentpwd;
4064: }
1.79 foxr 4065:
1.78 foxr 4066: return "$authtype:$availinfo";
1.224 foxr 4067: } else {
1.79 foxr 4068: Debug("Returning nouser");
1.78 foxr 4069: return "nouser";
4070: }
1.1 albertel 4071: }
4072:
1.220 foxr 4073: #
4074: # Validate a user given their domain, name and password. This utility
4075: # function is used by both AuthenticateHandler and ChangePasswordHandler
4076: # to validate the login credentials of a user.
4077: # Parameters:
4078: # $domain - The domain being logged into (this is required due to
4079: # the capability for multihomed systems.
4080: # $user - The name of the user being validated.
4081: # $password - The user's propoposed password.
4082: #
4083: # Returns:
4084: # 1 - The domain,user,pasword triplet corresponds to a valid
4085: # user.
4086: # 0 - The domain,user,password triplet is not a valid user.
4087: #
4088: sub validate_user {
4089: my ($domain, $user, $password) = @_;
4090:
4091:
4092: # Why negative ~pi you may well ask? Well this function is about
4093: # authentication, and therefore very important to get right.
4094: # I've initialized the flag that determines whether or not I've
4095: # validated correctly to a value it's not supposed to get.
4096: # At the end of this function. I'll ensure that it's not still that
4097: # value so we don't just wind up returning some accidental value
4098: # as a result of executing an unforseen code path that
4099: # did not set $validated.
4100:
4101: my $validated = -3.14159;
4102:
4103: # How we authenticate is determined by the type of authentication
4104: # the user has been assigned. If the authentication type is
4105: # "nouser", the user does not exist so we will return 0.
4106:
1.222 foxr 4107: my $contents = &get_auth_type($domain, $user);
1.220 foxr 4108: my ($howpwd, $contentpwd) = split(/:/, $contents);
4109:
4110: my $null = pack("C",0); # Used by kerberos auth types.
4111:
4112: if ($howpwd ne 'nouser') {
4113:
4114: if($howpwd eq "internal") { # Encrypted is in local password file.
4115: $validated = (crypt($password, $contentpwd) eq $contentpwd);
4116: }
4117: elsif ($howpwd eq "unix") { # User is a normal unix user.
4118: $contentpwd = (getpwnam($user))[1];
4119: if($contentpwd) {
4120: if($contentpwd eq 'x') { # Shadow password file...
4121: my $pwauth_path = "/usr/local/sbin/pwauth";
4122: open PWAUTH, "|$pwauth_path" or
4123: die "Cannot invoke authentication";
4124: print PWAUTH "$user\n$password\n";
4125: close PWAUTH;
4126: $validated = ! $?;
4127:
4128: } else { # Passwords in /etc/passwd.
4129: $validated = (crypt($password,
4130: $contentpwd) eq $contentpwd);
4131: }
4132: } else {
4133: $validated = 0;
4134: }
4135: }
4136: elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
4137: if(! ($password =~ /$null/) ) {
4138: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
4139: "",
4140: $contentpwd,,
4141: 'krbtgt',
4142: $contentpwd,
4143: 1,
4144: $password);
4145: if(!$k4error) {
4146: $validated = 1;
1.224 foxr 4147: } else {
1.220 foxr 4148: $validated = 0;
4149: &logthis('krb4: '.$user.', '.$contentpwd.', '.
4150: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
4151: }
1.224 foxr 4152: } else {
1.220 foxr 4153: $validated = 0; # Password has a match with null.
4154: }
1.224 foxr 4155: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220 foxr 4156: if(!($password =~ /$null/)) { # Null password not allowed.
4157: my $krbclient = &Authen::Krb5::parse_name($user.'@'
4158: .$contentpwd);
4159: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
4160: my $krbserver = &Authen::Krb5::parse_name($krbservice);
4161: my $credentials= &Authen::Krb5::cc_default();
4162: $credentials->initialize($krbclient);
4163: my $krbreturn = &Authen::KRb5::get_in_tkt_with_password($krbclient,
4164: $krbserver,
4165: $password,
4166: $credentials);
4167: $validated = ($krbreturn == 1);
1.224 foxr 4168: } else {
1.220 foxr 4169: $validated = 0;
4170: }
1.224 foxr 4171: } elsif ($howpwd eq "localauth") {
1.220 foxr 4172: # Authenticate via installation specific authentcation method:
4173: $validated = &localauth::localauth($user,
4174: $password,
4175: $contentpwd);
1.224 foxr 4176: } else { # Unrecognized auth is also bad.
1.220 foxr 4177: $validated = 0;
4178: }
4179: } else {
4180: $validated = 0;
4181: }
4182: #
4183: # $validated has the correct stat of the authentication:
4184: #
4185:
4186: unless ($validated != -3.14159) {
4187: die "ValidateUser - failed to set the value of validated";
4188: }
4189: return $validated;
4190: }
4191:
4192:
1.84 albertel 4193: sub addline {
4194: my ($fname,$hostid,$ip,$newline)=@_;
4195: my $contents;
4196: my $found=0;
4197: my $expr='^'.$hostid.':'.$ip.':';
4198: $expr =~ s/\./\\\./g;
1.134 albertel 4199: my $sh;
1.84 albertel 4200: if ($sh=IO::File->new("$fname.subscription")) {
4201: while (my $subline=<$sh>) {
4202: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
4203: }
4204: $sh->close();
4205: }
4206: $sh=IO::File->new(">$fname.subscription");
4207: if ($contents) { print $sh $contents; }
4208: if ($newline) { print $sh $newline; }
4209: $sh->close();
4210: return $found;
1.86 www 4211: }
4212:
4213: sub getchat {
1.122 www 4214: my ($cdom,$cname,$udom,$uname)=@_;
1.87 www 4215: my %hash;
4216: my $proname=&propath($cdom,$cname);
4217: my @entries=();
1.88 albertel 4218: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
4219: &GDBM_READER(),0640)) {
4220: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
4221: untie %hash;
1.123 www 4222: }
1.124 www 4223: my @participants=();
1.134 albertel 4224: my $cutoff=time-60;
1.123 www 4225: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124 www 4226: &GDBM_WRCREAT(),0640)) {
4227: $hash{$uname.':'.$udom}=time;
1.123 www 4228: foreach (sort keys %hash) {
4229: if ($hash{$_}>$cutoff) {
1.124 www 4230: $participants[$#participants+1]='active_participant:'.$_;
1.123 www 4231: }
4232: }
4233: untie %hash;
1.86 www 4234: }
1.124 www 4235: return (@participants,@entries);
1.86 www 4236: }
4237:
4238: sub chatadd {
1.88 albertel 4239: my ($cdom,$cname,$newchat)=@_;
4240: my %hash;
4241: my $proname=&propath($cdom,$cname);
4242: my @entries=();
1.142 www 4243: my $time=time;
1.88 albertel 4244: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
4245: &GDBM_WRCREAT(),0640)) {
4246: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
4247: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
4248: my ($thentime,$idnum)=split(/\_/,$lastid);
4249: my $newid=$time.'_000000';
4250: if ($thentime==$time) {
4251: $idnum=~s/^0+//;
4252: $idnum++;
4253: $idnum=substr('000000'.$idnum,-6,6);
4254: $newid=$time.'_'.$idnum;
4255: }
4256: $hash{$newid}=$newchat;
4257: my $expired=$time-3600;
4258: foreach (keys %hash) {
4259: my ($thistime)=($_=~/(\d+)\_/);
4260: if ($thistime<$expired) {
1.89 www 4261: delete $hash{$_};
1.88 albertel 4262: }
4263: }
4264: untie %hash;
1.142 www 4265: }
4266: {
4267: my $hfh;
4268: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
4269: print $hfh "$time:".&unescape($newchat)."\n";
4270: }
1.86 www 4271: }
1.84 albertel 4272: }
4273:
4274: sub unsub {
4275: my ($fname,$clientip)=@_;
4276: my $result;
1.188 foxr 4277: my $unsubs = 0; # Number of successful unsubscribes:
4278:
4279:
4280: # An old way subscriptions were handled was to have a
4281: # subscription marker file:
4282:
4283: Debug("Attempting unlink of $fname.$clientname");
1.161 foxr 4284: if (unlink("$fname.$clientname")) {
1.188 foxr 4285: $unsubs++; # Successful unsub via marker file.
4286: }
4287:
4288: # The more modern way to do it is to have a subscription list
4289: # file:
4290:
1.84 albertel 4291: if (-e "$fname.subscription") {
1.161 foxr 4292: my $found=&addline($fname,$clientname,$clientip,'');
1.188 foxr 4293: if ($found) {
4294: $unsubs++;
4295: }
4296: }
4297:
4298: # If either or both of these mechanisms succeeded in unsubscribing a
4299: # resource we can return ok:
4300:
4301: if($unsubs) {
4302: $result = "ok\n";
1.84 albertel 4303: } else {
1.188 foxr 4304: $result = "not_subscribed\n";
1.84 albertel 4305: }
1.188 foxr 4306:
1.84 albertel 4307: return $result;
4308: }
4309:
1.101 www 4310: sub currentversion {
4311: my $fname=shift;
4312: my $version=-1;
4313: my $ulsdir='';
4314: if ($fname=~/^(.+)\/[^\/]+$/) {
4315: $ulsdir=$1;
4316: }
1.114 albertel 4317: my ($fnamere1,$fnamere2);
4318: # remove version if already specified
1.101 www 4319: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 4320: # get the bits that go before and after the version number
4321: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
4322: $fnamere1=$1;
4323: $fnamere2='.'.$2;
4324: }
1.101 www 4325: if (-e $fname) { $version=1; }
4326: if (-e $ulsdir) {
1.134 albertel 4327: if(-d $ulsdir) {
4328: if (opendir(LSDIR,$ulsdir)) {
4329: my $ulsfn;
4330: while ($ulsfn=readdir(LSDIR)) {
1.101 www 4331: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 4332: my $thisfile=$ulsdir.'/'.$ulsfn;
4333: unless (-l $thisfile) {
1.160 www 4334: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 4335: if ($1>$version) { $version=$1; }
4336: }
4337: }
4338: }
4339: closedir(LSDIR);
4340: $version++;
4341: }
4342: }
4343: }
4344: return $version;
1.101 www 4345: }
4346:
4347: sub thisversion {
4348: my $fname=shift;
4349: my $version=-1;
4350: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
4351: $version=$1;
4352: }
4353: return $version;
4354: }
4355:
1.84 albertel 4356: sub subscribe {
4357: my ($userinput,$clientip)=@_;
4358: my $result;
4359: my ($cmd,$fname)=split(/:/,$userinput);
4360: my $ownership=&ishome($fname);
4361: if ($ownership eq 'owner') {
1.101 www 4362: # explitly asking for the current version?
4363: unless (-e $fname) {
4364: my $currentversion=¤tversion($fname);
4365: if (&thisversion($fname)==$currentversion) {
4366: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
4367: my $root=$1;
4368: my $extension=$2;
4369: symlink($root.'.'.$extension,
4370: $root.'.'.$currentversion.'.'.$extension);
1.102 www 4371: unless ($extension=~/\.meta$/) {
4372: symlink($root.'.'.$extension.'.meta',
4373: $root.'.'.$currentversion.'.'.$extension.'.meta');
4374: }
1.101 www 4375: }
4376: }
4377: }
1.84 albertel 4378: if (-e $fname) {
4379: if (-d $fname) {
4380: $result="directory\n";
4381: } else {
1.161 foxr 4382: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 4383: my $now=time;
1.161 foxr 4384: my $found=&addline($fname,$clientname,$clientip,
4385: "$clientname:$clientip:$now\n");
1.84 albertel 4386: if ($found) { $result="$fname\n"; }
4387: # if they were subscribed to only meta data, delete that
4388: # subscription, when you subscribe to a file you also get
4389: # the metadata
4390: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
4391: $fname=~s/\/home\/httpd\/html\/res/raw/;
4392: $fname="http://$thisserver/".$fname;
4393: $result="$fname\n";
4394: }
4395: } else {
4396: $result="not_found\n";
4397: }
4398: } else {
4399: $result="rejected\n";
4400: }
4401: return $result;
4402: }
1.91 albertel 4403:
4404: sub make_passwd_file {
1.98 foxr 4405: my ($uname, $umode,$npass,$passfilename)=@_;
1.91 albertel 4406: my $result="ok\n";
4407: if ($umode eq 'krb4' or $umode eq 'krb5') {
4408: {
4409: my $pf = IO::File->new(">$passfilename");
4410: print $pf "$umode:$npass\n";
4411: }
4412: } elsif ($umode eq 'internal') {
4413: my $salt=time;
4414: $salt=substr($salt,6,2);
4415: my $ncpass=crypt($npass,$salt);
4416: {
4417: &Debug("Creating internal auth");
4418: my $pf = IO::File->new(">$passfilename");
4419: print $pf "internal:$ncpass\n";
4420: }
4421: } elsif ($umode eq 'localauth') {
4422: {
4423: my $pf = IO::File->new(">$passfilename");
4424: print $pf "localauth:$npass\n";
4425: }
4426: } elsif ($umode eq 'unix') {
4427: {
1.186 foxr 4428: #
4429: # Don't allow the creation of privileged accounts!!! that would
4430: # be real bad!!!
4431: #
4432: my $uid = getpwnam($uname);
4433: if((defined $uid) && ($uid == 0)) {
4434: &logthis(">>>Attempted to create privilged account blocked");
4435: return "no_priv_account_error\n";
4436: }
4437:
1.223 foxr 4438: my $execpath ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224 foxr 4439:
4440: my $lc_error_file = $execdir."/tmp/lcuseradd".$$.".status";
1.91 albertel 4441: {
4442: &Debug("Executing external: ".$execpath);
1.98 foxr 4443: &Debug("user = ".$uname.", Password =". $npass);
1.132 matthew 4444: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91 albertel 4445: print $se "$uname\n";
4446: print $se "$npass\n";
4447: print $se "$npass\n";
1.223 foxr 4448: print $se "$lc_error_file\n"; # Status -> unique file.
1.97 foxr 4449: }
1.223 foxr 4450: my $error = IO::File->new("< $lc_error_file");
4451: my $useraddok = <$error>;
4452: $error->close;
4453: unlink($lc_error_file);
4454:
4455: chomp $useraddok;
4456:
1.97 foxr 4457: if($useraddok > 0) {
1.223 foxr 4458: my $error_text = &lcuseraddstrerror($useraddok);
4459: &logthis("Failed lcuseradd: $error_text");
4460: $result = "lcuseradd_failed:$error_text\n";
1.224 foxr 4461: } else {
1.223 foxr 4462: my $pf = IO::File->new(">$passfilename");
4463: print $pf "unix:\n";
1.91 albertel 4464: }
4465: }
4466: } elsif ($umode eq 'none') {
4467: {
1.223 foxr 4468: my $pf = IO::File->new("> $passfilename");
1.91 albertel 4469: print $pf "none:\n";
4470: }
4471: } else {
4472: $result="auth_mode_error\n";
4473: }
4474: return $result;
1.121 albertel 4475: }
4476:
4477: sub sethost {
4478: my ($remotereq) = @_;
4479: my (undef,$hostid)=split(/:/,$remotereq);
4480: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
4481: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200 matthew 4482: $currenthostid =$hostid;
1.121 albertel 4483: $currentdomainid=$hostdom{$hostid};
4484: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
4485: } else {
4486: &logthis("Requested host id $hostid not an alias of ".
4487: $perlvar{'lonHostID'}." refusing connection");
4488: return 'unable_to_set';
4489: }
4490: return 'ok';
4491: }
4492:
4493: sub version {
4494: my ($userinput)=@_;
4495: $remoteVERSION=(split(/:/,$userinput))[1];
4496: return "version:$VERSION";
1.127 albertel 4497: }
1.178 foxr 4498:
1.128 albertel 4499: #There is a copy of this in lonnet.pm
1.127 albertel 4500: sub userload {
4501: my $numusers=0;
4502: {
4503: opendir(LONIDS,$perlvar{'lonIDsDir'});
4504: my $filename;
4505: my $curtime=time;
4506: while ($filename=readdir(LONIDS)) {
4507: if ($filename eq '.' || $filename eq '..') {next;}
1.138 albertel 4508: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159 albertel 4509: if ($curtime-$mtime < 1800) { $numusers++; }
1.127 albertel 4510: }
4511: closedir(LONIDS);
4512: }
4513: my $userloadpercent=0;
4514: my $maxuserload=$perlvar{'lonUserLoadLim'};
4515: if ($maxuserload) {
1.129 albertel 4516: $userloadpercent=100*$numusers/$maxuserload;
1.127 albertel 4517: }
1.130 albertel 4518: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127 albertel 4519: return $userloadpercent;
1.91 albertel 4520: }
4521:
1.205 raeburn 4522: # Routines for serializing arrays and hashes (copies from lonnet)
4523:
4524: sub array2str {
4525: my (@array) = @_;
4526: my $result=&arrayref2str(\@array);
4527: $result=~s/^__ARRAY_REF__//;
4528: $result=~s/__END_ARRAY_REF__$//;
4529: return $result;
4530: }
4531:
4532: sub arrayref2str {
4533: my ($arrayref) = @_;
4534: my $result='__ARRAY_REF__';
4535: foreach my $elem (@$arrayref) {
4536: if(ref($elem) eq 'ARRAY') {
4537: $result.=&arrayref2str($elem).'&';
4538: } elsif(ref($elem) eq 'HASH') {
4539: $result.=&hashref2str($elem).'&';
4540: } elsif(ref($elem)) {
4541: #print("Got a ref of ".(ref($elem))." skipping.");
4542: } else {
4543: $result.=&escape($elem).'&';
4544: }
4545: }
4546: $result=~s/\&$//;
4547: $result .= '__END_ARRAY_REF__';
4548: return $result;
4549: }
4550:
4551: sub hash2str {
4552: my (%hash) = @_;
4553: my $result=&hashref2str(\%hash);
4554: $result=~s/^__HASH_REF__//;
4555: $result=~s/__END_HASH_REF__$//;
4556: return $result;
4557: }
4558:
4559: sub hashref2str {
4560: my ($hashref)=@_;
4561: my $result='__HASH_REF__';
4562: foreach (sort(keys(%$hashref))) {
4563: if (ref($_) eq 'ARRAY') {
4564: $result.=&arrayref2str($_).'=';
4565: } elsif (ref($_) eq 'HASH') {
4566: $result.=&hashref2str($_).'=';
4567: } elsif (ref($_)) {
4568: $result.='=';
4569: #print("Got a ref of ".(ref($_))." skipping.");
4570: } else {
4571: if ($_) {$result.=&escape($_).'=';} else { last; }
4572: }
4573:
4574: if(ref($hashref->{$_}) eq 'ARRAY') {
4575: $result.=&arrayref2str($hashref->{$_}).'&';
4576: } elsif(ref($hashref->{$_}) eq 'HASH') {
4577: $result.=&hashref2str($hashref->{$_}).'&';
4578: } elsif(ref($hashref->{$_})) {
4579: $result.='&';
4580: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
4581: } else {
4582: $result.=&escape($hashref->{$_}).'&';
4583: }
4584: }
4585: $result=~s/\&$//;
4586: $result .= '__END_HASH_REF__';
4587: return $result;
4588: }
1.200 matthew 4589:
1.61 harris41 4590: # ----------------------------------- POD (plain old documentation, CPAN style)
4591:
4592: =head1 NAME
4593:
4594: lond - "LON Daemon" Server (port "LOND" 5663)
4595:
4596: =head1 SYNOPSIS
4597:
1.74 harris41 4598: Usage: B<lond>
4599:
4600: Should only be run as user=www. This is a command-line script which
4601: is invoked by B<loncron>. There is no expectation that a typical user
4602: will manually start B<lond> from the command-line. (In other words,
4603: DO NOT START B<lond> YOURSELF.)
1.61 harris41 4604:
4605: =head1 DESCRIPTION
4606:
1.74 harris41 4607: There are two characteristics associated with the running of B<lond>,
4608: PROCESS MANAGEMENT (starting, stopping, handling child processes)
4609: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
4610: subscriptions, etc). These are described in two large
4611: sections below.
4612:
4613: B<PROCESS MANAGEMENT>
4614:
1.61 harris41 4615: Preforker - server who forks first. Runs as a daemon. HUPs.
4616: Uses IDEA encryption
4617:
1.74 harris41 4618: B<lond> forks off children processes that correspond to the other servers
4619: in the network. Management of these processes can be done at the
4620: parent process level or the child process level.
4621:
4622: B<logs/lond.log> is the location of log messages.
4623:
4624: The process management is now explained in terms of linux shell commands,
4625: subroutines internal to this code, and signal assignments:
4626:
4627: =over 4
4628:
4629: =item *
4630:
4631: PID is stored in B<logs/lond.pid>
4632:
4633: This is the process id number of the parent B<lond> process.
4634:
4635: =item *
4636:
4637: SIGTERM and SIGINT
4638:
4639: Parent signal assignment:
4640: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
4641:
4642: Child signal assignment:
4643: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
4644: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
4645: to restart a new child.)
4646:
4647: Command-line invocations:
4648: B<kill> B<-s> SIGTERM I<PID>
4649: B<kill> B<-s> SIGINT I<PID>
4650:
4651: Subroutine B<HUNTSMAN>:
4652: This is only invoked for the B<lond> parent I<PID>.
4653: This kills all the children, and then the parent.
4654: The B<lonc.pid> file is cleared.
4655:
4656: =item *
4657:
4658: SIGHUP
4659:
4660: Current bug:
4661: This signal can only be processed the first time
4662: on the parent process. Subsequent SIGHUP signals
4663: have no effect.
4664:
4665: Parent signal assignment:
4666: $SIG{HUP} = \&HUPSMAN;
4667:
4668: Child signal assignment:
4669: none (nothing happens)
4670:
4671: Command-line invocations:
4672: B<kill> B<-s> SIGHUP I<PID>
4673:
4674: Subroutine B<HUPSMAN>:
4675: This is only invoked for the B<lond> parent I<PID>,
4676: This kills all the children, and then the parent.
4677: The B<lond.pid> file is cleared.
4678:
4679: =item *
4680:
4681: SIGUSR1
4682:
4683: Parent signal assignment:
4684: $SIG{USR1} = \&USRMAN;
4685:
4686: Child signal assignment:
4687: $SIG{USR1}= \&logstatus;
4688:
4689: Command-line invocations:
4690: B<kill> B<-s> SIGUSR1 I<PID>
4691:
4692: Subroutine B<USRMAN>:
4693: When invoked for the B<lond> parent I<PID>,
4694: SIGUSR1 is sent to all the children, and the status of
4695: each connection is logged.
1.144 foxr 4696:
4697: =item *
4698:
4699: SIGUSR2
4700:
4701: Parent Signal assignment:
4702: $SIG{USR2} = \&UpdateHosts
4703:
4704: Child signal assignment:
4705: NONE
4706:
1.74 harris41 4707:
4708: =item *
4709:
4710: SIGCHLD
4711:
4712: Parent signal assignment:
4713: $SIG{CHLD} = \&REAPER;
4714:
4715: Child signal assignment:
4716: none
4717:
4718: Command-line invocations:
4719: B<kill> B<-s> SIGCHLD I<PID>
4720:
4721: Subroutine B<REAPER>:
4722: This is only invoked for the B<lond> parent I<PID>.
4723: Information pertaining to the child is removed.
4724: The socket port is cleaned up.
4725:
4726: =back
4727:
4728: B<SERVER-SIDE ACTIVITIES>
4729:
4730: Server-side information can be accepted in an encrypted or non-encrypted
4731: method.
4732:
4733: =over 4
4734:
4735: =item ping
4736:
4737: Query a client in the hosts.tab table; "Are you there?"
4738:
4739: =item pong
4740:
4741: Respond to a ping query.
4742:
4743: =item ekey
4744:
4745: Read in encrypted key, make cipher. Respond with a buildkey.
4746:
4747: =item load
4748:
4749: Respond with CPU load based on a computation upon /proc/loadavg.
4750:
4751: =item currentauth
4752:
4753: Reply with current authentication information (only over an
4754: encrypted channel).
4755:
4756: =item auth
4757:
4758: Only over an encrypted channel, reply as to whether a user's
4759: authentication information can be validated.
4760:
4761: =item passwd
4762:
4763: Allow for a password to be set.
4764:
4765: =item makeuser
4766:
4767: Make a user.
4768:
4769: =item passwd
4770:
4771: Allow for authentication mechanism and password to be changed.
4772:
4773: =item home
1.61 harris41 4774:
1.74 harris41 4775: Respond to a question "are you the home for a given user?"
4776:
4777: =item update
4778:
4779: Update contents of a subscribed resource.
4780:
4781: =item unsubscribe
4782:
4783: The server is unsubscribing from a resource.
4784:
4785: =item subscribe
4786:
4787: The server is subscribing to a resource.
4788:
4789: =item log
4790:
4791: Place in B<logs/lond.log>
4792:
4793: =item put
4794:
4795: stores hash in namespace
4796:
4797: =item rolesput
4798:
4799: put a role into a user's environment
4800:
4801: =item get
4802:
4803: returns hash with keys from array
4804: reference filled in from namespace
4805:
4806: =item eget
4807:
4808: returns hash with keys from array
4809: reference filled in from namesp (encrypts the return communication)
4810:
4811: =item rolesget
4812:
4813: get a role from a user's environment
4814:
4815: =item del
4816:
4817: deletes keys out of array from namespace
4818:
4819: =item keys
4820:
4821: returns namespace keys
4822:
4823: =item dump
4824:
4825: dumps the complete (or key matching regexp) namespace into a hash
4826:
4827: =item store
4828:
4829: stores hash permanently
4830: for this url; hashref needs to be given and should be a \%hashname; the
4831: remaining args aren't required and if they aren't passed or are '' they will
4832: be derived from the ENV
4833:
4834: =item restore
4835:
4836: returns a hash for a given url
4837:
4838: =item querysend
4839:
4840: Tells client about the lonsql process that has been launched in response
4841: to a sent query.
4842:
4843: =item queryreply
4844:
4845: Accept information from lonsql and make appropriate storage in temporary
4846: file space.
4847:
4848: =item idput
4849:
4850: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
4851: for each student, defined perhaps by the institutional Registrar.)
4852:
4853: =item idget
4854:
4855: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
4856: for each student, defined perhaps by the institutional Registrar.)
4857:
4858: =item tmpput
4859:
4860: Accept and store information in temporary space.
4861:
4862: =item tmpget
4863:
4864: Send along temporarily stored information.
4865:
4866: =item ls
4867:
4868: List part of a user's directory.
4869:
1.135 foxr 4870: =item pushtable
4871:
4872: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
4873: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
4874: must be restored manually in case of a problem with the new table file.
4875: pushtable requires that the request be encrypted and validated via
4876: ValidateManager. The form of the command is:
4877: enc:pushtable tablename <tablecontents> \n
4878: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
4879: cleartext newline.
4880:
1.74 harris41 4881: =item Hanging up (exit or init)
4882:
4883: What to do when a client tells the server that they (the client)
4884: are leaving the network.
4885:
4886: =item unknown command
4887:
4888: If B<lond> is sent an unknown command (not in the list above),
4889: it replys to the client "unknown_cmd".
1.135 foxr 4890:
1.74 harris41 4891:
4892: =item UNKNOWN CLIENT
4893:
4894: If the anti-spoofing algorithm cannot verify the client,
4895: the client is rejected (with a "refused" message sent
4896: to the client, and the connection is closed.
4897:
4898: =back
1.61 harris41 4899:
4900: =head1 PREREQUISITES
4901:
4902: IO::Socket
4903: IO::File
4904: Apache::File
4905: Symbol
4906: POSIX
4907: Crypt::IDEA
4908: LWP::UserAgent()
4909: GDBM_File
4910: Authen::Krb4
1.91 albertel 4911: Authen::Krb5
1.61 harris41 4912:
4913: =head1 COREQUISITES
4914:
4915: =head1 OSNAMES
4916:
4917: linux
4918:
4919: =head1 SCRIPT CATEGORIES
4920:
4921: Server/Process
4922:
4923: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>