Annotation of loncom/lond, revision 1.216
1.1 albertel 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60 www 4: #
1.216 ! foxr 5: # $Id: lond,v 1.215 2004/07/27 11:21:48 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.1 albertel 53:
1.204 albertel 54: my $DEBUG = 0; # Non zero to enable debug log entries.
1.77 foxr 55:
1.57 www 56: my $status='';
57: my $lastlog='';
58:
1.216 ! foxr 59: my $VERSION='$Revision: 1.215 $'; #' stupid emacs
1.121 albertel 60: my $remoteVERSION;
1.214 foxr 61: my $currenthostid="default";
1.115 albertel 62: my $currentdomainid;
1.134 albertel 63:
64: my $client;
1.200 matthew 65: my $clientip; # IP address of client.
66: my $clientdns; # DNS name of client.
67: my $clientname; # LonCAPA name of client.
1.140 foxr 68:
1.134 albertel 69: my $server;
1.200 matthew 70: my $thisserver; # DNS of us.
71:
72: my $keymode;
1.198 foxr 73:
1.207 foxr 74: my $cipher; # Cipher key negotiated with client
75: my $tmpsnum = 0; # Id of tmpputs.
76:
1.178 foxr 77: #
78: # Connection type is:
79: # client - All client actions are allowed
80: # manager - only management functions allowed.
81: # both - Both management and client actions are allowed
82: #
1.161 foxr 83:
1.178 foxr 84: my $ConnectionType;
1.161 foxr 85:
1.200 matthew 86: my %hostid; # ID's for hosts in cluster by ip.
87: my %hostdom; # LonCAPA domain for hosts in cluster.
88: my %hostip; # IPs for hosts in cluster.
89: my %hostdns; # ID's of hosts looked up by DNS name.
1.161 foxr 90:
1.178 foxr 91: my %managers; # Ip -> manager names
1.161 foxr 92:
1.178 foxr 93: my %perlvar; # Will have the apache conf defined perl vars.
1.134 albertel 94:
1.178 foxr 95: #
1.207 foxr 96: # The hash below is used for command dispatching, and is therefore keyed on the request keyword.
97: # Each element of the hash contains a reference to an array that contains:
98: # A reference to a sub that executes the request corresponding to the keyword.
99: # A flag that is true if the request must be encoded to be acceptable.
100: # A mask with bits as follows:
101: # CLIENT_OK - Set when the function is allowed by ordinary clients
102: # MANAGER_OK - Set when the function is allowed to manager clients.
103: #
104: my $CLIENT_OK = 1;
105: my $MANAGER_OK = 2;
106: my %Dispatcher;
107:
108:
109: #
1.178 foxr 110: # The array below are password error strings."
111: #
112: my $lastpwderror = 13; # Largest error number from lcpasswd.
113: my @passwderrors = ("ok",
114: "lcpasswd must be run as user 'www'",
115: "lcpasswd got incorrect number of arguments",
116: "lcpasswd did not get the right nubmer of input text lines",
117: "lcpasswd too many simultaneous pwd changes in progress",
118: "lcpasswd User does not exist.",
119: "lcpasswd Incorrect current passwd",
120: "lcpasswd Unable to su to root.",
121: "lcpasswd Cannot set new passwd.",
122: "lcpasswd Username has invalid characters",
123: "lcpasswd Invalid characters in password",
124: "11", "12",
125: "lcpasswd Password mismatch");
1.97 foxr 126:
127:
1.178 foxr 128: # The array below are lcuseradd error strings.:
1.97 foxr 129:
1.178 foxr 130: my $lastadderror = 13;
131: my @adderrors = ("ok",
132: "User ID mismatch, lcuseradd must run as user www",
133: "lcuseradd Incorrect number of command line parameters must be 3",
134: "lcuseradd Incorrect number of stdinput lines, must be 3",
135: "lcuseradd Too many other simultaneous pwd changes in progress",
136: "lcuseradd User does not exist",
137: "lcuseradd Unable to make www member of users's group",
138: "lcuseradd Unable to su to root",
139: "lcuseradd Unable to set password",
140: "lcuseradd Usrname has invalid characters",
141: "lcuseradd Password has an invalid character",
142: "lcuseradd User already exists",
143: "lcuseradd Could not add user.",
144: "lcuseradd Password mismatch");
1.97 foxr 145:
1.96 foxr 146:
1.207 foxr 147:
148: #
149: # Statistics that are maintained and dislayed in the status line.
150: #
1.212 foxr 151: my $Transactions = 0; # Number of attempted transactions.
152: my $Failures = 0; # Number of transcations failed.
1.207 foxr 153:
154: # ResetStatistics:
155: # Resets the statistics counters:
156: #
157: sub ResetStatistics {
158: $Transactions = 0;
159: $Failures = 0;
160: }
161:
162:
163:
1.200 matthew 164: #------------------------------------------------------------------------
165: #
166: # LocalConnection
167: # Completes the formation of a locally authenticated connection.
168: # This function will ensure that the 'remote' client is really the
169: # local host. If not, the connection is closed, and the function fails.
170: # If so, initcmd is parsed for the name of a file containing the
171: # IDEA session key. The fie is opened, read, deleted and the session
172: # key returned to the caller.
173: #
174: # Parameters:
175: # $Socket - Socket open on client.
176: # $initcmd - The full text of the init command.
177: #
178: # Implicit inputs:
179: # $clientdns - The DNS name of the remote client.
180: # $thisserver - Our DNS name.
181: #
182: # Returns:
183: # IDEA session key on success.
184: # undef on failure.
185: #
186: sub LocalConnection {
187: my ($Socket, $initcmd) = @_;
188: Debug("Attempting local connection: $initcmd client: $clientdns me: $thisserver");
189: if($clientdns ne $thisserver) {
190: &logthis('<font color="red"> LocalConnection rejecting non local: '
191: ."$clientdns ne $thisserver </font>");
192: close $Socket;
193: return undef;
194: }
195: else {
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;
326: }
327: else {
328: logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
329: &status("No challenge reqply");
330: return 0;
331: }
332:
333:
334: }
335:
1.96 foxr 336: #
1.140 foxr 337: # GetCertificate: Given a transaction that requires a certificate,
338: # this function will extract the certificate from the transaction
339: # request. Note that at this point, the only concept of a certificate
340: # is the hostname to which we are connected.
341: #
342: # Parameter:
343: # request - The request sent by our client (this parameterization may
344: # need to change when we really use a certificate granting
345: # authority.
346: #
347: sub GetCertificate {
348: my $request = shift;
349:
350: return $clientip;
351: }
1.161 foxr 352:
1.178 foxr 353: #
354: # Return true if client is a manager.
355: #
356: sub isManager {
357: return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
358: }
359: #
360: # Return tru if client can do client functions
361: #
362: sub isClient {
363: return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
364: }
1.161 foxr 365:
366:
1.156 foxr 367: #
368: # ReadManagerTable: Reads in the current manager table. For now this is
369: # done on each manager authentication because:
370: # - These authentications are not frequent
371: # - This allows dynamic changes to the manager table
372: # without the need to signal to the lond.
373: #
374:
375: sub ReadManagerTable {
376:
377: # Clean out the old table first..
378:
1.166 foxr 379: foreach my $key (keys %managers) {
380: delete $managers{$key};
381: }
382:
383: my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
384: if (!open (MANAGERS, $tablename)) {
385: logthis('<font color="red">No manager table. Nobody can manage!!</font>');
386: return;
387: }
388: while(my $host = <MANAGERS>) {
389: chomp($host);
390: if ($host =~ "^#") { # Comment line.
391: next;
392: }
393: if (!defined $hostip{$host}) { # This is a non cluster member
1.161 foxr 394: # The entry is of the form:
395: # cluname:hostname
396: # cluname - A 'cluster hostname' is needed in order to negotiate
397: # the host key.
398: # hostname- The dns name of the host.
399: #
1.166 foxr 400: my($cluname, $dnsname) = split(/:/, $host);
401:
402: my $ip = gethostbyname($dnsname);
403: if(defined($ip)) { # bad names don't deserve entry.
404: my $hostip = inet_ntoa($ip);
405: $managers{$hostip} = $cluname;
406: logthis('<font color="green"> registering manager '.
407: "$dnsname as $cluname with $hostip </font>\n");
408: }
409: } else {
410: logthis('<font color="green"> existing host'." $host</font>\n");
411: $managers{$hostip{$host}} = $host; # Use info from cluster tab if clumemeber
412: }
413: }
1.156 foxr 414: }
1.140 foxr 415:
416: #
417: # ValidManager: Determines if a given certificate represents a valid manager.
418: # in this primitive implementation, the 'certificate' is
419: # just the connecting loncapa client name. This is checked
420: # against a valid client list in the configuration.
421: #
422: #
423: sub ValidManager {
424: my $certificate = shift;
425:
1.163 foxr 426: return isManager;
1.140 foxr 427: }
428: #
1.143 foxr 429: # CopyFile: Called as part of the process of installing a
430: # new configuration file. This function copies an existing
431: # file to a backup file.
432: # Parameters:
433: # oldfile - Name of the file to backup.
434: # newfile - Name of the backup file.
435: # Return:
436: # 0 - Failure (errno has failure reason).
437: # 1 - Success.
438: #
439: sub CopyFile {
1.192 foxr 440:
441: my ($oldfile, $newfile) = @_;
1.143 foxr 442:
443: # The file must exist:
444:
445: if(-e $oldfile) {
446:
447: # Read the old file.
448:
449: my $oldfh = IO::File->new("< $oldfile");
450: if(!$oldfh) {
451: return 0;
452: }
453: my @contents = <$oldfh>; # Suck in the entire file.
454:
455: # write the backup file:
456:
457: my $newfh = IO::File->new("> $newfile");
458: if(!(defined $newfh)){
459: return 0;
460: }
461: my $lines = scalar @contents;
462: for (my $i =0; $i < $lines; $i++) {
463: print $newfh ($contents[$i]);
464: }
465:
466: $oldfh->close;
467: $newfh->close;
468:
469: chmod(0660, $newfile);
470:
471: return 1;
472:
473: } else {
474: return 0;
475: }
476: }
1.157 foxr 477: #
478: # Host files are passed out with externally visible host IPs.
479: # If, for example, we are behind a fire-wall or NAT host, our
480: # internally visible IP may be different than the externally
481: # visible IP. Therefore, we always adjust the contents of the
482: # host file so that the entry for ME is the IP that we believe
483: # we have. At present, this is defined as the entry that
484: # DNS has for us. If by some chance we are not able to get a
485: # DNS translation for us, then we assume that the host.tab file
486: # is correct.
487: # BUGBUGBUG - in the future, we really should see if we can
488: # easily query the interface(s) instead.
489: # Parameter(s):
490: # contents - The contents of the host.tab to check.
491: # Returns:
492: # newcontents - The adjusted contents.
493: #
494: #
495: sub AdjustHostContents {
496: my $contents = shift;
497: my $adjusted;
498: my $me = $perlvar{'lonHostID'};
499:
1.166 foxr 500: foreach my $line (split(/\n/,$contents)) {
1.157 foxr 501: if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
502: chomp($line);
503: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
504: if ($id eq $me) {
1.166 foxr 505: my $ip = gethostbyname($name);
506: my $ipnew = inet_ntoa($ip);
507: $ip = $ipnew;
1.157 foxr 508: # Reconstruct the host line and append to adjusted:
509:
1.166 foxr 510: my $newline = "$id:$domain:$role:$name:$ip";
511: if($maxcon ne "") { # Not all hosts have loncnew tuning params
512: $newline .= ":$maxcon:$idleto:$mincon";
513: }
514: $adjusted .= $newline."\n";
1.157 foxr 515:
1.166 foxr 516: } else { # Not me, pass unmodified.
517: $adjusted .= $line."\n";
518: }
1.157 foxr 519: } else { # Blank or comment never re-written.
520: $adjusted .= $line."\n"; # Pass blanks and comments as is.
521: }
1.166 foxr 522: }
523: return $adjusted;
1.157 foxr 524: }
1.143 foxr 525: #
526: # InstallFile: Called to install an administrative file:
527: # - The file is created with <name>.tmp
528: # - The <name>.tmp file is then mv'd to <name>
529: # This lugubrious procedure is done to ensure that we are never without
530: # a valid, even if dated, version of the file regardless of who crashes
531: # and when the crash occurs.
532: #
533: # Parameters:
534: # Name of the file
535: # File Contents.
536: # Return:
537: # nonzero - success.
538: # 0 - failure and $! has an errno.
539: #
540: sub InstallFile {
1.192 foxr 541:
542: my ($Filename, $Contents) = @_;
1.143 foxr 543: my $TempFile = $Filename.".tmp";
544:
545: # Open the file for write:
546:
547: my $fh = IO::File->new("> $TempFile"); # Write to temp.
548: if(!(defined $fh)) {
549: &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
550: return 0;
551: }
552: # write the contents of the file:
553:
554: print $fh ($Contents);
555: $fh->close; # In case we ever have a filesystem w. locking
556:
557: chmod(0660, $TempFile);
558:
559: # Now we can move install the file in position.
560:
561: move($TempFile, $Filename);
562:
563: return 1;
564: }
1.200 matthew 565:
566:
1.169 foxr 567: #
568: # ConfigFileFromSelector: converts a configuration file selector
569: # (one of host or domain at this point) into a
570: # configuration file pathname.
571: #
572: # Parameters:
573: # selector - Configuration file selector.
574: # Returns:
575: # Full path to the file or undef if the selector is invalid.
576: #
577: sub ConfigFileFromSelector {
578: my $selector = shift;
579: my $tablefile;
580:
581: my $tabledir = $perlvar{'lonTabDir'}.'/';
582: if ($selector eq "hosts") {
583: $tablefile = $tabledir."hosts.tab";
584: } elsif ($selector eq "domain") {
585: $tablefile = $tabledir."domain.tab";
586: } else {
587: return undef;
588: }
589: return $tablefile;
1.143 foxr 590:
1.169 foxr 591: }
1.143 foxr 592: #
1.141 foxr 593: # PushFile: Called to do an administrative push of a file.
594: # - Ensure the file being pushed is one we support.
595: # - Backup the old file to <filename.saved>
596: # - Separate the contents of the new file out from the
597: # rest of the request.
598: # - Write the new file.
599: # Parameter:
600: # Request - The entire user request. This consists of a : separated
601: # string pushfile:tablename:contents.
602: # NOTE: The contents may have :'s in it as well making things a bit
603: # more interesting... but not much.
604: # Returns:
605: # String to send to client ("ok" or "refused" if bad file).
606: #
607: sub PushFile {
608: my $request = shift;
609: my ($command, $filename, $contents) = split(":", $request, 3);
610:
611: # At this point in time, pushes for only the following tables are
612: # supported:
613: # hosts.tab ($filename eq host).
614: # domain.tab ($filename eq domain).
615: # Construct the destination filename or reject the request.
616: #
617: # lonManage is supposed to ensure this, however this session could be
618: # part of some elaborate spoof that managed somehow to authenticate.
619: #
620:
1.169 foxr 621:
622: my $tablefile = ConfigFileFromSelector($filename);
623: if(! (defined $tablefile)) {
1.141 foxr 624: return "refused";
625: }
626: #
627: # >copy< the old table to the backup table
628: # don't rename in case system crashes/reboots etc. in the time
629: # window between a rename and write.
630: #
631: my $backupfile = $tablefile;
632: $backupfile =~ s/\.tab$/.old/;
1.143 foxr 633: if(!CopyFile($tablefile, $backupfile)) {
634: &logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
635: return "error:$!";
636: }
1.141 foxr 637: &logthis('<font color="green"> Pushfile: backed up '
638: .$tablefile." to $backupfile</font>");
639:
1.157 foxr 640: # If the file being pushed is the host file, we adjust the entry for ourself so that the
641: # IP will be our current IP as looked up in dns. Note this is only 99% good as it's possible
642: # to conceive of conditions where we don't have a DNS entry locally. This is possible in a
643: # network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
644: # that possibilty.
645:
646: if($filename eq "host") {
647: $contents = AdjustHostContents($contents);
648: }
649:
1.141 foxr 650: # Install the new file:
651:
1.143 foxr 652: if(!InstallFile($tablefile, $contents)) {
653: &logthis('<font color="red"> Pushfile: unable to install '
1.145 foxr 654: .$tablefile." $! </font>");
1.143 foxr 655: return "error:$!";
656: }
657: else {
658: &logthis('<font color="green"> Installed new '.$tablefile
659: ."</font>");
660:
661: }
662:
1.141 foxr 663:
664: # Indicate success:
665:
666: return "ok";
667:
668: }
1.145 foxr 669:
670: #
671: # Called to re-init either lonc or lond.
672: #
673: # Parameters:
674: # request - The full request by the client. This is of the form
675: # reinit:<process>
676: # where <process> is allowed to be either of
677: # lonc or lond
678: #
679: # Returns:
680: # The string to be sent back to the client either:
681: # ok - Everything worked just fine.
682: # error:why - There was a failure and why describes the reason.
683: #
684: #
685: sub ReinitProcess {
686: my $request = shift;
687:
1.146 foxr 688:
689: # separate the request (reinit) from the process identifier and
690: # validate it producing the name of the .pid file for the process.
691: #
692: #
693: my ($junk, $process) = split(":", $request);
1.147 foxr 694: my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146 foxr 695: if($process eq 'lonc') {
696: $processpidfile = $processpidfile."lonc.pid";
1.147 foxr 697: if (!open(PIDFILE, "< $processpidfile")) {
698: return "error:Open failed for $processpidfile";
699: }
700: my $loncpid = <PIDFILE>;
701: close(PIDFILE);
702: logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
703: ."</font>");
704: kill("USR2", $loncpid);
1.146 foxr 705: } elsif ($process eq 'lond') {
1.147 foxr 706: logthis('<font color="red"> Reinitializing self (lond) </font>');
707: &UpdateHosts; # Lond is us!!
1.146 foxr 708: } else {
709: &logthis('<font color="yellow" Invalid reinit request for '.$process
710: ."</font>");
711: return "error:Invalid process identifier $process";
712: }
1.145 foxr 713: return 'ok';
714: }
1.168 foxr 715: # Validate a line in a configuration file edit script:
716: # Validation includes:
717: # - Ensuring the command is valid.
718: # - Ensuring the command has sufficient parameters
719: # Parameters:
720: # scriptline - A line to validate (\n has been stripped for what it's worth).
1.167 foxr 721: #
1.168 foxr 722: # Return:
723: # 0 - Invalid scriptline.
724: # 1 - Valid scriptline
725: # NOTE:
726: # Only the command syntax is checked, not the executability of the
727: # command.
728: #
729: sub isValidEditCommand {
730: my $scriptline = shift;
731:
732: # Line elements are pipe separated:
733:
734: my ($command, $key, $newline) = split(/\|/, $scriptline);
735: &logthis('<font color="green"> isValideditCommand checking: '.
736: "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
737:
738: if ($command eq "delete") {
739: #
740: # key with no newline.
741: #
742: if( ($key eq "") || ($newline ne "")) {
743: return 0; # Must have key but no newline.
744: } else {
745: return 1; # Valid syntax.
746: }
1.169 foxr 747: } elsif ($command eq "replace") {
1.168 foxr 748: #
749: # key and newline:
750: #
751: if (($key eq "") || ($newline eq "")) {
752: return 0;
753: } else {
754: return 1;
755: }
1.169 foxr 756: } elsif ($command eq "append") {
757: if (($key ne "") && ($newline eq "")) {
758: return 1;
759: } else {
760: return 0;
761: }
1.168 foxr 762: } else {
763: return 0; # Invalid command.
764: }
765: return 0; # Should not get here!!!
766: }
1.169 foxr 767: #
768: # ApplyEdit - Applies an edit command to a line in a configuration
769: # file. It is the caller's responsiblity to validate the
770: # edit line.
771: # Parameters:
772: # $directive - A single edit directive to apply.
773: # Edit directives are of the form:
774: # append|newline - Appends a new line to the file.
775: # replace|key|newline - Replaces the line with key value 'key'
776: # delete|key - Deletes the line with key value 'key'.
777: # $editor - A config file editor object that contains the
778: # file being edited.
779: #
780: sub ApplyEdit {
1.192 foxr 781:
782: my ($directive, $editor) = @_;
1.169 foxr 783:
784: # Break the directive down into its command and its parameters
785: # (at most two at this point. The meaning of the parameters, if in fact
786: # they exist depends on the command).
787:
788: my ($command, $p1, $p2) = split(/\|/, $directive);
789:
790: if($command eq "append") {
791: $editor->Append($p1); # p1 - key p2 null.
792: } elsif ($command eq "replace") {
793: $editor->ReplaceLine($p1, $p2); # p1 - key p2 = newline.
794: } elsif ($command eq "delete") {
795: $editor->DeleteLine($p1); # p1 - key p2 null.
796: } else { # Should not get here!!!
797: die "Invalid command given to ApplyEdit $command"
798: }
799: }
800: #
801: # AdjustOurHost:
802: # Adjusts a host file stored in a configuration file editor object
803: # for the true IP address of this host. This is necessary for hosts
804: # that live behind a firewall.
805: # Those hosts have a publicly distributed IP of the firewall, but
806: # internally must use their actual IP. We assume that a given
807: # host only has a single IP interface for now.
808: # Formal Parameters:
809: # editor - The configuration file editor to adjust. This
810: # editor is assumed to contain a hosts.tab file.
811: # Strategy:
812: # - Figure out our hostname.
813: # - Lookup the entry for this host.
814: # - Modify the line to contain our IP
815: # - Do a replace for this host.
816: sub AdjustOurHost {
817: my $editor = shift;
818:
819: # figure out who I am.
820:
821: my $myHostName = $perlvar{'lonHostID'}; # LonCAPA hostname.
822:
823: # Get my host file entry.
824:
825: my $ConfigLine = $editor->Find($myHostName);
826: if(! (defined $ConfigLine)) {
827: die "AdjustOurHost - no entry for me in hosts file $myHostName";
828: }
829: # figure out my IP:
830: # Use the config line to get my hostname.
831: # Use gethostbyname to translate that into an IP address.
832: #
833: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
834: my $BinaryIp = gethostbyname($name);
835: my $ip = inet_ntoa($ip);
836: #
837: # Reassemble the config line from the elements in the list.
838: # Note that if the loncnew items were not present before, they will
839: # be now even if they would be empty
840: #
841: my $newConfigLine = $id;
842: foreach my $item ($domain, $role, $name, $ip, $maxcon, $idleto, $mincon) {
843: $newConfigLine .= ":".$item;
844: }
845: # Replace the line:
846:
847: $editor->ReplaceLine($id, $newConfigLine);
848:
849: }
850: #
851: # ReplaceConfigFile:
852: # Replaces a configuration file with the contents of a
853: # configuration file editor object.
854: # This is done by:
855: # - Copying the target file to <filename>.old
856: # - Writing the new file to <filename>.tmp
857: # - Moving <filename.tmp> -> <filename>
858: # This laborious process ensures that the system is never without
859: # a configuration file that's at least valid (even if the contents
860: # may be dated).
861: # Parameters:
862: # filename - Name of the file to modify... this is a full path.
863: # editor - Editor containing the file.
864: #
865: sub ReplaceConfigFile {
1.192 foxr 866:
867: my ($filename, $editor) = @_;
1.168 foxr 868:
1.169 foxr 869: CopyFile ($filename, $filename.".old");
870:
871: my $contents = $editor->Get(); # Get the contents of the file.
872:
873: InstallFile($filename, $contents);
874: }
1.168 foxr 875: #
876: #
877: # Called to edit a configuration table file
1.167 foxr 878: # Parameters:
879: # request - The entire command/request sent by lonc or lonManage
880: # Return:
881: # The reply to send to the client.
1.168 foxr 882: #
1.167 foxr 883: sub EditFile {
884: my $request = shift;
885:
886: # Split the command into it's pieces: edit:filetype:script
887:
1.168 foxr 888: my ($request, $filetype, $script) = split(/:/, $request,3); # : in script
1.167 foxr 889:
890: # Check the pre-coditions for success:
891:
892: if($request != "edit") { # Something is amiss afoot alack.
893: return "error:edit request detected, but request != 'edit'\n";
894: }
895: if( ($filetype ne "hosts") &&
896: ($filetype ne "domain")) {
897: return "error:edit requested with invalid file specifier: $filetype \n";
898: }
899:
900: # Split the edit script and check it's validity.
1.168 foxr 901:
902: my @scriptlines = split(/\n/, $script); # one line per element.
903: my $linecount = scalar(@scriptlines);
904: for(my $i = 0; $i < $linecount; $i++) {
905: chomp($scriptlines[$i]);
906: if(!isValidEditCommand($scriptlines[$i])) {
907: return "error:edit with bad script line: '$scriptlines[$i]' \n";
908: }
909: }
1.145 foxr 910:
1.167 foxr 911: # Execute the edit operation.
1.169 foxr 912: # - Create a config file editor for the appropriate file and
913: # - execute each command in the script:
914: #
915: my $configfile = ConfigFileFromSelector($filetype);
916: if (!(defined $configfile)) {
917: return "refused\n";
918: }
919: my $editor = ConfigFileEdit->new($configfile);
1.167 foxr 920:
1.169 foxr 921: for (my $i = 0; $i < $linecount; $i++) {
922: ApplyEdit($scriptlines[$i], $editor);
923: }
924: # If the file is the host file, ensure that our host is
925: # adjusted to have our ip:
926: #
927: if($filetype eq "host") {
928: AdjustOurHost($editor);
929: }
930: # Finally replace the current file with our file.
931: #
932: ReplaceConfigFile($configfile, $editor);
1.167 foxr 933:
934: return "ok\n";
935: }
1.207 foxr 936:
937: #---------------------------------------------------------------
938: #
939: # Manipulation of hash based databases (factoring out common code
940: # for later use as we refactor.
941: #
942: # Ties a domain level resource file to a hash.
943: # If requested a history entry is created in the associated hist file.
944: #
945: # Parameters:
946: # domain - Name of the domain in which the resource file lives.
947: # namespace - Name of the hash within that domain.
948: # how - How to tie the hash (e.g. GDBM_WRCREAT()).
949: # loghead - Optional parameter, if present a log entry is created
950: # in the associated history file and this is the first part
951: # of that entry.
952: # logtail - Goes along with loghead, The actual logentry is of the
953: # form $loghead:<timestamp>:logtail.
954: # Returns:
955: # Reference to a hash bound to the db file or alternatively undef
956: # if the tie failed.
957: #
1.209 albertel 958: sub tie_domain_hash {
1.210 albertel 959: my ($domain,$namespace,$how,$loghead,$logtail) = @_;
1.207 foxr 960:
961: # Filter out any whitespace in the domain name:
962:
963: $domain =~ s/\W//g;
964:
965: # We have enough to go on to tie the hash:
966:
967: my $user_top_dir = $perlvar{'lonUsersDir'};
968: my $domain_dir = $user_top_dir."/$domain";
969: my $resource_file = $domain_dir."/$namespace.db";
970: my %hash;
971: if(tie(%hash, 'GDBM_File', $resource_file, $how, 0640)) {
1.211 albertel 972: if (defined($loghead)) { # Need to log the operation.
1.210 albertel 973: my $logFh = IO::File->new(">>$domain_dir/$namespace.hist");
1.207 foxr 974: if($logFh) {
975: my $timestamp = time;
976: print $logFh "$loghead:$timestamp:$logtail\n";
977: }
1.210 albertel 978: $logFh->close;
1.207 foxr 979: }
980: return \%hash; # Return the tied hash.
1.210 albertel 981: } else {
1.207 foxr 982: return undef; # Tie failed.
983: }
984: }
985:
986: #
987: # Ties a user's resource file to a hash.
988: # If necessary, an appropriate history
989: # log file entry is made as well.
990: # This sub factors out common code from the subs that manipulate
991: # the various gdbm files that keep keyword value pairs.
992: # Parameters:
993: # domain - Name of the domain the user is in.
994: # user - Name of the 'current user'.
995: # namespace - Namespace representing the file to tie.
996: # how - What the tie is done to (e.g. GDBM_WRCREAT().
997: # loghead - Optional first part of log entry if there may be a
998: # history file.
999: # what - Optional tail of log entry if there may be a history
1000: # file.
1001: # Returns:
1002: # hash to which the database is tied. It's up to the caller to untie.
1003: # undef if the has could not be tied.
1004: #
1.210 albertel 1005: sub tie_user_hash {
1006: my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
1.207 foxr 1007:
1008: $namespace=~s/\//\_/g; # / -> _
1009: $namespace=~s/\W//g; # whitespace eliminated.
1010: my $proname = propath($domain, $user);
1011:
1012: # Tie the database.
1013:
1014: my %hash;
1015: if(tie(%hash, 'GDBM_File', "$proname/$namespace.db",
1016: $how, 0640)) {
1.209 albertel 1017: # If this is a namespace for which a history is kept,
1018: # make the history log entry:
1.211 albertel 1019: if (($namespace =~/^nohist\_/) && (defined($loghead))) {
1.209 albertel 1020: my $args = scalar @_;
1021: Debug(" Opening history: $namespace $args");
1022: my $hfh = IO::File->new(">>$proname/$namespace.hist");
1023: if($hfh) {
1024: my $now = time;
1025: print $hfh "$loghead:$now:$what\n";
1026: }
1.210 albertel 1027: $hfh->close;
1.209 albertel 1028: }
1.207 foxr 1029: return \%hash;
1.209 albertel 1030: } else {
1.207 foxr 1031: return undef;
1032: }
1033:
1034: }
1.214 foxr 1035:
1036: #--------------------- Request Handlers --------------------------------------------
1037: #
1.215 foxr 1038: # By convention each request handler registers itself prior to the sub
1039: # declaration:
1.214 foxr 1040: #
1041:
1.216 ! foxr 1042: #++
! 1043: #
1.214 foxr 1044: # Handles ping requests.
1045: # Parameters:
1046: # $cmd - the actual keyword that invoked us.
1047: # $tail - the tail of the request that invoked us.
1048: # $replyfd- File descriptor connected to the client
1049: # Implicit Inputs:
1050: # $currenthostid - Global variable that carries the name of the host we are
1051: # known as.
1052: # Returns:
1053: # 1 - Ok to continue processing.
1054: # 0 - Program should exit.
1055: # Side effects:
1056: # Reply information is sent to the client.
1057:
1058: sub ping_handler {
1059: my ($cmd, $tail, $client) = @_;
1060: Debug("$cmd $tail $client .. $currenthostid:");
1061:
1062: Reply( $client,"$currenthostid\n","$cmd:$tail");
1063:
1064: return 1;
1065: }
1066: ®ister_handler("ping", \&ping_handler, 0, 1, 1); # Ping unencoded, client or manager.
1067:
1.216 ! foxr 1068: #++
1.215 foxr 1069: #
1070: # Handles pong requests. Pong replies with our current host id, and
1071: # the results of a ping sent to us via our lonc.
1072: #
1073: # Parameters:
1074: # $cmd - the actual keyword that invoked us.
1075: # $tail - the tail of the request that invoked us.
1076: # $replyfd- File descriptor connected to the client
1077: # Implicit Inputs:
1078: # $currenthostid - Global variable that carries the name of the host we are
1079: # connected to.
1080: # Returns:
1081: # 1 - Ok to continue processing.
1082: # 0 - Program should exit.
1083: # Side effects:
1084: # Reply information is sent to the client.
1085:
1086: sub pong_handler {
1087: my ($cmd, $tail, $replyfd) = @_;
1088:
1089: my $reply=&reply("ping",$clientname);
1090: &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail");
1091: return 1;
1092: }
1093: ®ister_handler("pong", \&pong_handler, 0, 1, 1); # Pong unencoded, client or manager
1094:
1.216 ! foxr 1095: #++
! 1096: # Called to establish an encrypted session key with the remote client.
! 1097: # Note that with secure lond, in most cases this function is never
! 1098: # invoked. Instead, the secure session key is established either
! 1099: # via a local file that's locked down tight and only lives for a short
! 1100: # time, or via an ssl tunnel...and is generated from a bunch-o-random
! 1101: # bits from /dev/urandom, rather than the predictable pattern used by
! 1102: # by this sub. This sub is only used in the old-style insecure
! 1103: # key negotiation.
! 1104: # Parameters:
! 1105: # $cmd - the actual keyword that invoked us.
! 1106: # $tail - the tail of the request that invoked us.
! 1107: # $replyfd- File descriptor connected to the client
! 1108: # Implicit Inputs:
! 1109: # $currenthostid - Global variable that carries the name of the host
! 1110: # known as.
! 1111: # $clientname - Global variable that carries the name of the hsot we're connected to.
! 1112: # Returns:
! 1113: # 1 - Ok to continue processing.
! 1114: # 0 - Program should exit.
! 1115: # Implicit Outputs:
! 1116: # Reply information is sent to the client.
! 1117: # $cipher is set with a reference to a new IDEA encryption object.
! 1118: #
! 1119: sub establish_key_handler {
! 1120: my ($cmd, $tail, $replyfd) = @_;
! 1121:
! 1122: my $buildkey=time.$$.int(rand 100000);
! 1123: $buildkey=~tr/1-6/A-F/;
! 1124: $buildkey=int(rand 100000).$buildkey.int(rand 100000);
! 1125: my $key=$currenthostid.$clientname;
! 1126: $key=~tr/a-z/A-Z/;
! 1127: $key=~tr/G-P/0-9/;
! 1128: $key=~tr/Q-Z/0-9/;
! 1129: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
! 1130: $key=substr($key,0,32);
! 1131: my $cipherkey=pack("H32",$key);
! 1132: $cipher=new IDEA $cipherkey;
! 1133: &Reply($replyfd, "$buildkey\n", "$cmd:$tail");
! 1134:
! 1135: return 1;
! 1136:
! 1137: }
! 1138: ®ister_handler("ekey", \&establish_key_handler, 0, 1,1);
! 1139:
1.215 foxr 1140:
1.214 foxr 1141:
1.207 foxr 1142: #---------------------------------------------------------------
1143: #
1144: # Getting, decoding and dispatching requests:
1145: #
1146:
1147: #
1148: # Get a Request:
1149: # Gets a Request message from the client. The transaction
1150: # is defined as a 'line' of text. We remove the new line
1151: # from the text line.
1152: #
1.211 albertel 1153: sub get_request {
1.207 foxr 1154: my $input = <$client>;
1155: chomp($input);
1156:
1.212 foxr 1157: Debug("get_request: Request = $input\n");
1.207 foxr 1158:
1159: &status('Processing '.$clientname.':'.$input);
1160:
1161: return $input;
1162: }
1.212 foxr 1163: #---------------------------------------------------------------
1164: #
1165: # Process a request. This sub should shrink as each action
1166: # gets farmed out into a separat sub that is registered
1167: # with the dispatch hash.
1168: #
1169: # Parameters:
1170: # user_input - The request received from the client (lonc).
1171: # Returns:
1172: # true to keep processing, false if caller should exit.
1173: #
1174: sub process_request {
1175: my ($userinput) = @_; # Easier for now to break style than to
1176: # fix all the userinput -> user_input.
1177: my $wasenc = 0; # True if request was encrypted.
1178: # ------------------------------------------------------------ See if encrypted
1179: if ($userinput =~ /^enc/) {
1180: $userinput = decipher($userinput);
1181: $wasenc=1;
1182: if(!$userinput) { # Cipher not defined.
1183: &Failure($client, "error: Encrypted data without negotated key");
1184: return 0;
1185: }
1186: }
1187: Debug("process_request: $userinput\n");
1188:
1.213 foxr 1189: #
1190: # The 'correct way' to add a command to lond is now to
1191: # write a sub to execute it and Add it to the command dispatch
1192: # hash via a call to register_handler.. The comments to that
1193: # sub should give you enough to go on to show how to do this
1194: # along with the examples that are building up as this code
1195: # is getting refactored. Until all branches of the
1196: # if/elseif monster below have been factored out into
1197: # separate procesor subs, if the dispatch hash is missing
1198: # the command keyword, we will fall through to the remainder
1199: # of the if/else chain below in order to keep this thing in
1200: # working order throughout the transmogrification.
1201:
1202: my ($command, $tail) = split(/:/, $userinput, 2);
1203: chomp($command);
1204: chomp($tail);
1205: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
1.214 foxr 1206: $command =~ s/(\r)//; # And this too for parameterless commands.
1207: if(!$tail) {
1208: $tail =""; # defined but blank.
1209: }
1.213 foxr 1210:
1211: &Debug("Command received: $command, encoded = $wasenc");
1212:
1213: if(defined $Dispatcher{$command}) {
1214:
1215: my $dispatch_info = $Dispatcher{$command};
1216: my $handler = $$dispatch_info[0];
1217: my $need_encode = $$dispatch_info[1];
1218: my $client_types = $$dispatch_info[2];
1219: Debug("Matched dispatch hash: mustencode: $need_encode "
1220: ."ClientType $client_types");
1221:
1222: # Validate the request:
1223:
1224: my $ok = 1;
1225: my $requesterprivs = 0;
1226: if(&isClient()) {
1227: $requesterprivs |= $CLIENT_OK;
1228: }
1229: if(&isManager()) {
1230: $requesterprivs |= $MANAGER_OK;
1231: }
1232: if($need_encode && (!$wasenc)) {
1233: Debug("Must encode but wasn't: $need_encode $wasenc");
1234: $ok = 0;
1235: }
1236: if(($client_types & $requesterprivs) == 0) {
1237: Debug("Client not privileged to do this operation");
1238: $ok = 0;
1239: }
1240:
1241: if($ok) {
1242: Debug("Dispatching to handler $command $tail");
1243: my $keep_going = &$handler($command, $tail, $client);
1244: return $keep_going;
1245: } else {
1246: Debug("Refusing to dispatch because client did not match requirements");
1247: Failure($client, "refused\n", $userinput);
1248: return 1;
1249: }
1250:
1251: }
1252:
1.215 foxr 1253: #------------------- Commands not yet in spearate handlers. --------------
1254:
1.212 foxr 1255: # ------------------------------------------------------------------------ load
1.216 ! foxr 1256: if ($userinput =~ /^load/) { # client only
1.212 foxr 1257: if (isClient) {
1258: my $loadavg;
1259: {
1260: my $loadfile=IO::File->new('/proc/loadavg');
1261: $loadavg=<$loadfile>;
1262: }
1263: $loadavg =~ s/\s.*//g;
1264: my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
1265: print $client "$loadpercent\n";
1266: } else {
1267: Reply($client, "refused\n", $userinput);
1268:
1269: }
1270: # -------------------------------------------------------------------- userload
1271: } elsif ($userinput =~ /^userload/) { # client only
1272: if(isClient) {
1273: my $userloadpercent=&userload();
1274: print $client "$userloadpercent\n";
1275: } else {
1276: Reply($client, "refused\n", $userinput);
1277:
1278: }
1279: #
1280: # Transactions requiring encryption:
1281: #
1282: # ----------------------------------------------------------------- currentauth
1283: } elsif ($userinput =~ /^currentauth/) {
1284: if (($wasenc==1) && isClient) { # Encoded & client only.
1285: my ($cmd,$udom,$uname)=split(/:/,$userinput);
1286: my $result = GetAuthType($udom, $uname);
1287: if($result eq "nouser") {
1288: print $client "unknown_user\n";
1289: }
1290: else {
1291: print $client "$result\n";
1292: }
1293: } else {
1294: Reply($client, "refused\n", $userinput);
1295:
1296: }
1297: #--------------------------------------------------------------------- pushfile
1298: } elsif($userinput =~ /^pushfile/) { # encoded & manager.
1299: if(($wasenc == 1) && isManager) {
1300: my $cert = GetCertificate($userinput);
1301: if(ValidManager($cert)) {
1302: my $reply = PushFile($userinput);
1303: print $client "$reply\n";
1304: } else {
1305: print $client "refused\n";
1306: }
1307: } else {
1308: Reply($client, "refused\n", $userinput);
1309:
1310: }
1311: #--------------------------------------------------------------------- reinit
1312: } elsif($userinput =~ /^reinit/) { # Encoded and manager
1313: if (($wasenc == 1) && isManager) {
1314: my $cert = GetCertificate($userinput);
1315: if(ValidManager($cert)) {
1316: chomp($userinput);
1317: my $reply = ReinitProcess($userinput);
1318: print $client "$reply\n";
1319: } else {
1320: print $client "refused\n";
1321: }
1322: } else {
1323: Reply($client, "refused\n", $userinput);
1324: }
1325: #------------------------------------------------------------------------- edit
1326: } elsif ($userinput =~ /^edit/) { # encoded and manager:
1327: if(($wasenc ==1) && (isManager)) {
1328: my $cert = GetCertificate($userinput);
1329: if(ValidManager($cert)) {
1330: my($command, $filetype, $script) = split(/:/, $userinput);
1331: if (($filetype eq "hosts") || ($filetype eq "domain")) {
1332: if($script ne "") {
1333: Reply($client, EditFile($userinput));
1334: } else {
1335: Reply($client,"refused\n",$userinput);
1336: }
1337: } else {
1338: Reply($client,"refused\n",$userinput);
1339: }
1340: } else {
1341: Reply($client,"refused\n",$userinput);
1342: }
1343: } else {
1344: Reply($client,"refused\n",$userinput);
1345: }
1346: # ------------------------------------------------------------------------ auth
1347: } elsif ($userinput =~ /^auth/) { # Encoded and client only.
1348: if (($wasenc==1) && isClient) {
1349: my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
1350: chomp($upass);
1351: $upass=unescape($upass);
1352: my $proname=propath($udom,$uname);
1353: my $passfilename="$proname/passwd";
1354: if (-e $passfilename) {
1355: my $pf = IO::File->new($passfilename);
1356: my $realpasswd=<$pf>;
1357: chomp($realpasswd);
1358: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1359: my $pwdcorrect=0;
1360: if ($howpwd eq 'internal') {
1361: &Debug("Internal auth");
1362: $pwdcorrect=
1363: (crypt($upass,$contentpwd) eq $contentpwd);
1364: } elsif ($howpwd eq 'unix') {
1365: &Debug("Unix auth");
1366: if((getpwnam($uname))[1] eq "") { #no such user!
1367: $pwdcorrect = 0;
1368: } else {
1369: $contentpwd=(getpwnam($uname))[1];
1370: my $pwauth_path="/usr/local/sbin/pwauth";
1371: unless ($contentpwd eq 'x') {
1372: $pwdcorrect=
1373: (crypt($upass,$contentpwd) eq
1374: $contentpwd);
1375: }
1376:
1377: elsif (-e $pwauth_path) {
1378: open PWAUTH, "|$pwauth_path" or
1379: die "Cannot invoke authentication";
1380: print PWAUTH "$uname\n$upass\n";
1381: close PWAUTH;
1382: $pwdcorrect=!$?;
1383: }
1384: }
1385: } elsif ($howpwd eq 'krb4') {
1386: my $null=pack("C",0);
1387: unless ($upass=~/$null/) {
1388: my $krb4_error = &Authen::Krb4::get_pw_in_tkt
1389: ($uname,"",$contentpwd,'krbtgt',
1390: $contentpwd,1,$upass);
1391: if (!$krb4_error) {
1392: $pwdcorrect = 1;
1393: } else {
1394: $pwdcorrect=0;
1395: # log error if it is not a bad password
1396: if ($krb4_error != 62) {
1397: &logthis('krb4:'.$uname.','.
1398: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
1399: }
1400: }
1401: }
1402: } elsif ($howpwd eq 'krb5') {
1403: my $null=pack("C",0);
1404: unless ($upass=~/$null/) {
1405: my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
1406: my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
1407: my $krbserver=&Authen::Krb5::parse_name($krbservice);
1408: my $credentials=&Authen::Krb5::cc_default();
1409: $credentials->initialize($krbclient);
1410: my $krbreturn =
1411: &Authen::Krb5::get_in_tkt_with_password(
1412: $krbclient,$krbserver,$upass,$credentials);
1413: # unless ($krbreturn) {
1414: # &logthis("Krb5 Error: ".
1415: # &Authen::Krb5::error());
1416: # }
1417: $pwdcorrect = ($krbreturn == 1);
1418: } else { $pwdcorrect=0; }
1419: } elsif ($howpwd eq 'localauth') {
1420: $pwdcorrect=&localauth::localauth($uname,$upass,
1421: $contentpwd);
1422: }
1423: if ($pwdcorrect) {
1424: print $client "authorized\n";
1425: } else {
1426: print $client "non_authorized\n";
1427: }
1428: } else {
1429: print $client "unknown_user\n";
1430: }
1431: } else {
1432: Reply($client, "refused\n", $userinput);
1433:
1434: }
1435: # ---------------------------------------------------------------------- passwd
1436: } elsif ($userinput =~ /^passwd/) { # encoded and client
1437: if (($wasenc==1) && isClient) {
1438: my
1439: ($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
1440: chomp($npass);
1441: $upass=&unescape($upass);
1442: $npass=&unescape($npass);
1443: &Debug("Trying to change password for $uname");
1444: my $proname=propath($udom,$uname);
1445: my $passfilename="$proname/passwd";
1446: if (-e $passfilename) {
1447: my $realpasswd;
1448: { my $pf = IO::File->new($passfilename);
1449: $realpasswd=<$pf>; }
1450: chomp($realpasswd);
1451: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1452: if ($howpwd eq 'internal') {
1453: &Debug("internal auth");
1454: if (crypt($upass,$contentpwd) eq $contentpwd) {
1455: my $salt=time;
1456: $salt=substr($salt,6,2);
1457: my $ncpass=crypt($npass,$salt);
1458: {
1459: my $pf;
1460: if ($pf = IO::File->new(">$passfilename")) {
1461: print $pf "internal:$ncpass\n";
1462: &logthis("Result of password change for $uname: pwchange_success");
1463: print $client "ok\n";
1464: } else {
1465: &logthis("Unable to open $uname passwd to change password");
1466: print $client "non_authorized\n";
1467: }
1468: }
1469:
1470: } else {
1471: print $client "non_authorized\n";
1472: }
1473: } elsif ($howpwd eq 'unix') {
1474: # Unix means we have to access /etc/password
1475: # one way or another.
1476: # First: Make sure the current password is
1477: # correct
1478: &Debug("auth is unix");
1479: $contentpwd=(getpwnam($uname))[1];
1480: my $pwdcorrect = "0";
1481: my $pwauth_path="/usr/local/sbin/pwauth";
1482: unless ($contentpwd eq 'x') {
1483: $pwdcorrect=
1484: (crypt($upass,$contentpwd) eq $contentpwd);
1485: } elsif (-e $pwauth_path) {
1486: open PWAUTH, "|$pwauth_path" or
1487: die "Cannot invoke authentication";
1488: print PWAUTH "$uname\n$upass\n";
1489: close PWAUTH;
1490: &Debug("exited pwauth with $? ($uname,$upass) ");
1491: $pwdcorrect=($? == 0);
1492: }
1493: if ($pwdcorrect) {
1494: my $execdir=$perlvar{'lonDaemons'};
1495: &Debug("Opening lcpasswd pipeline");
1496: my $pf = IO::File->new("|$execdir/lcpasswd > $perlvar{'lonDaemons'}/logs/lcpasswd.log");
1497: print $pf "$uname\n$npass\n$npass\n";
1498: close $pf;
1499: my $err = $?;
1500: my $result = ($err>0 ? 'pwchange_failure'
1501: : 'ok');
1502: &logthis("Result of password change for $uname: ".
1503: &lcpasswdstrerror($?));
1504: print $client "$result\n";
1505: } else {
1506: print $client "non_authorized\n";
1507: }
1508: } else {
1509: print $client "auth_mode_error\n";
1510: }
1511: } else {
1512: print $client "unknown_user\n";
1513: }
1514: } else {
1515: Reply($client, "refused\n", $userinput);
1516:
1517: }
1518: # -------------------------------------------------------------------- makeuser
1519: } elsif ($userinput =~ /^makeuser/) { # encoded and client.
1520: &Debug("Make user received");
1521: my $oldumask=umask(0077);
1522: if (($wasenc==1) && isClient) {
1523: my
1524: ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
1525: &Debug("cmd =".$cmd." $udom =".$udom.
1526: " uname=".$uname);
1527: chomp($npass);
1528: $npass=&unescape($npass);
1529: my $proname=propath($udom,$uname);
1530: my $passfilename="$proname/passwd";
1531: &Debug("Password file created will be:".
1532: $passfilename);
1533: if (-e $passfilename) {
1534: print $client "already_exists\n";
1535: } elsif ($udom ne $currentdomainid) {
1536: print $client "not_right_domain\n";
1537: } else {
1538: my @fpparts=split(/\//,$proname);
1539: my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
1540: my $fperror='';
1541: for (my $i=3;$i<=$#fpparts;$i++) {
1542: $fpnow.='/'.$fpparts[$i];
1543: unless (-e $fpnow) {
1544: unless (mkdir($fpnow,0777)) {
1545: $fperror="error: ".($!+0)
1546: ." mkdir failed while attempting "
1547: ."makeuser";
1548: }
1549: }
1550: }
1551: unless ($fperror) {
1552: my $result=&make_passwd_file($uname, $umode,$npass,
1553: $passfilename);
1554: print $client $result;
1555: } else {
1556: print $client "$fperror\n";
1557: }
1558: }
1559: } else {
1560: Reply($client, "refused\n", $userinput);
1561:
1562: }
1563: umask($oldumask);
1564: # -------------------------------------------------------------- changeuserauth
1565: } elsif ($userinput =~ /^changeuserauth/) { # encoded & client
1566: &Debug("Changing authorization");
1567: if (($wasenc==1) && isClient) {
1568: my
1569: ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
1570: chomp($npass);
1571: &Debug("cmd = ".$cmd." domain= ".$udom.
1572: "uname =".$uname." umode= ".$umode);
1573: $npass=&unescape($npass);
1574: my $proname=&propath($udom,$uname);
1575: my $passfilename="$proname/passwd";
1576: if ($udom ne $currentdomainid) {
1577: print $client "not_right_domain\n";
1578: } else {
1579: my $result=&make_passwd_file($uname, $umode,$npass,
1580: $passfilename);
1581: print $client $result;
1582: }
1583: } else {
1584: Reply($client, "refused\n", $userinput);
1585:
1586: }
1587: # ------------------------------------------------------------------------ home
1588: } elsif ($userinput =~ /^home/) { # client clear or encoded
1589: if(isClient) {
1590: my ($cmd,$udom,$uname)=split(/:/,$userinput);
1591: chomp($uname);
1592: my $proname=propath($udom,$uname);
1593: if (-e $proname) {
1594: print $client "found\n";
1595: } else {
1596: print $client "not_found\n";
1597: }
1598: } else {
1599: Reply($client, "refused\n", $userinput);
1600:
1601: }
1602: # ---------------------------------------------------------------------- update
1603: } elsif ($userinput =~ /^update/) { # client clear or encoded.
1604: if(isClient) {
1605: my ($cmd,$fname)=split(/:/,$userinput);
1606: my $ownership=ishome($fname);
1607: if ($ownership eq 'not_owner') {
1608: if (-e $fname) {
1609: my ($dev,$ino,$mode,$nlink,
1610: $uid,$gid,$rdev,$size,
1611: $atime,$mtime,$ctime,
1612: $blksize,$blocks)=stat($fname);
1613: my $now=time;
1614: my $since=$now-$atime;
1615: if ($since>$perlvar{'lonExpire'}) {
1616: my $reply=
1617: &reply("unsub:$fname","$clientname");
1618: unlink("$fname");
1619: } else {
1620: my $transname="$fname.in.transfer";
1621: my $remoteurl=
1622: &reply("sub:$fname","$clientname");
1623: my $response;
1624: {
1625: my $ua=new LWP::UserAgent;
1626: my $request=new HTTP::Request('GET',"$remoteurl");
1627: $response=$ua->request($request,$transname);
1628: }
1629: if ($response->is_error()) {
1630: unlink($transname);
1631: my $message=$response->status_line;
1632: &logthis(
1633: "LWP GET: $message for $fname ($remoteurl)");
1634: } else {
1635: if ($remoteurl!~/\.meta$/) {
1636: my $ua=new LWP::UserAgent;
1637: my $mrequest=
1638: new HTTP::Request('GET',$remoteurl.'.meta');
1639: my $mresponse=
1640: $ua->request($mrequest,$fname.'.meta');
1641: if ($mresponse->is_error()) {
1642: unlink($fname.'.meta');
1643: }
1644: }
1645: rename($transname,$fname);
1646: }
1647: }
1648: print $client "ok\n";
1649: } else {
1650: print $client "not_found\n";
1651: }
1652: } else {
1653: print $client "rejected\n";
1654: }
1655: } else {
1656: Reply($client, "refused\n", $userinput);
1657:
1658: }
1659: # -------------------------------------- fetch a user file from a remote server
1660: } elsif ($userinput =~ /^fetchuserfile/) { # Client clear or enc.
1661: if(isClient) {
1662: my ($cmd,$fname)=split(/:/,$userinput);
1663: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1664: my $udir=propath($udom,$uname).'/userfiles';
1665: unless (-e $udir) { mkdir($udir,0770); }
1666: if (-e $udir) {
1667: $ufile=~s/^[\.\~]+//;
1668: my $path = $udir;
1669: if ($ufile =~m|(.+)/([^/]+)$|) {
1670: my @parts=split('/',$1);
1671: foreach my $part (@parts) {
1672: $path .= '/'.$part;
1673: if ((-e $path)!=1) {
1674: mkdir($path,0770);
1675: }
1676: }
1677: }
1678: my $destname=$udir.'/'.$ufile;
1679: my $transname=$udir.'/'.$ufile.'.in.transit';
1680: my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
1681: my $response;
1682: {
1683: my $ua=new LWP::UserAgent;
1684: my $request=new HTTP::Request('GET',"$remoteurl");
1685: $response=$ua->request($request,$transname);
1686: }
1687: if ($response->is_error()) {
1688: unlink($transname);
1689: my $message=$response->status_line;
1690: &logthis("LWP GET: $message for $fname ($remoteurl)");
1691: print $client "failed\n";
1692: } else {
1693: if (!rename($transname,$destname)) {
1694: &logthis("Unable to move $transname to $destname");
1695: unlink($transname);
1696: print $client "failed\n";
1697: } else {
1698: print $client "ok\n";
1699: }
1700: }
1701: } else {
1702: print $client "not_home\n";
1703: }
1704: } else {
1705: Reply($client, "refused\n", $userinput);
1706: }
1707: # --------------------------------------------------------- remove a user file
1708: } elsif ($userinput =~ /^removeuserfile/) { # Client clear or enc.
1709: if(isClient) {
1710: my ($cmd,$fname)=split(/:/,$userinput);
1711: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1712: &logthis("$udom - $uname - $ufile");
1713: if ($ufile =~m|/\.\./|) {
1714: # any files paths with /../ in them refuse
1715: # to deal with
1716: print $client "refused\n";
1717: } else {
1718: my $udir=propath($udom,$uname);
1719: if (-e $udir) {
1720: my $file=$udir.'/userfiles/'.$ufile;
1721: if (-e $file) {
1722: unlink($file);
1723: if (-e $file) {
1724: print $client "failed\n";
1725: } else {
1726: print $client "ok\n";
1727: }
1728: } else {
1729: print $client "not_found\n";
1730: }
1731: } else {
1732: print $client "not_home\n";
1733: }
1734: }
1735: } else {
1736: Reply($client, "refused\n", $userinput);
1737: }
1738: # ------------------------------------------ authenticate access to a user file
1739: } elsif ($userinput =~ /^tokenauthuserfile/) { # Client only
1740: if(isClient) {
1741: my ($cmd,$fname,$session)=split(/:/,$userinput);
1742: chomp($session);
1743: my $reply='non_auth';
1744: if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
1745: $session.'.id')) {
1746: while (my $line=<ENVIN>) {
1747: if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply='ok'; }
1748: }
1749: close(ENVIN);
1750: print $client $reply."\n";
1751: } else {
1752: print $client "invalid_token\n";
1753: }
1754: } else {
1755: Reply($client, "refused\n", $userinput);
1756:
1757: }
1758: # ----------------------------------------------------------------- unsubscribe
1759: } elsif ($userinput =~ /^unsub/) {
1760: if(isClient) {
1761: my ($cmd,$fname)=split(/:/,$userinput);
1762: if (-e $fname) {
1763: print $client &unsub($fname,$clientip);
1764: } else {
1765: print $client "not_found\n";
1766: }
1767: } else {
1768: Reply($client, "refused\n", $userinput);
1769:
1770: }
1771: # ------------------------------------------------------------------- subscribe
1772: } elsif ($userinput =~ /^sub/) {
1773: if(isClient) {
1774: print $client &subscribe($userinput,$clientip);
1775: } else {
1776: Reply($client, "refused\n", $userinput);
1777:
1778: }
1779: # ------------------------------------------------------------- current version
1780: } elsif ($userinput =~ /^currentversion/) {
1781: if(isClient) {
1782: my ($cmd,$fname)=split(/:/,$userinput);
1783: print $client ¤tversion($fname)."\n";
1784: } else {
1785: Reply($client, "refused\n", $userinput);
1786:
1787: }
1788: # ------------------------------------------------------------------------- log
1789: } elsif ($userinput =~ /^log/) {
1790: if(isClient) {
1791: my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
1792: chomp($what);
1793: my $proname=propath($udom,$uname);
1794: my $now=time;
1795: {
1796: my $hfh;
1797: if ($hfh=IO::File->new(">>$proname/activity.log")) {
1798: print $hfh "$now:$clientname:$what\n";
1799: print $client "ok\n";
1800: } else {
1801: print $client "error: ".($!+0)
1802: ." IO::File->new Failed "
1803: ."while attempting log\n";
1804: }
1805: }
1806: } else {
1807: Reply($client, "refused\n", $userinput);
1808:
1809: }
1810: # ------------------------------------------------------------------------- put
1811: } elsif ($userinput =~ /^put/) {
1812: if(isClient) {
1813: my ($cmd,$udom,$uname,$namespace,$what)
1814: =split(/:/,$userinput,5);
1815: $namespace=~s/\//\_/g;
1816: $namespace=~s/\W//g;
1817: if ($namespace ne 'roles') {
1818: chomp($what);
1819: my $proname=propath($udom,$uname);
1820: my $now=time;
1821: my @pairs=split(/\&/,$what);
1822: my %hash;
1823: if (tie(%hash,'GDBM_File',
1824: "$proname/$namespace.db",
1825: &GDBM_WRCREAT(),0640)) {
1826: unless ($namespace=~/^nohist\_/) {
1827: my $hfh;
1828: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
1829: }
1830:
1831: foreach my $pair (@pairs) {
1832: my ($key,$value)=split(/=/,$pair);
1833: $hash{$key}=$value;
1834: }
1835: if (untie(%hash)) {
1836: print $client "ok\n";
1837: } else {
1838: print $client "error: ".($!+0)
1839: ." untie(GDBM) failed ".
1840: "while attempting put\n";
1841: }
1842: } else {
1843: print $client "error: ".($!)
1844: ." tie(GDBM) Failed ".
1845: "while attempting put\n";
1846: }
1847: } else {
1848: print $client "refused\n";
1849: }
1850: } else {
1851: Reply($client, "refused\n", $userinput);
1852:
1853: }
1854: # ------------------------------------------------------------------- inc
1855: } elsif ($userinput =~ /^inc:/) {
1856: if(isClient) {
1857: my ($cmd,$udom,$uname,$namespace,$what)
1858: =split(/:/,$userinput);
1859: $namespace=~s/\//\_/g;
1860: $namespace=~s/\W//g;
1861: if ($namespace ne 'roles') {
1862: chomp($what);
1863: my $proname=propath($udom,$uname);
1864: my $now=time;
1865: my @pairs=split(/\&/,$what);
1866: my %hash;
1867: if (tie(%hash,'GDBM_File',
1868: "$proname/$namespace.db",
1869: &GDBM_WRCREAT(),0640)) {
1870: unless ($namespace=~/^nohist\_/) {
1871: my $hfh;
1872: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
1873: }
1874: foreach my $pair (@pairs) {
1875: my ($key,$value)=split(/=/,$pair);
1876: # We could check that we have a number...
1877: if (! defined($value) || $value eq '') {
1878: $value = 1;
1879: }
1880: $hash{$key}+=$value;
1881: }
1882: if (untie(%hash)) {
1883: print $client "ok\n";
1884: } else {
1885: print $client "error: ".($!+0)
1886: ." untie(GDBM) failed ".
1887: "while attempting inc\n";
1888: }
1889: } else {
1890: print $client "error: ".($!)
1891: ." tie(GDBM) Failed ".
1892: "while attempting inc\n";
1893: }
1894: } else {
1895: print $client "refused\n";
1896: }
1897: } else {
1898: Reply($client, "refused\n", $userinput);
1899:
1900: }
1901: # -------------------------------------------------------------------- rolesput
1902: } elsif ($userinput =~ /^rolesput/) {
1903: if(isClient) {
1904: &Debug("rolesput");
1905: if ($wasenc==1) {
1906: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
1907: =split(/:/,$userinput);
1908: &Debug("cmd = ".$cmd." exedom= ".$exedom.
1909: "user = ".$exeuser." udom=".$udom.
1910: "what = ".$what);
1911: my $namespace='roles';
1912: chomp($what);
1913: my $proname=propath($udom,$uname);
1914: my $now=time;
1915: my @pairs=split(/\&/,$what);
1916: my %hash;
1917: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1918: {
1919: my $hfh;
1920: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
1921: print $hfh "P:$now:$exedom:$exeuser:$what\n";
1922: }
1923: }
1924:
1925: foreach my $pair (@pairs) {
1926: my ($key,$value)=split(/=/,$pair);
1927: &ManagePermissions($key, $udom, $uname,
1928: &GetAuthType( $udom,
1929: $uname));
1930: $hash{$key}=$value;
1931: }
1932: if (untie(%hash)) {
1933: print $client "ok\n";
1934: } else {
1935: print $client "error: ".($!+0)
1936: ." untie(GDBM) Failed ".
1937: "while attempting rolesput\n";
1938: }
1939: } else {
1940: print $client "error: ".($!+0)
1941: ." tie(GDBM) Failed ".
1942: "while attempting rolesput\n";
1943: }
1944: } else {
1945: print $client "refused\n";
1946: }
1947: } else {
1948: Reply($client, "refused\n", $userinput);
1949:
1950: }
1951: # -------------------------------------------------------------------- rolesdel
1952: } elsif ($userinput =~ /^rolesdel/) {
1953: if(isClient) {
1954: &Debug("rolesdel");
1955: if ($wasenc==1) {
1956: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
1957: =split(/:/,$userinput);
1958: &Debug("cmd = ".$cmd." exedom= ".$exedom.
1959: "user = ".$exeuser." udom=".$udom.
1960: "what = ".$what);
1961: my $namespace='roles';
1962: chomp($what);
1963: my $proname=propath($udom,$uname);
1964: my $now=time;
1965: my @rolekeys=split(/\&/,$what);
1966: my %hash;
1967: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1968: {
1969: my $hfh;
1970: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
1971: print $hfh "D:$now:$exedom:$exeuser:$what\n";
1972: }
1973: }
1974: foreach my $key (@rolekeys) {
1975: delete $hash{$key};
1976: }
1977: if (untie(%hash)) {
1978: print $client "ok\n";
1979: } else {
1980: print $client "error: ".($!+0)
1981: ." untie(GDBM) Failed ".
1982: "while attempting rolesdel\n";
1983: }
1984: } else {
1985: print $client "error: ".($!+0)
1986: ." tie(GDBM) Failed ".
1987: "while attempting rolesdel\n";
1988: }
1989: } else {
1990: print $client "refused\n";
1991: }
1992: } else {
1993: Reply($client, "refused\n", $userinput);
1994:
1995: }
1996: # ------------------------------------------------------------------------- get
1997: } elsif ($userinput =~ /^get/) {
1998: if(isClient) {
1999: my ($cmd,$udom,$uname,$namespace,$what)
2000: =split(/:/,$userinput);
2001: $namespace=~s/\//\_/g;
2002: $namespace=~s/\W//g;
2003: chomp($what);
2004: my @queries=split(/\&/,$what);
2005: my $proname=propath($udom,$uname);
2006: my $qresult='';
2007: my %hash;
2008: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2009: for (my $i=0;$i<=$#queries;$i++) {
2010: $qresult.="$hash{$queries[$i]}&";
2011: }
2012: if (untie(%hash)) {
2013: $qresult=~s/\&$//;
2014: print $client "$qresult\n";
2015: } else {
2016: print $client "error: ".($!+0)
2017: ." untie(GDBM) Failed ".
2018: "while attempting get\n";
2019: }
2020: } else {
2021: if ($!+0 == 2) {
2022: print $client "error:No such file or ".
2023: "GDBM reported bad block error\n";
2024: } else {
2025: print $client "error: ".($!+0)
2026: ." tie(GDBM) Failed ".
2027: "while attempting get\n";
2028: }
2029: }
2030: } else {
2031: Reply($client, "refused\n", $userinput);
2032:
2033: }
2034: # ------------------------------------------------------------------------ eget
2035: } elsif ($userinput =~ /^eget/) {
2036: if (isClient) {
2037: my ($cmd,$udom,$uname,$namespace,$what)
2038: =split(/:/,$userinput);
2039: $namespace=~s/\//\_/g;
2040: $namespace=~s/\W//g;
2041: chomp($what);
2042: my @queries=split(/\&/,$what);
2043: my $proname=propath($udom,$uname);
2044: my $qresult='';
2045: my %hash;
2046: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2047: for (my $i=0;$i<=$#queries;$i++) {
2048: $qresult.="$hash{$queries[$i]}&";
2049: }
2050: if (untie(%hash)) {
2051: $qresult=~s/\&$//;
2052: if ($cipher) {
2053: my $cmdlength=length($qresult);
2054: $qresult.=" ";
2055: my $encqresult='';
2056: for
2057: (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
2058: $encqresult.=
2059: unpack("H16",
2060: $cipher->encrypt(substr($qresult,$encidx,8)));
2061: }
2062: print $client "enc:$cmdlength:$encqresult\n";
2063: } else {
2064: print $client "error:no_key\n";
2065: }
2066: } else {
2067: print $client "error: ".($!+0)
2068: ." untie(GDBM) Failed ".
2069: "while attempting eget\n";
2070: }
2071: } else {
2072: print $client "error: ".($!+0)
2073: ." tie(GDBM) Failed ".
2074: "while attempting eget\n";
2075: }
2076: } else {
2077: Reply($client, "refused\n", $userinput);
2078:
2079: }
2080: # ------------------------------------------------------------------------- del
2081: } elsif ($userinput =~ /^del/) {
2082: if(isClient) {
2083: my ($cmd,$udom,$uname,$namespace,$what)
2084: =split(/:/,$userinput);
2085: $namespace=~s/\//\_/g;
2086: $namespace=~s/\W//g;
2087: chomp($what);
2088: my $proname=propath($udom,$uname);
2089: my $now=time;
2090: my @keys=split(/\&/,$what);
2091: my %hash;
2092: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2093: unless ($namespace=~/^nohist\_/) {
2094: my $hfh;
2095: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "D:$now:$what\n"; }
2096: }
2097: foreach my $key (@keys) {
2098: delete($hash{$key});
2099: }
2100: if (untie(%hash)) {
2101: print $client "ok\n";
2102: } else {
2103: print $client "error: ".($!+0)
2104: ." untie(GDBM) Failed ".
2105: "while attempting del\n";
2106: }
2107: } else {
2108: print $client "error: ".($!+0)
2109: ." tie(GDBM) Failed ".
2110: "while attempting del\n";
2111: }
2112: } else {
2113: Reply($client, "refused\n", $userinput);
2114:
2115: }
2116: # ------------------------------------------------------------------------ keys
2117: } elsif ($userinput =~ /^keys/) {
2118: if(isClient) {
2119: my ($cmd,$udom,$uname,$namespace)
2120: =split(/:/,$userinput);
2121: $namespace=~s/\//\_/g;
2122: $namespace=~s/\W//g;
2123: my $proname=propath($udom,$uname);
2124: my $qresult='';
2125: my %hash;
2126: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2127: foreach my $key (keys %hash) {
2128: $qresult.="$key&";
2129: }
2130: if (untie(%hash)) {
2131: $qresult=~s/\&$//;
2132: print $client "$qresult\n";
2133: } else {
2134: print $client "error: ".($!+0)
2135: ." untie(GDBM) Failed ".
2136: "while attempting keys\n";
2137: }
2138: } else {
2139: print $client "error: ".($!+0)
2140: ." tie(GDBM) Failed ".
2141: "while attempting keys\n";
2142: }
2143: } else {
2144: Reply($client, "refused\n", $userinput);
2145:
2146: }
2147: # ----------------------------------------------------------------- dumpcurrent
2148: } elsif ($userinput =~ /^currentdump/) {
2149: if (isClient) {
2150: my ($cmd,$udom,$uname,$namespace)
2151: =split(/:/,$userinput);
2152: $namespace=~s/\//\_/g;
2153: $namespace=~s/\W//g;
2154: my $qresult='';
2155: my $proname=propath($udom,$uname);
2156: my %hash;
2157: if (tie(%hash,'GDBM_File',
2158: "$proname/$namespace.db",
2159: &GDBM_READER(),0640)) {
2160: # Structure of %data:
2161: # $data{$symb}->{$parameter}=$value;
2162: # $data{$symb}->{'v.'.$parameter}=$version;
2163: # since $parameter will be unescaped, we do not
2164: # have to worry about silly parameter names...
2165: my %data = ();
2166: while (my ($key,$value) = each(%hash)) {
2167: my ($v,$symb,$param) = split(/:/,$key);
2168: next if ($v eq 'version' || $symb eq 'keys');
2169: next if (exists($data{$symb}) &&
2170: exists($data{$symb}->{$param}) &&
2171: $data{$symb}->{'v.'.$param} > $v);
2172: $data{$symb}->{$param}=$value;
2173: $data{$symb}->{'v.'.$param}=$v;
2174: }
2175: if (untie(%hash)) {
2176: while (my ($symb,$param_hash) = each(%data)) {
2177: while(my ($param,$value) = each (%$param_hash)){
2178: next if ($param =~ /^v\./);
2179: $qresult.=$symb.':'.$param.'='.$value.'&';
2180: }
2181: }
2182: chop($qresult);
2183: print $client "$qresult\n";
2184: } else {
2185: print $client "error: ".($!+0)
2186: ." untie(GDBM) Failed ".
2187: "while attempting currentdump\n";
2188: }
2189: } else {
2190: print $client "error: ".($!+0)
2191: ." tie(GDBM) Failed ".
2192: "while attempting currentdump\n";
2193: }
2194: } else {
2195: Reply($client, "refused\n", $userinput);
2196: }
2197: # ------------------------------------------------------------------------ dump
2198: } elsif ($userinput =~ /^dump/) {
2199: if(isClient) {
2200: my ($cmd,$udom,$uname,$namespace,$regexp)
2201: =split(/:/,$userinput);
2202: $namespace=~s/\//\_/g;
2203: $namespace=~s/\W//g;
2204: if (defined($regexp)) {
2205: $regexp=&unescape($regexp);
2206: } else {
2207: $regexp='.';
2208: }
2209: my $qresult='';
2210: my $proname=propath($udom,$uname);
2211: my %hash;
2212: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2213: while (my ($key,$value) = each(%hash)) {
2214: if ($regexp eq '.') {
2215: $qresult.=$key.'='.$value.'&';
2216: } else {
2217: my $unescapeKey = &unescape($key);
2218: if (eval('$unescapeKey=~/$regexp/')) {
2219: $qresult.="$key=$value&";
2220: }
2221: }
2222: }
2223: if (untie(%hash)) {
2224: chop($qresult);
2225: print $client "$qresult\n";
2226: } else {
2227: print $client "error: ".($!+0)
2228: ." untie(GDBM) Failed ".
2229: "while attempting dump\n";
2230: }
2231: } else {
2232: print $client "error: ".($!+0)
2233: ." tie(GDBM) Failed ".
2234: "while attempting dump\n";
2235: }
2236: } else {
2237: Reply($client, "refused\n", $userinput);
2238:
2239: }
2240: # ----------------------------------------------------------------------- store
2241: } elsif ($userinput =~ /^store/) {
2242: if(isClient) {
2243: my ($cmd,$udom,$uname,$namespace,$rid,$what)
2244: =split(/:/,$userinput);
2245: $namespace=~s/\//\_/g;
2246: $namespace=~s/\W//g;
2247: if ($namespace ne 'roles') {
2248: chomp($what);
2249: my $proname=propath($udom,$uname);
2250: my $now=time;
2251: my @pairs=split(/\&/,$what);
2252: my %hash;
2253: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2254: unless ($namespace=~/^nohist\_/) {
2255: my $hfh;
2256: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
2257: print $hfh "P:$now:$rid:$what\n";
2258: }
2259: }
2260: my @previouskeys=split(/&/,$hash{"keys:$rid"});
2261: my $key;
2262: $hash{"version:$rid"}++;
2263: my $version=$hash{"version:$rid"};
2264: my $allkeys='';
2265: foreach my $pair (@pairs) {
2266: my ($key,$value)=split(/=/,$pair);
2267: $allkeys.=$key.':';
2268: $hash{"$version:$rid:$key"}=$value;
2269: }
2270: $hash{"$version:$rid:timestamp"}=$now;
2271: $allkeys.='timestamp';
2272: $hash{"$version:keys:$rid"}=$allkeys;
2273: if (untie(%hash)) {
2274: print $client "ok\n";
2275: } else {
2276: print $client "error: ".($!+0)
2277: ." untie(GDBM) Failed ".
2278: "while attempting store\n";
2279: }
2280: } else {
2281: print $client "error: ".($!+0)
2282: ." tie(GDBM) Failed ".
2283: "while attempting store\n";
2284: }
2285: } else {
2286: print $client "refused\n";
2287: }
2288: } else {
2289: Reply($client, "refused\n", $userinput);
2290:
2291: }
2292: # --------------------------------------------------------------------- restore
2293: } elsif ($userinput =~ /^restore/) {
2294: if(isClient) {
2295: my ($cmd,$udom,$uname,$namespace,$rid)
2296: =split(/:/,$userinput);
2297: $namespace=~s/\//\_/g;
2298: $namespace=~s/\W//g;
2299: chomp($rid);
2300: my $proname=propath($udom,$uname);
2301: my $qresult='';
2302: my %hash;
2303: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2304: my $version=$hash{"version:$rid"};
2305: $qresult.="version=$version&";
2306: my $scope;
2307: for ($scope=1;$scope<=$version;$scope++) {
2308: my $vkeys=$hash{"$scope:keys:$rid"};
2309: my @keys=split(/:/,$vkeys);
2310: my $key;
2311: $qresult.="$scope:keys=$vkeys&";
2312: foreach $key (@keys) {
2313: $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
2314: }
2315: }
2316: if (untie(%hash)) {
2317: $qresult=~s/\&$//;
2318: print $client "$qresult\n";
2319: } else {
2320: print $client "error: ".($!+0)
2321: ." untie(GDBM) Failed ".
2322: "while attempting restore\n";
2323: }
2324: } else {
2325: print $client "error: ".($!+0)
2326: ." tie(GDBM) Failed ".
2327: "while attempting restore\n";
2328: }
2329: } else {
2330: Reply($client, "refused\n", $userinput);
2331:
2332: }
2333: # -------------------------------------------------------------------- chatsend
2334: } elsif ($userinput =~ /^chatsend/) {
2335: if(isClient) {
2336: my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
2337: &chatadd($cdom,$cnum,$newpost);
2338: print $client "ok\n";
2339: } else {
2340: Reply($client, "refused\n", $userinput);
2341:
2342: }
2343: # -------------------------------------------------------------------- chatretr
2344: } elsif ($userinput =~ /^chatretr/) {
2345: if(isClient) {
2346: my
2347: ($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
2348: my $reply='';
2349: foreach (&getchat($cdom,$cnum,$udom,$uname)) {
2350: $reply.=&escape($_).':';
2351: }
2352: $reply=~s/\:$//;
2353: print $client $reply."\n";
2354: } else {
2355: Reply($client, "refused\n", $userinput);
2356:
2357: }
2358: # ------------------------------------------------------------------- querysend
2359: } elsif ($userinput =~ /^querysend/) {
2360: if (isClient) {
2361: my ($cmd,$query,
2362: $arg1,$arg2,$arg3)=split(/\:/,$userinput);
2363: $query=~s/\n*$//g;
2364: print $client "".
2365: sqlreply("$clientname\&$query".
2366: "\&$arg1"."\&$arg2"."\&$arg3")."\n";
2367: } else {
2368: Reply($client, "refused\n", $userinput);
2369:
2370: }
2371: # ------------------------------------------------------------------ queryreply
2372: } elsif ($userinput =~ /^queryreply/) {
2373: if(isClient) {
2374: my ($cmd,$id,$reply)=split(/:/,$userinput);
2375: my $store;
2376: my $execdir=$perlvar{'lonDaemons'};
2377: if ($store=IO::File->new(">$execdir/tmp/$id")) {
2378: $reply=~s/\&/\n/g;
2379: print $store $reply;
2380: close $store;
2381: my $store2=IO::File->new(">$execdir/tmp/$id.end");
2382: print $store2 "done\n";
2383: close $store2;
2384: print $client "ok\n";
2385: }
2386: else {
2387: print $client "error: ".($!+0)
2388: ." IO::File->new Failed ".
2389: "while attempting queryreply\n";
2390: }
2391: } else {
2392: Reply($client, "refused\n", $userinput);
2393:
2394: }
2395: # ----------------------------------------------------------------- courseidput
2396: } elsif ($userinput =~ /^courseidput/) {
2397: if(isClient) {
2398: my ($cmd,$udom,$what)=split(/:/,$userinput);
2399: chomp($what);
2400: $udom=~s/\W//g;
2401: my $proname=
2402: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
2403: my $now=time;
2404: my @pairs=split(/\&/,$what);
2405: my %hash;
2406: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
2407: foreach my $pair (@pairs) {
2408: my ($key,$descr,$inst_code)=split(/=/,$pair);
2409: $hash{$key}=$descr.':'.$inst_code.':'.$now;
2410: }
2411: if (untie(%hash)) {
2412: print $client "ok\n";
2413: } else {
2414: print $client "error: ".($!+0)
2415: ." untie(GDBM) Failed ".
2416: "while attempting courseidput\n";
2417: }
2418: } else {
2419: print $client "error: ".($!+0)
2420: ." tie(GDBM) Failed ".
2421: "while attempting courseidput\n";
2422: }
2423: } else {
2424: Reply($client, "refused\n", $userinput);
2425:
2426: }
2427: # ---------------------------------------------------------------- courseiddump
2428: } elsif ($userinput =~ /^courseiddump/) {
2429: if(isClient) {
2430: my ($cmd,$udom,$since,$description)
2431: =split(/:/,$userinput);
2432: if (defined($description)) {
2433: $description=&unescape($description);
2434: } else {
2435: $description='.';
2436: }
2437: unless (defined($since)) { $since=0; }
2438: my $qresult='';
2439: my $proname=
2440: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
2441: my %hash;
2442: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
2443: while (my ($key,$value) = each(%hash)) {
2444: my ($descr,$lasttime,$inst_code);
2445: if ($value =~ m/^([^\:]*):([^\:]*):(\d+)$/) {
2446: ($descr,$inst_code,$lasttime)=($1,$2,$3);
2447: } else {
2448: ($descr,$lasttime) = split(/\:/,$value);
2449: }
2450: if ($lasttime<$since) { next; }
2451: if ($description eq '.') {
2452: $qresult.=$key.'='.$descr.':'.$inst_code.'&';
2453: } else {
2454: my $unescapeVal = &unescape($descr);
2455: if (eval('$unescapeVal=~/\Q$description\E/i')) {
2456: $qresult.=$key.'='.$descr.':'.$inst_code.'&';
2457: }
2458: }
2459: }
2460: if (untie(%hash)) {
2461: chop($qresult);
2462: print $client "$qresult\n";
2463: } else {
2464: print $client "error: ".($!+0)
2465: ." untie(GDBM) Failed ".
2466: "while attempting courseiddump\n";
2467: }
2468: } else {
2469: print $client "error: ".($!+0)
2470: ." tie(GDBM) Failed ".
2471: "while attempting courseiddump\n";
2472: }
2473: } else {
2474: Reply($client, "refused\n", $userinput);
2475:
2476: }
2477: # ----------------------------------------------------------------------- idput
2478: } elsif ($userinput =~ /^idput/) {
2479: if(isClient) {
2480: my ($cmd,$udom,$what)=split(/:/,$userinput);
2481: chomp($what);
2482: $udom=~s/\W//g;
2483: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
2484: my $now=time;
2485: my @pairs=split(/\&/,$what);
2486: my %hash;
2487: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
2488: {
2489: my $hfh;
2490: if ($hfh=IO::File->new(">>$proname.hist")) {
2491: print $hfh "P:$now:$what\n";
2492: }
2493: }
2494: foreach my $pair (@pairs) {
2495: my ($key,$value)=split(/=/,$pair);
2496: $hash{$key}=$value;
2497: }
2498: if (untie(%hash)) {
2499: print $client "ok\n";
2500: } else {
2501: print $client "error: ".($!+0)
2502: ." untie(GDBM) Failed ".
2503: "while attempting idput\n";
2504: }
2505: } else {
2506: print $client "error: ".($!+0)
2507: ." tie(GDBM) Failed ".
2508: "while attempting idput\n";
2509: }
2510: } else {
2511: Reply($client, "refused\n", $userinput);
2512:
2513: }
2514: # ----------------------------------------------------------------------- idget
2515: } elsif ($userinput =~ /^idget/) {
2516: if(isClient) {
2517: my ($cmd,$udom,$what)=split(/:/,$userinput);
2518: chomp($what);
2519: $udom=~s/\W//g;
2520: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
2521: my @queries=split(/\&/,$what);
2522: my $qresult='';
2523: my %hash;
2524: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
2525: for (my $i=0;$i<=$#queries;$i++) {
2526: $qresult.="$hash{$queries[$i]}&";
2527: }
2528: if (untie(%hash)) {
2529: $qresult=~s/\&$//;
2530: print $client "$qresult\n";
2531: } else {
2532: print $client "error: ".($!+0)
2533: ." untie(GDBM) Failed ".
2534: "while attempting idget\n";
2535: }
2536: } else {
2537: print $client "error: ".($!+0)
2538: ." tie(GDBM) Failed ".
2539: "while attempting idget\n";
2540: }
2541: } else {
2542: Reply($client, "refused\n", $userinput);
2543:
2544: }
2545: # ---------------------------------------------------------------------- tmpput
2546: } elsif ($userinput =~ /^tmpput/) {
2547: if(isClient) {
2548: my ($cmd,$what)=split(/:/,$userinput);
2549: my $store;
2550: $tmpsnum++;
2551: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
2552: $id=~s/\W/\_/g;
2553: $what=~s/\n//g;
2554: my $execdir=$perlvar{'lonDaemons'};
2555: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
2556: print $store $what;
2557: close $store;
2558: print $client "$id\n";
2559: }
2560: else {
2561: print $client "error: ".($!+0)
2562: ."IO::File->new Failed ".
2563: "while attempting tmpput\n";
2564: }
2565: } else {
2566: Reply($client, "refused\n", $userinput);
2567:
2568: }
2569:
2570: # ---------------------------------------------------------------------- tmpget
2571: } elsif ($userinput =~ /^tmpget/) {
2572: if(isClient) {
2573: my ($cmd,$id)=split(/:/,$userinput);
2574: chomp($id);
2575: $id=~s/\W/\_/g;
2576: my $store;
2577: my $execdir=$perlvar{'lonDaemons'};
2578: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
2579: my $reply=<$store>;
2580: print $client "$reply\n";
2581: close $store;
2582: }
2583: else {
2584: print $client "error: ".($!+0)
2585: ."IO::File->new Failed ".
2586: "while attempting tmpget\n";
2587: }
2588: } else {
2589: Reply($client, "refused\n", $userinput);
2590:
2591: }
2592: # ---------------------------------------------------------------------- tmpdel
2593: } elsif ($userinput =~ /^tmpdel/) {
2594: if(isClient) {
2595: my ($cmd,$id)=split(/:/,$userinput);
2596: chomp($id);
2597: $id=~s/\W/\_/g;
2598: my $execdir=$perlvar{'lonDaemons'};
2599: if (unlink("$execdir/tmp/$id.tmp")) {
2600: print $client "ok\n";
2601: } else {
2602: print $client "error: ".($!+0)
2603: ."Unlink tmp Failed ".
2604: "while attempting tmpdel\n";
2605: }
2606: } else {
2607: Reply($client, "refused\n", $userinput);
2608:
2609: }
2610: # ----------------------------------------- portfolio directory list (portls)
2611: } elsif ($userinput =~ /^portls/) {
2612: if(isClient) {
2613: my ($cmd,$uname,$udom)=split(/:/,$userinput);
2614: my $udir=propath($udom,$uname).'/userfiles/portfolio';
2615: my $dirLine='';
2616: my $dirContents='';
2617: if (opendir(LSDIR,$udir.'/')){
2618: while ($dirLine = readdir(LSDIR)){
2619: $dirContents = $dirContents.$dirLine.'<br />';
2620: }
2621: } else {
2622: $dirContents = "No directory found\n";
2623: }
2624: print $client $dirContents."\n";
2625: } else {
2626: Reply($client, "refused\n", $userinput);
2627: }
2628: # -------------------------------------------------------------------------- ls
2629: } elsif ($userinput =~ /^ls/) {
2630: if(isClient) {
2631: my $obs;
2632: my $rights;
2633: my ($cmd,$ulsdir)=split(/:/,$userinput);
2634: my $ulsout='';
2635: my $ulsfn;
2636: if (-e $ulsdir) {
2637: if(-d $ulsdir) {
2638: if (opendir(LSDIR,$ulsdir)) {
2639: while ($ulsfn=readdir(LSDIR)) {
2640: undef $obs, $rights;
2641: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
2642: #We do some obsolete checking here
2643: if(-e $ulsdir.'/'.$ulsfn.".meta") {
2644: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
2645: my @obsolete=<FILE>;
2646: foreach my $obsolete (@obsolete) {
2647: if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; }
2648: if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
2649: }
2650: }
2651: $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
2652: if($obs eq '1') { $ulsout.="&1"; }
2653: else { $ulsout.="&0"; }
2654: if($rights eq '1') { $ulsout.="&1:"; }
2655: else { $ulsout.="&0:"; }
2656: }
2657: closedir(LSDIR);
2658: }
2659: } else {
2660: my @ulsstats=stat($ulsdir);
2661: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
2662: }
2663: } else {
2664: $ulsout='no_such_dir';
2665: }
2666: if ($ulsout eq '') { $ulsout='empty'; }
2667: print $client "$ulsout\n";
2668: } else {
2669: Reply($client, "refused\n", $userinput);
2670:
2671: }
2672: # ----------------------------------------------------------------- setannounce
2673: } elsif ($userinput =~ /^setannounce/) {
2674: if (isClient) {
2675: my ($cmd,$announcement)=split(/:/,$userinput);
2676: chomp($announcement);
2677: $announcement=&unescape($announcement);
2678: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
2679: '/announcement.txt')) {
2680: print $store $announcement;
2681: close $store;
2682: print $client "ok\n";
2683: } else {
2684: print $client "error: ".($!+0)."\n";
2685: }
2686: } else {
2687: Reply($client, "refused\n", $userinput);
2688:
2689: }
2690: # ------------------------------------------------------------------ Hanging up
2691: } elsif (($userinput =~ /^exit/) ||
2692: ($userinput =~ /^init/)) { # no restrictions.
2693: &logthis(
2694: "Client $clientip ($clientname) hanging up: $userinput");
2695: print $client "bye\n";
2696: $client->shutdown(2); # shutdown the socket forcibly.
2697: $client->close();
2698: return 0;
2699:
2700: # ---------------------------------- set current host/domain
2701: } elsif ($userinput =~ /^sethost:/) {
2702: if (isClient) {
2703: print $client &sethost($userinput)."\n";
2704: } else {
2705: print $client "refused\n";
2706: }
2707: #---------------------------------- request file (?) version.
2708: } elsif ($userinput =~/^version:/) {
2709: if (isClient) {
2710: print $client &version($userinput)."\n";
2711: } else {
2712: print $client "refused\n";
2713: }
2714: #------------------------------- is auto-enrollment enabled?
2715: } elsif ($userinput =~/^autorun:/) {
2716: if (isClient) {
2717: my ($cmd,$cdom) = split(/:/,$userinput);
2718: my $outcome = &localenroll::run($cdom);
2719: print $client "$outcome\n";
2720: } else {
2721: print $client "0\n";
2722: }
2723: #------------------------------- get official sections (for auto-enrollment).
2724: } elsif ($userinput =~/^autogetsections:/) {
2725: if (isClient) {
2726: my ($cmd,$coursecode,$cdom)=split(/:/,$userinput);
2727: my @secs = &localenroll::get_sections($coursecode,$cdom);
2728: my $seclist = &escape(join(':',@secs));
2729: print $client "$seclist\n";
2730: } else {
2731: print $client "refused\n";
2732: }
2733: #----------------------- validate owner of new course section (for auto-enrollment).
2734: } elsif ($userinput =~/^autonewcourse:/) {
2735: if (isClient) {
2736: my ($cmd,$inst_course_id,$owner,$cdom)=split(/:/,$userinput);
2737: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
2738: print $client "$outcome\n";
2739: } else {
2740: print $client "refused\n";
2741: }
2742: #-------------- validate course section in schedule of classes (for auto-enrollment).
2743: } elsif ($userinput =~/^autovalidatecourse:/) {
2744: if (isClient) {
2745: my ($cmd,$inst_course_id,$cdom)=split(/:/,$userinput);
2746: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
2747: print $client "$outcome\n";
2748: } else {
2749: print $client "refused\n";
2750: }
2751: #--------------------------- create password for new user (for auto-enrollment).
2752: } elsif ($userinput =~/^autocreatepassword:/) {
2753: if (isClient) {
2754: my ($cmd,$authparam,$cdom)=split(/:/,$userinput);
2755: my ($create_passwd,$authchk);
2756: ($authparam,$create_passwd,$authchk) = &localenroll::create_password($authparam,$cdom);
2757: print $client &escape($authparam.':'.$create_passwd.':'.$authchk)."\n";
2758: } else {
2759: print $client "refused\n";
2760: }
2761: #--------------------------- read and remove temporary files (for auto-enrollment).
2762: } elsif ($userinput =~/^autoretrieve:/) {
2763: if (isClient) {
2764: my ($cmd,$filename) = split(/:/,$userinput);
2765: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
2766: if ( (-e $source) && ($filename ne '') ) {
2767: my $reply = '';
2768: if (open(my $fh,$source)) {
2769: while (<$fh>) {
2770: chomp($_);
2771: $_ =~ s/^\s+//g;
2772: $_ =~ s/\s+$//g;
2773: $reply .= $_;
2774: }
2775: close($fh);
2776: print $client &escape($reply)."\n";
2777: # unlink($source);
2778: } else {
2779: print $client "error\n";
2780: }
2781: } else {
2782: print $client "error\n";
2783: }
2784: } else {
2785: print $client "refused\n";
2786: }
2787: #--------------------- read and retrieve institutional code format (for support form).
2788: } elsif ($userinput =~/^autoinstcodeformat:/) {
2789: if (isClient) {
2790: my $reply;
2791: my($cmd,$cdom,$course) = split(/:/,$userinput);
2792: my @pairs = split/\&/,$course;
2793: my %instcodes = ();
2794: my %codes = ();
2795: my @codetitles = ();
2796: my %cat_titles = ();
2797: my %cat_order = ();
2798: foreach (@pairs) {
2799: my ($key,$value) = split/=/,$_;
2800: $instcodes{&unescape($key)} = &unescape($value);
2801: }
2802: my $formatreply = &localenroll::instcode_format($cdom,\%instcodes,\%codes,\@codetitles,\%cat_titles,\%cat_order);
2803: if ($formatreply eq 'ok') {
2804: my $codes_str = &hash2str(%codes);
2805: my $codetitles_str = &array2str(@codetitles);
2806: my $cat_titles_str = &hash2str(%cat_titles);
2807: my $cat_order_str = &hash2str(%cat_order);
2808: print $client $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'.$cat_order_str."\n";
2809: }
2810: } else {
2811: print $client "refused\n";
2812: }
2813: # ------------------------------------------------------------- unknown command
2814:
2815: } else {
2816: # unknown command
2817: print $client "unknown_cmd\n";
2818: }
2819: # -------------------------------------------------------------------- complete
2820: Debug("process_request - returning 1");
2821: return 1;
2822: }
1.207 foxr 2823: #
2824: # Decipher encoded traffic
2825: # Parameters:
2826: # input - Encoded data.
2827: # Returns:
2828: # Decoded data or undef if encryption key was not yet negotiated.
2829: # Implicit input:
2830: # cipher - This global holds the negotiated encryption key.
2831: #
1.211 albertel 2832: sub decipher {
1.207 foxr 2833: my ($input) = @_;
2834: my $output = '';
1.212 foxr 2835:
2836:
1.207 foxr 2837: if($cipher) {
2838: my($enc, $enclength, $encinput) = split(/:/, $input);
2839: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
2840: $output .=
2841: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
2842: }
2843: return substr($output, 0, $enclength);
2844: } else {
2845: return undef;
2846: }
2847: }
2848:
2849: #
2850: # Register a command processor. This function is invoked to register a sub
2851: # to process a request. Once registered, the ProcessRequest sub can automatically
2852: # dispatch requests to an appropriate sub, and do the top level validity checking
2853: # as well:
2854: # - Is the keyword recognized.
2855: # - Is the proper client type attempting the request.
2856: # - Is the request encrypted if it has to be.
2857: # Parameters:
2858: # $request_name - Name of the request being registered.
2859: # This is the command request that will match
2860: # against the hash keywords to lookup the information
2861: # associated with the dispatch information.
2862: # $procedure - Reference to a sub to call to process the request.
2863: # All subs get called as follows:
2864: # Procedure($cmd, $tail, $replyfd, $key)
2865: # $cmd - the actual keyword that invoked us.
2866: # $tail - the tail of the request that invoked us.
2867: # $replyfd- File descriptor connected to the client
2868: # $must_encode - True if the request must be encoded to be good.
2869: # $client_ok - True if it's ok for a client to request this.
2870: # $manager_ok - True if it's ok for a manager to request this.
2871: # Side effects:
2872: # - On success, the Dispatcher hash has an entry added for the key $RequestName
2873: # - On failure, the program will die as it's a bad internal bug to try to
2874: # register a duplicate command handler.
2875: #
1.211 albertel 2876: sub register_handler {
1.212 foxr 2877: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
1.207 foxr 2878:
2879: # Don't allow duplication#
2880:
2881: if (defined $Dispatcher{$request_name}) {
2882: die "Attempting to define a duplicate request handler for $request_name\n";
2883: }
2884: # Build the client type mask:
2885:
2886: my $client_type_mask = 0;
2887: if($client_ok) {
2888: $client_type_mask |= $CLIENT_OK;
2889: }
2890: if($manager_ok) {
2891: $client_type_mask |= $MANAGER_OK;
2892: }
2893:
2894: # Enter the hash:
2895:
2896: my @entry = ($procedure, $must_encode, $client_type_mask);
2897:
2898: $Dispatcher{$request_name} = \@entry;
2899:
2900:
2901: }
2902:
2903:
2904: #------------------------------------------------------------------
2905:
2906:
2907:
2908:
1.141 foxr 2909: #
1.96 foxr 2910: # Convert an error return code from lcpasswd to a string value.
2911: #
2912: sub lcpasswdstrerror {
2913: my $ErrorCode = shift;
1.97 foxr 2914: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 2915: return "lcpasswd Unrecognized error return value ".$ErrorCode;
2916: } else {
1.98 foxr 2917: return $passwderrors[$ErrorCode];
1.96 foxr 2918: }
2919: }
2920:
1.97 foxr 2921: #
2922: # Convert an error return code from lcuseradd to a string value:
2923: #
2924: sub lcuseraddstrerror {
2925: my $ErrorCode = shift;
2926: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
2927: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
2928: } else {
1.98 foxr 2929: return $adderrors[$ErrorCode];
1.97 foxr 2930: }
2931: }
2932:
1.23 harris41 2933: # grabs exception and records it to log before exiting
2934: sub catchexception {
1.27 albertel 2935: my ($error)=@_;
1.25 www 2936: $SIG{'QUIT'}='DEFAULT';
2937: $SIG{__DIE__}='DEFAULT';
1.165 albertel 2938: &status("Catching exception");
1.190 albertel 2939: &logthis("<font color='red'>CRITICAL: "
1.134 albertel 2940: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27 albertel 2941: ."a crash with this error msg->[$error]</font>");
1.57 www 2942: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 2943: if ($client) { print $client "error: $error\n"; }
1.59 www 2944: $server->close();
1.27 albertel 2945: die($error);
1.23 harris41 2946: }
2947:
1.63 www 2948: sub timeout {
1.165 albertel 2949: &status("Handling Timeout");
1.190 albertel 2950: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63 www 2951: &catchexception('Timeout');
2952: }
1.22 harris41 2953: # -------------------------------- Set signal handlers to record abnormal exits
2954:
2955: $SIG{'QUIT'}=\&catchexception;
2956: $SIG{__DIE__}=\&catchexception;
2957:
1.81 matthew 2958: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 2959: &status("Read loncapa.conf and loncapa_apache.conf");
2960: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 2961: %perlvar=%{$perlvarref};
1.80 harris41 2962: undef $perlvarref;
1.19 www 2963:
1.35 harris41 2964: # ----------------------------- Make sure this process is running from user=www
2965: my $wwwid=getpwnam('www');
2966: if ($wwwid!=$<) {
1.134 albertel 2967: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
2968: my $subj="LON: $currenthostid User ID mismatch";
1.37 harris41 2969: system("echo 'User ID mismatch. lond must be run as user www.' |\
1.35 harris41 2970: mailto $emailto -s '$subj' > /dev/null");
2971: exit 1;
2972: }
2973:
1.19 www 2974: # --------------------------------------------- Check if other instance running
2975:
2976: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
2977:
2978: if (-e $pidfile) {
2979: my $lfh=IO::File->new("$pidfile");
2980: my $pide=<$lfh>;
2981: chomp($pide);
1.29 harris41 2982: if (kill 0 => $pide) { die "already running"; }
1.19 www 2983: }
1.1 albertel 2984:
2985: # ------------------------------------------------------------- Read hosts file
2986:
2987:
2988:
2989: # establish SERVER socket, bind and listen.
2990: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
2991: Type => SOCK_STREAM,
2992: Proto => 'tcp',
2993: Reuse => 1,
2994: Listen => 10 )
1.29 harris41 2995: or die "making socket: $@\n";
1.1 albertel 2996:
2997: # --------------------------------------------------------- Do global variables
2998:
2999: # global variables
3000:
1.134 albertel 3001: my %children = (); # keys are current child process IDs
1.1 albertel 3002:
3003: sub REAPER { # takes care of dead children
3004: $SIG{CHLD} = \&REAPER;
1.165 albertel 3005: &status("Handling child death");
1.178 foxr 3006: my $pid;
3007: do {
3008: $pid = waitpid(-1,&WNOHANG());
3009: if (defined($children{$pid})) {
3010: &logthis("Child $pid died");
3011: delete($children{$pid});
1.183 albertel 3012: } elsif ($pid > 0) {
1.178 foxr 3013: &logthis("Unknown Child $pid died");
3014: }
3015: } while ( $pid > 0 );
3016: foreach my $child (keys(%children)) {
3017: $pid = waitpid($child,&WNOHANG());
3018: if ($pid > 0) {
3019: &logthis("Child $child - $pid looks like we missed it's death");
3020: delete($children{$pid});
3021: }
1.176 albertel 3022: }
1.165 albertel 3023: &status("Finished Handling child death");
1.1 albertel 3024: }
3025:
3026: sub HUNTSMAN { # signal handler for SIGINT
1.165 albertel 3027: &status("Killing children (INT)");
1.1 albertel 3028: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
3029: kill 'INT' => keys %children;
1.59 www 3030: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 3031: my $execdir=$perlvar{'lonDaemons'};
3032: unlink("$execdir/logs/lond.pid");
1.190 albertel 3033: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165 albertel 3034: &status("Done killing children");
1.1 albertel 3035: exit; # clean up with dignity
3036: }
3037:
3038: sub HUPSMAN { # signal handler for SIGHUP
3039: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.165 albertel 3040: &status("Killing children for restart (HUP)");
1.1 albertel 3041: kill 'INT' => keys %children;
1.59 www 3042: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190 albertel 3043: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134 albertel 3044: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 3045: unlink("$execdir/logs/lond.pid");
1.165 albertel 3046: &status("Restarting self (HUP)");
1.1 albertel 3047: exec("$execdir/lond"); # here we go again
3048: }
3049:
1.144 foxr 3050: #
1.148 foxr 3051: # Kill off hashes that describe the host table prior to re-reading it.
3052: # Hashes affected are:
1.200 matthew 3053: # %hostid, %hostdom %hostip %hostdns.
1.148 foxr 3054: #
3055: sub KillHostHashes {
3056: foreach my $key (keys %hostid) {
3057: delete $hostid{$key};
3058: }
3059: foreach my $key (keys %hostdom) {
3060: delete $hostdom{$key};
3061: }
3062: foreach my $key (keys %hostip) {
3063: delete $hostip{$key};
3064: }
1.200 matthew 3065: foreach my $key (keys %hostdns) {
3066: delete $hostdns{$key};
3067: }
1.148 foxr 3068: }
3069: #
3070: # Read in the host table from file and distribute it into the various hashes:
3071: #
3072: # - %hostid - Indexed by IP, the loncapa hostname.
3073: # - %hostdom - Indexed by loncapa hostname, the domain.
3074: # - %hostip - Indexed by hostid, the Ip address of the host.
3075: sub ReadHostTable {
3076:
3077: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200 matthew 3078: my $myloncapaname = $perlvar{'lonHostID'};
3079: Debug("My loncapa name is : $myloncapaname");
1.148 foxr 3080: while (my $configline=<CONFIG>) {
1.178 foxr 3081: if (!($configline =~ /^\s*\#/)) {
3082: my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
3083: chomp($ip); $ip=~s/\D+$//;
1.200 matthew 3084: $hostid{$ip}=$id; # LonCAPA name of host by IP.
3085: $hostdom{$id}=$domain; # LonCAPA domain name of host.
3086: $hostip{$id}=$ip; # IP address of host.
3087: $hostdns{$name} = $id; # LonCAPA name of host by DNS.
3088:
3089: if ($id eq $perlvar{'lonHostID'}) {
3090: Debug("Found me in the host table: $name");
3091: $thisserver=$name;
3092: }
1.178 foxr 3093: }
1.148 foxr 3094: }
3095: close(CONFIG);
3096: }
3097: #
3098: # Reload the Apache daemon's state.
1.150 foxr 3099: # This is done by invoking /home/httpd/perl/apachereload
3100: # a setuid perl script that can be root for us to do this job.
1.148 foxr 3101: #
3102: sub ReloadApache {
1.150 foxr 3103: my $execdir = $perlvar{'lonDaemons'};
3104: my $script = $execdir."/apachereload";
3105: system($script);
1.148 foxr 3106: }
3107:
3108: #
1.144 foxr 3109: # Called in response to a USR2 signal.
3110: # - Reread hosts.tab
3111: # - All children connected to hosts that were removed from hosts.tab
3112: # are killed via SIGINT
3113: # - All children connected to previously existing hosts are sent SIGUSR1
3114: # - Our internal hosts hash is updated to reflect the new contents of
3115: # hosts.tab causing connections from hosts added to hosts.tab to
3116: # now be honored.
3117: #
3118: sub UpdateHosts {
1.165 albertel 3119: &status("Reload hosts.tab");
1.147 foxr 3120: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 3121: #
3122: # The %children hash has the set of IP's we currently have children
3123: # on. These need to be matched against records in the hosts.tab
3124: # Any ip's no longer in the table get killed off they correspond to
3125: # either dropped or changed hosts. Note that the re-read of the table
3126: # will take care of new and changed hosts as connections come into being.
3127:
3128:
3129: KillHostHashes;
3130: ReadHostTable;
3131:
3132: foreach my $child (keys %children) {
3133: my $childip = $children{$child};
3134: if(!$hostid{$childip}) {
1.149 foxr 3135: logthis('<font color="blue"> UpdateHosts killing child '
3136: ." $child for ip $childip </font>");
1.148 foxr 3137: kill('INT', $child);
1.149 foxr 3138: } else {
3139: logthis('<font color="green"> keeping child for ip '
3140: ." $childip (pid=$child) </font>");
1.148 foxr 3141: }
3142: }
3143: ReloadApache;
1.165 albertel 3144: &status("Finished reloading hosts.tab");
1.144 foxr 3145: }
3146:
1.148 foxr 3147:
1.57 www 3148: sub checkchildren {
1.165 albertel 3149: &status("Checking on the children (sending signals)");
1.57 www 3150: &initnewstatus();
3151: &logstatus();
3152: &logthis('Going to check on the children');
1.134 albertel 3153: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 3154: foreach (sort keys %children) {
1.57 www 3155: sleep 1;
3156: unless (kill 'USR1' => $_) {
3157: &logthis ('Child '.$_.' is dead');
3158: &logstatus($$.' is dead');
3159: }
1.61 harris41 3160: }
1.63 www 3161: sleep 5;
1.212 foxr 3162: $SIG{ALRM} = sub { Debug("timeout");
3163: die "timeout"; };
1.113 albertel 3164: $SIG{__DIE__} = 'DEFAULT';
1.165 albertel 3165: &status("Checking on the children (waiting for reports)");
1.63 www 3166: foreach (sort keys %children) {
3167: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 3168: eval {
3169: alarm(300);
1.63 www 3170: &logthis('Child '.$_.' did not respond');
1.67 albertel 3171: kill 9 => $_;
1.131 albertel 3172: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
3173: #$subj="LON: $currenthostid killed lond process $_";
3174: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
3175: #$execdir=$perlvar{'lonDaemons'};
3176: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.113 albertel 3177: alarm(0);
3178: }
1.63 www 3179: }
3180: }
1.113 albertel 3181: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 3182: $SIG{__DIE__} = \&catchexception;
1.165 albertel 3183: &status("Finished checking children");
1.57 www 3184: }
3185:
1.1 albertel 3186: # --------------------------------------------------------------------- Logging
3187:
3188: sub logthis {
3189: my $message=shift;
3190: my $execdir=$perlvar{'lonDaemons'};
3191: my $fh=IO::File->new(">>$execdir/logs/lond.log");
3192: my $now=time;
3193: my $local=localtime($now);
1.58 www 3194: $lastlog=$local.': '.$message;
1.1 albertel 3195: print $fh "$local ($$): $message\n";
3196: }
3197:
1.77 foxr 3198: # ------------------------- Conditional log if $DEBUG true.
3199: sub Debug {
3200: my $message = shift;
3201: if($DEBUG) {
3202: &logthis($message);
3203: }
3204: }
1.161 foxr 3205:
3206: #
3207: # Sub to do replies to client.. this gives a hook for some
3208: # debug tracing too:
3209: # Parameters:
3210: # fd - File open on client.
3211: # reply - Text to send to client.
3212: # request - Original request from client.
3213: #
3214: sub Reply {
1.192 foxr 3215: my ($fd, $reply, $request) = @_;
1.161 foxr 3216: print $fd $reply;
3217: Debug("Request was $request Reply was $reply");
3218:
1.212 foxr 3219: $Transactions++;
3220:
3221:
3222: }
3223:
3224:
3225: #
3226: # Sub to report a failure.
3227: # This function:
3228: # - Increments the failure statistic counters.
3229: # - Invokes Reply to send the error message to the client.
3230: # Parameters:
3231: # fd - File descriptor open on the client
3232: # reply - Reply text to emit.
3233: # request - The original request message (used by Reply
3234: # to debug if that's enabled.
3235: # Implicit outputs:
3236: # $Failures- The number of failures is incremented.
3237: # Reply (invoked here) sends a message to the
3238: # client:
3239: #
3240: sub Failure {
3241: my $fd = shift;
3242: my $reply = shift;
3243: my $request = shift;
3244:
3245: $Failures++;
3246: Reply($fd, $reply, $request); # That's simple eh?
1.161 foxr 3247: }
1.57 www 3248: # ------------------------------------------------------------------ Log status
3249:
3250: sub logstatus {
1.178 foxr 3251: &status("Doing logging");
3252: my $docdir=$perlvar{'lonDocRoot'};
3253: {
3254: my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
1.200 matthew 3255: print $fh $$."\t".$clientname."\t".$currenthostid."\t"
3256: .$status."\t".$lastlog."\t $keymode\n";
1.178 foxr 3257: $fh->close();
3258: }
3259: &status("Finished londstatus.txt");
3260: {
3261: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200 matthew 3262: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178 foxr 3263: $fh->close();
3264: }
3265: &status("Finished logging");
1.57 www 3266: }
3267:
3268: sub initnewstatus {
3269: my $docdir=$perlvar{'lonDocRoot'};
3270: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
3271: my $now=time;
3272: my $local=localtime($now);
3273: print $fh "LOND status $local - parent $$\n\n";
1.64 www 3274: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 3275: while (my $filename=readdir(DIR)) {
1.64 www 3276: unlink("$docdir/lon-status/londchld/$filename");
3277: }
3278: closedir(DIR);
1.57 www 3279: }
3280:
3281: # -------------------------------------------------------------- Status setting
3282:
3283: sub status {
3284: my $what=shift;
3285: my $now=time;
3286: my $local=localtime($now);
1.178 foxr 3287: $status=$local.': '.$what;
3288: $0='lond: '.$what.' '.$local;
1.57 www 3289: }
1.11 www 3290:
3291: # -------------------------------------------------------- Escape Special Chars
3292:
3293: sub escape {
3294: my $str=shift;
3295: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
3296: return $str;
3297: }
3298:
3299: # ----------------------------------------------------- Un-Escape Special Chars
3300:
3301: sub unescape {
3302: my $str=shift;
3303: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
3304: return $str;
3305: }
3306:
1.1 albertel 3307: # ----------------------------------------------------------- Send USR1 to lonc
3308:
3309: sub reconlonc {
3310: my $peerfile=shift;
3311: &logthis("Trying to reconnect for $peerfile");
3312: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
3313: if (my $fh=IO::File->new("$loncfile")) {
3314: my $loncpid=<$fh>;
3315: chomp($loncpid);
3316: if (kill 0 => $loncpid) {
3317: &logthis("lonc at pid $loncpid responding, sending USR1");
3318: kill USR1 => $loncpid;
3319: } else {
1.9 www 3320: &logthis(
1.190 albertel 3321: "<font color='red'>CRITICAL: "
1.9 www 3322: ."lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 3323: }
3324: } else {
1.190 albertel 3325: &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1 albertel 3326: }
3327: }
3328:
3329: # -------------------------------------------------- Non-critical communication
1.11 www 3330:
1.1 albertel 3331: sub subreply {
3332: my ($cmd,$server)=@_;
3333: my $peerfile="$perlvar{'lonSockDir'}/$server";
3334: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
3335: Type => SOCK_STREAM,
3336: Timeout => 10)
3337: or return "con_lost";
3338: print $sclient "$cmd\n";
3339: my $answer=<$sclient>;
3340: chomp($answer);
3341: if (!$answer) { $answer="con_lost"; }
3342: return $answer;
3343: }
3344:
3345: sub reply {
3346: my ($cmd,$server)=@_;
3347: my $answer;
1.115 albertel 3348: if ($server ne $currenthostid) {
1.1 albertel 3349: $answer=subreply($cmd,$server);
3350: if ($answer eq 'con_lost') {
3351: $answer=subreply("ping",$server);
3352: if ($answer ne $server) {
1.115 albertel 3353: &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1 albertel 3354: &reconlonc("$perlvar{'lonSockDir'}/$server");
3355: }
3356: $answer=subreply($cmd,$server);
3357: }
3358: } else {
3359: $answer='self_reply';
3360: }
3361: return $answer;
3362: }
3363:
1.13 www 3364: # -------------------------------------------------------------- Talk to lonsql
3365:
1.12 harris41 3366: sub sqlreply {
3367: my ($cmd)=@_;
3368: my $answer=subsqlreply($cmd);
3369: if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
3370: return $answer;
3371: }
3372:
3373: sub subsqlreply {
3374: my ($cmd)=@_;
3375: my $unixsock="mysqlsock";
3376: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
3377: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
3378: Type => SOCK_STREAM,
3379: Timeout => 10)
3380: or return "con_lost";
3381: print $sclient "$cmd\n";
3382: my $answer=<$sclient>;
3383: chomp($answer);
3384: if (!$answer) { $answer="con_lost"; }
3385: return $answer;
3386: }
3387:
1.1 albertel 3388: # -------------------------------------------- Return path to profile directory
1.11 www 3389:
1.1 albertel 3390: sub propath {
3391: my ($udom,$uname)=@_;
3392: $udom=~s/\W//g;
3393: $uname=~s/\W//g;
1.16 www 3394: my $subdir=$uname.'__';
1.1 albertel 3395: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3396: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
3397: return $proname;
3398: }
3399:
3400: # --------------------------------------- Is this the home server of an author?
1.11 www 3401:
1.1 albertel 3402: sub ishome {
3403: my $author=shift;
3404: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3405: my ($udom,$uname)=split(/\//,$author);
3406: my $proname=propath($udom,$uname);
3407: if (-e $proname) {
3408: return 'owner';
3409: } else {
3410: return 'not_owner';
3411: }
3412: }
3413:
3414: # ======================================================= Continue main program
3415: # ---------------------------------------------------- Fork once and dissociate
3416:
1.134 albertel 3417: my $fpid=fork;
1.1 albertel 3418: exit if $fpid;
1.29 harris41 3419: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 3420:
1.29 harris41 3421: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 3422:
3423: # ------------------------------------------------------- Write our PID on disk
3424:
1.134 albertel 3425: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 3426: open (PIDSAVE,">$execdir/logs/lond.pid");
3427: print PIDSAVE "$$\n";
3428: close(PIDSAVE);
1.190 albertel 3429: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57 www 3430: &status('Starting');
1.1 albertel 3431:
1.106 foxr 3432:
1.1 albertel 3433:
3434: # ----------------------------------------------------- Install signal handlers
3435:
1.57 www 3436:
1.1 albertel 3437: $SIG{CHLD} = \&REAPER;
3438: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
3439: $SIG{HUP} = \&HUPSMAN;
1.57 www 3440: $SIG{USR1} = \&checkchildren;
1.144 foxr 3441: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 3442:
1.148 foxr 3443: # Read the host hashes:
3444:
3445: ReadHostTable;
1.106 foxr 3446:
3447: # --------------------------------------------------------------
3448: # Accept connections. When a connection comes in, it is validated
3449: # and if good, a child process is created to process transactions
3450: # along the connection.
3451:
1.1 albertel 3452: while (1) {
1.165 albertel 3453: &status('Starting accept');
1.106 foxr 3454: $client = $server->accept() or next;
1.165 albertel 3455: &status('Accepted '.$client.' off to spawn');
1.106 foxr 3456: make_new_child($client);
1.165 albertel 3457: &status('Finished spawning');
1.1 albertel 3458: }
3459:
1.212 foxr 3460: sub make_new_child {
3461: my $pid;
3462: # my $cipher; # Now global
3463: my $sigset;
1.178 foxr 3464:
1.212 foxr 3465: $client = shift;
3466: &status('Starting new child '.$client);
3467: &logthis('<font color="green"> Attempting to start child ('.$client.
3468: ")</font>");
3469: # block signal for fork
3470: $sigset = POSIX::SigSet->new(SIGINT);
3471: sigprocmask(SIG_BLOCK, $sigset)
3472: or die "Can't block SIGINT for fork: $!\n";
1.178 foxr 3473:
1.212 foxr 3474: die "fork: $!" unless defined ($pid = fork);
1.178 foxr 3475:
1.212 foxr 3476: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
3477: # connection liveness.
1.178 foxr 3478:
1.212 foxr 3479: #
3480: # Figure out who we're talking to so we can record the peer in
3481: # the pid hash.
3482: #
3483: my $caller = getpeername($client);
3484: my ($port,$iaddr);
3485: if (defined($caller) && length($caller) > 0) {
3486: ($port,$iaddr)=unpack_sockaddr_in($caller);
3487: } else {
3488: &logthis("Unable to determine who caller was, getpeername returned nothing");
3489: }
3490: if (defined($iaddr)) {
3491: $clientip = inet_ntoa($iaddr);
3492: Debug("Connected with $clientip");
3493: $clientdns = gethostbyaddr($iaddr, AF_INET);
3494: Debug("Connected with $clientdns by name");
3495: } else {
3496: &logthis("Unable to determine clientip");
3497: $clientip='Unavailable';
3498: }
3499:
3500: if ($pid) {
3501: # Parent records the child's birth and returns.
3502: sigprocmask(SIG_UNBLOCK, $sigset)
3503: or die "Can't unblock SIGINT for fork: $!\n";
3504: $children{$pid} = $clientip;
3505: &status('Started child '.$pid);
3506: return;
3507: } else {
3508: # Child can *not* return from this subroutine.
3509: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
3510: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
3511: #don't get intercepted
3512: $SIG{USR1}= \&logstatus;
3513: $SIG{ALRM}= \&timeout;
3514: $lastlog='Forked ';
3515: $status='Forked';
1.178 foxr 3516:
1.212 foxr 3517: # unblock signals
3518: sigprocmask(SIG_UNBLOCK, $sigset)
3519: or die "Can't unblock SIGINT for fork: $!\n";
1.178 foxr 3520:
1.212 foxr 3521: # my $tmpsnum=0; # Now global
3522: #---------------------------------------------------- kerberos 5 initialization
3523: &Authen::Krb5::init_context();
3524: &Authen::Krb5::init_ets();
1.209 albertel 3525:
1.212 foxr 3526: &status('Accepted connection');
3527: # =============================================================================
3528: # do something with the connection
3529: # -----------------------------------------------------------------------------
3530: # see if we know client and 'check' for spoof IP by ineffective challenge
1.178 foxr 3531:
1.212 foxr 3532: ReadManagerTable; # May also be a manager!!
3533:
3534: my $clientrec=($hostid{$clientip} ne undef);
3535: my $ismanager=($managers{$clientip} ne undef);
3536: $clientname = "[unknonwn]";
3537: if($clientrec) { # Establish client type.
3538: $ConnectionType = "client";
3539: $clientname = $hostid{$clientip};
3540: if($ismanager) {
3541: $ConnectionType = "both";
3542: }
3543: } else {
3544: $ConnectionType = "manager";
3545: $clientname = $managers{$clientip};
3546: }
3547: my $clientok;
1.178 foxr 3548:
1.212 foxr 3549: if ($clientrec || $ismanager) {
3550: &status("Waiting for init from $clientip $clientname");
3551: &logthis('<font color="yellow">INFO: Connection, '.
3552: $clientip.
3553: " ($clientname) connection type = $ConnectionType </font>" );
3554: &status("Connecting $clientip ($clientname))");
3555: my $remotereq=<$client>;
3556: chomp($remotereq);
3557: Debug("Got init: $remotereq");
3558: my $inikeyword = split(/:/, $remotereq);
3559: if ($remotereq =~ /^init/) {
3560: &sethost("sethost:$perlvar{'lonHostID'}");
3561: #
3562: # If the remote is attempting a local init... give that a try:
3563: #
3564: my ($i, $inittype) = split(/:/, $remotereq);
1.209 albertel 3565:
1.212 foxr 3566: # If the connection type is ssl, but I didn't get my
3567: # certificate files yet, then I'll drop back to
3568: # insecure (if allowed).
3569:
3570: if($inittype eq "ssl") {
3571: my ($ca, $cert) = lonssl::CertificateFile;
3572: my $kfile = lonssl::KeyFile;
3573: if((!$ca) ||
3574: (!$cert) ||
3575: (!$kfile)) {
3576: $inittype = ""; # This forces insecure attempt.
3577: &logthis("<font color=\"blue\"> Certificates not "
3578: ."installed -- trying insecure auth</font>");
1.178 foxr 3579: }
1.212 foxr 3580: else { # SSL certificates are in place so
3581: } # Leave the inittype alone.
3582: }
3583:
3584: if($inittype eq "local") {
3585: my $key = LocalConnection($client, $remotereq);
3586: if($key) {
3587: Debug("Got local key $key");
3588: $clientok = 1;
3589: my $cipherkey = pack("H32", $key);
3590: $cipher = new IDEA($cipherkey);
3591: print $client "ok:local\n";
3592: &logthis('<font color="green"'
3593: . "Successful local authentication </font>");
3594: $keymode = "local"
1.178 foxr 3595: } else {
1.212 foxr 3596: Debug("Failed to get local key");
3597: $clientok = 0;
3598: shutdown($client, 3);
3599: close $client;
1.178 foxr 3600: }
1.212 foxr 3601: } elsif ($inittype eq "ssl") {
3602: my $key = SSLConnection($client);
3603: if ($key) {
3604: $clientok = 1;
3605: my $cipherkey = pack("H32", $key);
3606: $cipher = new IDEA($cipherkey);
3607: &logthis('<font color="green">'
3608: ."Successfull ssl authentication with $clientname </font>");
3609: $keymode = "ssl";
3610:
1.178 foxr 3611: } else {
1.212 foxr 3612: $clientok = 0;
3613: close $client;
1.178 foxr 3614: }
1.212 foxr 3615:
3616: } else {
3617: my $ok = InsecureConnection($client);
3618: if($ok) {
3619: $clientok = 1;
3620: &logthis('<font color="green">'
3621: ."Successful insecure authentication with $clientname </font>");
3622: print $client "ok\n";
3623: $keymode = "insecure";
1.178 foxr 3624: } else {
1.212 foxr 3625: &logthis('<font color="yellow">'
3626: ."Attempted insecure connection disallowed </font>");
3627: close $client;
3628: $clientok = 0;
1.178 foxr 3629:
3630: }
3631: }
1.212 foxr 3632: } else {
3633: &logthis(
3634: "<font color='blue'>WARNING: "
3635: ."$clientip failed to initialize: >$remotereq< </font>");
3636: &status('No init '.$clientip);
3637: }
3638:
3639: } else {
3640: &logthis(
3641: "<font color='blue'>WARNING: Unknown client $clientip</font>");
3642: &status('Hung up on '.$clientip);
3643: }
3644:
3645: if ($clientok) {
3646: # ---------------- New known client connecting, could mean machine online again
3647:
3648: foreach my $id (keys(%hostip)) {
3649: if ($hostip{$id} ne $clientip ||
3650: $hostip{$currenthostid} eq $clientip) {
3651: # no need to try to do recon's to myself
3652: next;
3653: }
3654: &reconlonc("$perlvar{'lonSockDir'}/$id");
3655: }
3656: &logthis("<font color='green'>Established connection: $clientname</font>");
3657: &status('Will listen to '.$clientname);
3658: # ------------------------------------------------------------ Process requests
3659: my $keep_going = 1;
3660: my $user_input;
3661: while(($user_input = get_request) && $keep_going) {
3662: alarm(120);
3663: Debug("Main: Got $user_input\n");
3664: $keep_going = &process_request($user_input);
1.178 foxr 3665: alarm(0);
1.212 foxr 3666: &status('Listening to '.$clientname." ($keymode)");
1.161 foxr 3667: }
1.212 foxr 3668:
1.59 www 3669: # --------------------------------------------- client unknown or fishy, refuse
1.212 foxr 3670: } else {
1.161 foxr 3671: print $client "refused\n";
3672: $client->close();
1.190 albertel 3673: &logthis("<font color='blue'>WARNING: "
1.161 foxr 3674: ."Rejected client $clientip, closing connection</font>");
3675: }
1.212 foxr 3676: }
1.161 foxr 3677:
1.1 albertel 3678: # =============================================================================
1.161 foxr 3679:
1.190 albertel 3680: &logthis("<font color='red'>CRITICAL: "
1.161 foxr 3681: ."Disconnect from $clientip ($clientname)</font>");
3682:
3683:
3684: # this exit is VERY important, otherwise the child will become
3685: # a producer of more and more children, forking yourself into
3686: # process death.
3687: exit;
1.106 foxr 3688:
1.78 foxr 3689: }
3690:
3691:
3692: #
3693: # Checks to see if the input roleput request was to set
3694: # an author role. If so, invokes the lchtmldir script to set
3695: # up a correct public_html
3696: # Parameters:
3697: # request - The request sent to the rolesput subchunk.
3698: # We're looking for /domain/_au
3699: # domain - The domain in which the user is having roles doctored.
3700: # user - Name of the user for which the role is being put.
3701: # authtype - The authentication type associated with the user.
3702: #
3703: sub ManagePermissions
3704: {
1.192 foxr 3705:
3706: my ($request, $domain, $user, $authtype) = @_;
1.78 foxr 3707:
3708: # See if the request is of the form /$domain/_au
3709: if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
3710: my $execdir = $perlvar{'lonDaemons'};
3711: my $userhome= "/home/$user" ;
1.134 albertel 3712: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.78 foxr 3713: system("$execdir/lchtmldir $userhome $user $authtype");
3714: }
3715: }
3716: #
3717: # GetAuthType - Determines the authorization type of a user in a domain.
3718:
3719: # Returns the authorization type or nouser if there is no such user.
3720: #
3721: sub GetAuthType
3722: {
1.192 foxr 3723:
3724: my ($domain, $user) = @_;
1.78 foxr 3725:
1.79 foxr 3726: Debug("GetAuthType( $domain, $user ) \n");
1.78 foxr 3727: my $proname = &propath($domain, $user);
3728: my $passwdfile = "$proname/passwd";
3729: if( -e $passwdfile ) {
3730: my $pf = IO::File->new($passwdfile);
3731: my $realpassword = <$pf>;
3732: chomp($realpassword);
1.79 foxr 3733: Debug("Password info = $realpassword\n");
1.78 foxr 3734: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 3735: Debug("Authtype = $authtype, content = $contentpwd\n");
1.78 foxr 3736: my $availinfo = '';
1.91 albertel 3737: if($authtype eq 'krb4' or $authtype eq 'krb5') {
1.78 foxr 3738: $availinfo = $contentpwd;
3739: }
1.79 foxr 3740:
1.78 foxr 3741: return "$authtype:$availinfo";
3742: }
3743: else {
1.79 foxr 3744: Debug("Returning nouser");
1.78 foxr 3745: return "nouser";
3746: }
1.1 albertel 3747: }
3748:
1.84 albertel 3749: sub addline {
3750: my ($fname,$hostid,$ip,$newline)=@_;
3751: my $contents;
3752: my $found=0;
3753: my $expr='^'.$hostid.':'.$ip.':';
3754: $expr =~ s/\./\\\./g;
1.134 albertel 3755: my $sh;
1.84 albertel 3756: if ($sh=IO::File->new("$fname.subscription")) {
3757: while (my $subline=<$sh>) {
3758: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
3759: }
3760: $sh->close();
3761: }
3762: $sh=IO::File->new(">$fname.subscription");
3763: if ($contents) { print $sh $contents; }
3764: if ($newline) { print $sh $newline; }
3765: $sh->close();
3766: return $found;
1.86 www 3767: }
3768:
3769: sub getchat {
1.122 www 3770: my ($cdom,$cname,$udom,$uname)=@_;
1.87 www 3771: my %hash;
3772: my $proname=&propath($cdom,$cname);
3773: my @entries=();
1.88 albertel 3774: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
3775: &GDBM_READER(),0640)) {
3776: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
3777: untie %hash;
1.123 www 3778: }
1.124 www 3779: my @participants=();
1.134 albertel 3780: my $cutoff=time-60;
1.123 www 3781: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124 www 3782: &GDBM_WRCREAT(),0640)) {
3783: $hash{$uname.':'.$udom}=time;
1.123 www 3784: foreach (sort keys %hash) {
3785: if ($hash{$_}>$cutoff) {
1.124 www 3786: $participants[$#participants+1]='active_participant:'.$_;
1.123 www 3787: }
3788: }
3789: untie %hash;
1.86 www 3790: }
1.124 www 3791: return (@participants,@entries);
1.86 www 3792: }
3793:
3794: sub chatadd {
1.88 albertel 3795: my ($cdom,$cname,$newchat)=@_;
3796: my %hash;
3797: my $proname=&propath($cdom,$cname);
3798: my @entries=();
1.142 www 3799: my $time=time;
1.88 albertel 3800: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
3801: &GDBM_WRCREAT(),0640)) {
3802: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
3803: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
3804: my ($thentime,$idnum)=split(/\_/,$lastid);
3805: my $newid=$time.'_000000';
3806: if ($thentime==$time) {
3807: $idnum=~s/^0+//;
3808: $idnum++;
3809: $idnum=substr('000000'.$idnum,-6,6);
3810: $newid=$time.'_'.$idnum;
3811: }
3812: $hash{$newid}=$newchat;
3813: my $expired=$time-3600;
3814: foreach (keys %hash) {
3815: my ($thistime)=($_=~/(\d+)\_/);
3816: if ($thistime<$expired) {
1.89 www 3817: delete $hash{$_};
1.88 albertel 3818: }
3819: }
3820: untie %hash;
1.142 www 3821: }
3822: {
3823: my $hfh;
3824: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
3825: print $hfh "$time:".&unescape($newchat)."\n";
3826: }
1.86 www 3827: }
1.84 albertel 3828: }
3829:
3830: sub unsub {
3831: my ($fname,$clientip)=@_;
3832: my $result;
1.188 foxr 3833: my $unsubs = 0; # Number of successful unsubscribes:
3834:
3835:
3836: # An old way subscriptions were handled was to have a
3837: # subscription marker file:
3838:
3839: Debug("Attempting unlink of $fname.$clientname");
1.161 foxr 3840: if (unlink("$fname.$clientname")) {
1.188 foxr 3841: $unsubs++; # Successful unsub via marker file.
3842: }
3843:
3844: # The more modern way to do it is to have a subscription list
3845: # file:
3846:
1.84 albertel 3847: if (-e "$fname.subscription") {
1.161 foxr 3848: my $found=&addline($fname,$clientname,$clientip,'');
1.188 foxr 3849: if ($found) {
3850: $unsubs++;
3851: }
3852: }
3853:
3854: # If either or both of these mechanisms succeeded in unsubscribing a
3855: # resource we can return ok:
3856:
3857: if($unsubs) {
3858: $result = "ok\n";
1.84 albertel 3859: } else {
1.188 foxr 3860: $result = "not_subscribed\n";
1.84 albertel 3861: }
1.188 foxr 3862:
1.84 albertel 3863: return $result;
3864: }
3865:
1.101 www 3866: sub currentversion {
3867: my $fname=shift;
3868: my $version=-1;
3869: my $ulsdir='';
3870: if ($fname=~/^(.+)\/[^\/]+$/) {
3871: $ulsdir=$1;
3872: }
1.114 albertel 3873: my ($fnamere1,$fnamere2);
3874: # remove version if already specified
1.101 www 3875: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 3876: # get the bits that go before and after the version number
3877: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
3878: $fnamere1=$1;
3879: $fnamere2='.'.$2;
3880: }
1.101 www 3881: if (-e $fname) { $version=1; }
3882: if (-e $ulsdir) {
1.134 albertel 3883: if(-d $ulsdir) {
3884: if (opendir(LSDIR,$ulsdir)) {
3885: my $ulsfn;
3886: while ($ulsfn=readdir(LSDIR)) {
1.101 www 3887: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 3888: my $thisfile=$ulsdir.'/'.$ulsfn;
3889: unless (-l $thisfile) {
1.160 www 3890: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 3891: if ($1>$version) { $version=$1; }
3892: }
3893: }
3894: }
3895: closedir(LSDIR);
3896: $version++;
3897: }
3898: }
3899: }
3900: return $version;
1.101 www 3901: }
3902:
3903: sub thisversion {
3904: my $fname=shift;
3905: my $version=-1;
3906: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
3907: $version=$1;
3908: }
3909: return $version;
3910: }
3911:
1.84 albertel 3912: sub subscribe {
3913: my ($userinput,$clientip)=@_;
3914: my $result;
3915: my ($cmd,$fname)=split(/:/,$userinput);
3916: my $ownership=&ishome($fname);
3917: if ($ownership eq 'owner') {
1.101 www 3918: # explitly asking for the current version?
3919: unless (-e $fname) {
3920: my $currentversion=¤tversion($fname);
3921: if (&thisversion($fname)==$currentversion) {
3922: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
3923: my $root=$1;
3924: my $extension=$2;
3925: symlink($root.'.'.$extension,
3926: $root.'.'.$currentversion.'.'.$extension);
1.102 www 3927: unless ($extension=~/\.meta$/) {
3928: symlink($root.'.'.$extension.'.meta',
3929: $root.'.'.$currentversion.'.'.$extension.'.meta');
3930: }
1.101 www 3931: }
3932: }
3933: }
1.84 albertel 3934: if (-e $fname) {
3935: if (-d $fname) {
3936: $result="directory\n";
3937: } else {
1.161 foxr 3938: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 3939: my $now=time;
1.161 foxr 3940: my $found=&addline($fname,$clientname,$clientip,
3941: "$clientname:$clientip:$now\n");
1.84 albertel 3942: if ($found) { $result="$fname\n"; }
3943: # if they were subscribed to only meta data, delete that
3944: # subscription, when you subscribe to a file you also get
3945: # the metadata
3946: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
3947: $fname=~s/\/home\/httpd\/html\/res/raw/;
3948: $fname="http://$thisserver/".$fname;
3949: $result="$fname\n";
3950: }
3951: } else {
3952: $result="not_found\n";
3953: }
3954: } else {
3955: $result="rejected\n";
3956: }
3957: return $result;
3958: }
1.91 albertel 3959:
3960: sub make_passwd_file {
1.98 foxr 3961: my ($uname, $umode,$npass,$passfilename)=@_;
1.91 albertel 3962: my $result="ok\n";
3963: if ($umode eq 'krb4' or $umode eq 'krb5') {
3964: {
3965: my $pf = IO::File->new(">$passfilename");
3966: print $pf "$umode:$npass\n";
3967: }
3968: } elsif ($umode eq 'internal') {
3969: my $salt=time;
3970: $salt=substr($salt,6,2);
3971: my $ncpass=crypt($npass,$salt);
3972: {
3973: &Debug("Creating internal auth");
3974: my $pf = IO::File->new(">$passfilename");
3975: print $pf "internal:$ncpass\n";
3976: }
3977: } elsif ($umode eq 'localauth') {
3978: {
3979: my $pf = IO::File->new(">$passfilename");
3980: print $pf "localauth:$npass\n";
3981: }
3982: } elsif ($umode eq 'unix') {
3983: {
1.186 foxr 3984: #
3985: # Don't allow the creation of privileged accounts!!! that would
3986: # be real bad!!!
3987: #
3988: my $uid = getpwnam($uname);
3989: if((defined $uid) && ($uid == 0)) {
3990: &logthis(">>>Attempted to create privilged account blocked");
3991: return "no_priv_account_error\n";
3992: }
3993:
1.91 albertel 3994: my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
3995: {
3996: &Debug("Executing external: ".$execpath);
1.98 foxr 3997: &Debug("user = ".$uname.", Password =". $npass);
1.132 matthew 3998: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91 albertel 3999: print $se "$uname\n";
4000: print $se "$npass\n";
4001: print $se "$npass\n";
1.97 foxr 4002: }
4003: my $useraddok = $?;
4004: if($useraddok > 0) {
4005: &logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
1.91 albertel 4006: }
4007: my $pf = IO::File->new(">$passfilename");
4008: print $pf "unix:\n";
4009: }
4010: } elsif ($umode eq 'none') {
4011: {
4012: my $pf = IO::File->new(">$passfilename");
4013: print $pf "none:\n";
4014: }
4015: } else {
4016: $result="auth_mode_error\n";
4017: }
4018: return $result;
1.121 albertel 4019: }
4020:
4021: sub sethost {
4022: my ($remotereq) = @_;
4023: my (undef,$hostid)=split(/:/,$remotereq);
4024: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
4025: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200 matthew 4026: $currenthostid =$hostid;
1.121 albertel 4027: $currentdomainid=$hostdom{$hostid};
4028: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
4029: } else {
4030: &logthis("Requested host id $hostid not an alias of ".
4031: $perlvar{'lonHostID'}." refusing connection");
4032: return 'unable_to_set';
4033: }
4034: return 'ok';
4035: }
4036:
4037: sub version {
4038: my ($userinput)=@_;
4039: $remoteVERSION=(split(/:/,$userinput))[1];
4040: return "version:$VERSION";
1.127 albertel 4041: }
1.178 foxr 4042:
1.128 albertel 4043: #There is a copy of this in lonnet.pm
1.127 albertel 4044: sub userload {
4045: my $numusers=0;
4046: {
4047: opendir(LONIDS,$perlvar{'lonIDsDir'});
4048: my $filename;
4049: my $curtime=time;
4050: while ($filename=readdir(LONIDS)) {
4051: if ($filename eq '.' || $filename eq '..') {next;}
1.138 albertel 4052: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159 albertel 4053: if ($curtime-$mtime < 1800) { $numusers++; }
1.127 albertel 4054: }
4055: closedir(LONIDS);
4056: }
4057: my $userloadpercent=0;
4058: my $maxuserload=$perlvar{'lonUserLoadLim'};
4059: if ($maxuserload) {
1.129 albertel 4060: $userloadpercent=100*$numusers/$maxuserload;
1.127 albertel 4061: }
1.130 albertel 4062: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127 albertel 4063: return $userloadpercent;
1.91 albertel 4064: }
4065:
1.205 raeburn 4066: # Routines for serializing arrays and hashes (copies from lonnet)
4067:
4068: sub array2str {
4069: my (@array) = @_;
4070: my $result=&arrayref2str(\@array);
4071: $result=~s/^__ARRAY_REF__//;
4072: $result=~s/__END_ARRAY_REF__$//;
4073: return $result;
4074: }
4075:
4076: sub arrayref2str {
4077: my ($arrayref) = @_;
4078: my $result='__ARRAY_REF__';
4079: foreach my $elem (@$arrayref) {
4080: if(ref($elem) eq 'ARRAY') {
4081: $result.=&arrayref2str($elem).'&';
4082: } elsif(ref($elem) eq 'HASH') {
4083: $result.=&hashref2str($elem).'&';
4084: } elsif(ref($elem)) {
4085: #print("Got a ref of ".(ref($elem))." skipping.");
4086: } else {
4087: $result.=&escape($elem).'&';
4088: }
4089: }
4090: $result=~s/\&$//;
4091: $result .= '__END_ARRAY_REF__';
4092: return $result;
4093: }
4094:
4095: sub hash2str {
4096: my (%hash) = @_;
4097: my $result=&hashref2str(\%hash);
4098: $result=~s/^__HASH_REF__//;
4099: $result=~s/__END_HASH_REF__$//;
4100: return $result;
4101: }
4102:
4103: sub hashref2str {
4104: my ($hashref)=@_;
4105: my $result='__HASH_REF__';
4106: foreach (sort(keys(%$hashref))) {
4107: if (ref($_) eq 'ARRAY') {
4108: $result.=&arrayref2str($_).'=';
4109: } elsif (ref($_) eq 'HASH') {
4110: $result.=&hashref2str($_).'=';
4111: } elsif (ref($_)) {
4112: $result.='=';
4113: #print("Got a ref of ".(ref($_))." skipping.");
4114: } else {
4115: if ($_) {$result.=&escape($_).'=';} else { last; }
4116: }
4117:
4118: if(ref($hashref->{$_}) eq 'ARRAY') {
4119: $result.=&arrayref2str($hashref->{$_}).'&';
4120: } elsif(ref($hashref->{$_}) eq 'HASH') {
4121: $result.=&hashref2str($hashref->{$_}).'&';
4122: } elsif(ref($hashref->{$_})) {
4123: $result.='&';
4124: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
4125: } else {
4126: $result.=&escape($hashref->{$_}).'&';
4127: }
4128: }
4129: $result=~s/\&$//;
4130: $result .= '__END_HASH_REF__';
4131: return $result;
4132: }
1.200 matthew 4133:
1.61 harris41 4134: # ----------------------------------- POD (plain old documentation, CPAN style)
4135:
4136: =head1 NAME
4137:
4138: lond - "LON Daemon" Server (port "LOND" 5663)
4139:
4140: =head1 SYNOPSIS
4141:
1.74 harris41 4142: Usage: B<lond>
4143:
4144: Should only be run as user=www. This is a command-line script which
4145: is invoked by B<loncron>. There is no expectation that a typical user
4146: will manually start B<lond> from the command-line. (In other words,
4147: DO NOT START B<lond> YOURSELF.)
1.61 harris41 4148:
4149: =head1 DESCRIPTION
4150:
1.74 harris41 4151: There are two characteristics associated with the running of B<lond>,
4152: PROCESS MANAGEMENT (starting, stopping, handling child processes)
4153: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
4154: subscriptions, etc). These are described in two large
4155: sections below.
4156:
4157: B<PROCESS MANAGEMENT>
4158:
1.61 harris41 4159: Preforker - server who forks first. Runs as a daemon. HUPs.
4160: Uses IDEA encryption
4161:
1.74 harris41 4162: B<lond> forks off children processes that correspond to the other servers
4163: in the network. Management of these processes can be done at the
4164: parent process level or the child process level.
4165:
4166: B<logs/lond.log> is the location of log messages.
4167:
4168: The process management is now explained in terms of linux shell commands,
4169: subroutines internal to this code, and signal assignments:
4170:
4171: =over 4
4172:
4173: =item *
4174:
4175: PID is stored in B<logs/lond.pid>
4176:
4177: This is the process id number of the parent B<lond> process.
4178:
4179: =item *
4180:
4181: SIGTERM and SIGINT
4182:
4183: Parent signal assignment:
4184: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
4185:
4186: Child signal assignment:
4187: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
4188: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
4189: to restart a new child.)
4190:
4191: Command-line invocations:
4192: B<kill> B<-s> SIGTERM I<PID>
4193: B<kill> B<-s> SIGINT I<PID>
4194:
4195: Subroutine B<HUNTSMAN>:
4196: This is only invoked for the B<lond> parent I<PID>.
4197: This kills all the children, and then the parent.
4198: The B<lonc.pid> file is cleared.
4199:
4200: =item *
4201:
4202: SIGHUP
4203:
4204: Current bug:
4205: This signal can only be processed the first time
4206: on the parent process. Subsequent SIGHUP signals
4207: have no effect.
4208:
4209: Parent signal assignment:
4210: $SIG{HUP} = \&HUPSMAN;
4211:
4212: Child signal assignment:
4213: none (nothing happens)
4214:
4215: Command-line invocations:
4216: B<kill> B<-s> SIGHUP I<PID>
4217:
4218: Subroutine B<HUPSMAN>:
4219: This is only invoked for the B<lond> parent I<PID>,
4220: This kills all the children, and then the parent.
4221: The B<lond.pid> file is cleared.
4222:
4223: =item *
4224:
4225: SIGUSR1
4226:
4227: Parent signal assignment:
4228: $SIG{USR1} = \&USRMAN;
4229:
4230: Child signal assignment:
4231: $SIG{USR1}= \&logstatus;
4232:
4233: Command-line invocations:
4234: B<kill> B<-s> SIGUSR1 I<PID>
4235:
4236: Subroutine B<USRMAN>:
4237: When invoked for the B<lond> parent I<PID>,
4238: SIGUSR1 is sent to all the children, and the status of
4239: each connection is logged.
1.144 foxr 4240:
4241: =item *
4242:
4243: SIGUSR2
4244:
4245: Parent Signal assignment:
4246: $SIG{USR2} = \&UpdateHosts
4247:
4248: Child signal assignment:
4249: NONE
4250:
1.74 harris41 4251:
4252: =item *
4253:
4254: SIGCHLD
4255:
4256: Parent signal assignment:
4257: $SIG{CHLD} = \&REAPER;
4258:
4259: Child signal assignment:
4260: none
4261:
4262: Command-line invocations:
4263: B<kill> B<-s> SIGCHLD I<PID>
4264:
4265: Subroutine B<REAPER>:
4266: This is only invoked for the B<lond> parent I<PID>.
4267: Information pertaining to the child is removed.
4268: The socket port is cleaned up.
4269:
4270: =back
4271:
4272: B<SERVER-SIDE ACTIVITIES>
4273:
4274: Server-side information can be accepted in an encrypted or non-encrypted
4275: method.
4276:
4277: =over 4
4278:
4279: =item ping
4280:
4281: Query a client in the hosts.tab table; "Are you there?"
4282:
4283: =item pong
4284:
4285: Respond to a ping query.
4286:
4287: =item ekey
4288:
4289: Read in encrypted key, make cipher. Respond with a buildkey.
4290:
4291: =item load
4292:
4293: Respond with CPU load based on a computation upon /proc/loadavg.
4294:
4295: =item currentauth
4296:
4297: Reply with current authentication information (only over an
4298: encrypted channel).
4299:
4300: =item auth
4301:
4302: Only over an encrypted channel, reply as to whether a user's
4303: authentication information can be validated.
4304:
4305: =item passwd
4306:
4307: Allow for a password to be set.
4308:
4309: =item makeuser
4310:
4311: Make a user.
4312:
4313: =item passwd
4314:
4315: Allow for authentication mechanism and password to be changed.
4316:
4317: =item home
1.61 harris41 4318:
1.74 harris41 4319: Respond to a question "are you the home for a given user?"
4320:
4321: =item update
4322:
4323: Update contents of a subscribed resource.
4324:
4325: =item unsubscribe
4326:
4327: The server is unsubscribing from a resource.
4328:
4329: =item subscribe
4330:
4331: The server is subscribing to a resource.
4332:
4333: =item log
4334:
4335: Place in B<logs/lond.log>
4336:
4337: =item put
4338:
4339: stores hash in namespace
4340:
4341: =item rolesput
4342:
4343: put a role into a user's environment
4344:
4345: =item get
4346:
4347: returns hash with keys from array
4348: reference filled in from namespace
4349:
4350: =item eget
4351:
4352: returns hash with keys from array
4353: reference filled in from namesp (encrypts the return communication)
4354:
4355: =item rolesget
4356:
4357: get a role from a user's environment
4358:
4359: =item del
4360:
4361: deletes keys out of array from namespace
4362:
4363: =item keys
4364:
4365: returns namespace keys
4366:
4367: =item dump
4368:
4369: dumps the complete (or key matching regexp) namespace into a hash
4370:
4371: =item store
4372:
4373: stores hash permanently
4374: for this url; hashref needs to be given and should be a \%hashname; the
4375: remaining args aren't required and if they aren't passed or are '' they will
4376: be derived from the ENV
4377:
4378: =item restore
4379:
4380: returns a hash for a given url
4381:
4382: =item querysend
4383:
4384: Tells client about the lonsql process that has been launched in response
4385: to a sent query.
4386:
4387: =item queryreply
4388:
4389: Accept information from lonsql and make appropriate storage in temporary
4390: file space.
4391:
4392: =item idput
4393:
4394: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
4395: for each student, defined perhaps by the institutional Registrar.)
4396:
4397: =item idget
4398:
4399: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
4400: for each student, defined perhaps by the institutional Registrar.)
4401:
4402: =item tmpput
4403:
4404: Accept and store information in temporary space.
4405:
4406: =item tmpget
4407:
4408: Send along temporarily stored information.
4409:
4410: =item ls
4411:
4412: List part of a user's directory.
4413:
1.135 foxr 4414: =item pushtable
4415:
4416: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
4417: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
4418: must be restored manually in case of a problem with the new table file.
4419: pushtable requires that the request be encrypted and validated via
4420: ValidateManager. The form of the command is:
4421: enc:pushtable tablename <tablecontents> \n
4422: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
4423: cleartext newline.
4424:
1.74 harris41 4425: =item Hanging up (exit or init)
4426:
4427: What to do when a client tells the server that they (the client)
4428: are leaving the network.
4429:
4430: =item unknown command
4431:
4432: If B<lond> is sent an unknown command (not in the list above),
4433: it replys to the client "unknown_cmd".
1.135 foxr 4434:
1.74 harris41 4435:
4436: =item UNKNOWN CLIENT
4437:
4438: If the anti-spoofing algorithm cannot verify the client,
4439: the client is rejected (with a "refused" message sent
4440: to the client, and the connection is closed.
4441:
4442: =back
1.61 harris41 4443:
4444: =head1 PREREQUISITES
4445:
4446: IO::Socket
4447: IO::File
4448: Apache::File
4449: Symbol
4450: POSIX
4451: Crypt::IDEA
4452: LWP::UserAgent()
4453: GDBM_File
4454: Authen::Krb4
1.91 albertel 4455: Authen::Krb5
1.61 harris41 4456:
4457: =head1 COREQUISITES
4458:
4459: =head1 OSNAMES
4460:
4461: linux
4462:
4463: =head1 SCRIPT CATEGORIES
4464:
4465: Server/Process
4466:
4467: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>