Annotation of loncom/lond, revision 1.210
1.1 albertel 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60 www 4: #
1.210 ! albertel 5: # $Id: lond,v 1.209 2004/07/23 14:10:47 albertel Exp $
1.60 www 6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
1.167 foxr 13: # the Free Software Foundation; either version 2 of the License, or
1.60 www 14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
1.178 foxr 23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1.60 www 24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
1.161 foxr 27:
28:
1.60 www 29: # http://www.lon-capa.org/
30: #
1.54 harris41 31:
1.134 albertel 32: use strict;
1.80 harris41 33: use lib '/home/httpd/lib/perl/';
34: use LONCAPA::Configuration;
35:
1.1 albertel 36: use IO::Socket;
37: use IO::File;
1.126 albertel 38: #use Apache::File;
1.1 albertel 39: use Symbol;
40: use POSIX;
41: use Crypt::IDEA;
42: use LWP::UserAgent();
1.3 www 43: use GDBM_File;
44: use Authen::Krb4;
1.91 albertel 45: use Authen::Krb5;
1.49 albertel 46: use lib '/home/httpd/lib/perl/';
47: use localauth;
1.193 raeburn 48: use localenroll;
1.143 foxr 49: use File::Copy;
1.169 foxr 50: use LONCAPA::ConfigFileEdit;
1.200 matthew 51: use LONCAPA::lonlocal;
52: use LONCAPA::lonssl;
1.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.210 ! albertel 59: my $VERSION='$Revision: 1.209 $'; #' stupid emacs
1.121 albertel 60: my $remoteVERSION;
1.115 albertel 61: my $currenthostid;
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: #
151: my $Transactions; # Number of attempted transactions.
152: my $Failures; # Number of transcations failed.
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)) {
972: if (scalar @_) { # 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:
1019: if (($namespace =~/^nohist\_/) && (scalar @_ > 0)) {
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: }
1035: #---------------------------------------------------------------
1036: #
1037: # Getting, decoding and dispatching requests:
1038: #
1039:
1040: #
1041: # Get a Request:
1042: # Gets a Request message from the client. The transaction
1043: # is defined as a 'line' of text. We remove the new line
1044: # from the text line.
1045: #
1046: sub GetRequest {
1047: my $input = <$client>;
1048: chomp($input);
1049:
1050: Debug("Request = $input\n");
1051:
1052: &status('Processing '.$clientname.':'.$input);
1053:
1054: return $input;
1055: }
1056: #
1057: # Decipher encoded traffic
1058: # Parameters:
1059: # input - Encoded data.
1060: # Returns:
1061: # Decoded data or undef if encryption key was not yet negotiated.
1062: # Implicit input:
1063: # cipher - This global holds the negotiated encryption key.
1064: #
1065: sub Decipher {
1066: my ($input) = @_;
1067: my $output = '';
1068:
1069:
1070: if($cipher) {
1071: my($enc, $enclength, $encinput) = split(/:/, $input);
1072: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
1073: $output .=
1074: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
1075: }
1076: return substr($output, 0, $enclength);
1077: } else {
1078: return undef;
1079: }
1080: }
1081:
1082: #
1083: # Register a command processor. This function is invoked to register a sub
1084: # to process a request. Once registered, the ProcessRequest sub can automatically
1085: # dispatch requests to an appropriate sub, and do the top level validity checking
1086: # as well:
1087: # - Is the keyword recognized.
1088: # - Is the proper client type attempting the request.
1089: # - Is the request encrypted if it has to be.
1090: # Parameters:
1091: # $request_name - Name of the request being registered.
1092: # This is the command request that will match
1093: # against the hash keywords to lookup the information
1094: # associated with the dispatch information.
1095: # $procedure - Reference to a sub to call to process the request.
1096: # All subs get called as follows:
1097: # Procedure($cmd, $tail, $replyfd, $key)
1098: # $cmd - the actual keyword that invoked us.
1099: # $tail - the tail of the request that invoked us.
1100: # $replyfd- File descriptor connected to the client
1101: # $must_encode - True if the request must be encoded to be good.
1102: # $client_ok - True if it's ok for a client to request this.
1103: # $manager_ok - True if it's ok for a manager to request this.
1104: # Side effects:
1105: # - On success, the Dispatcher hash has an entry added for the key $RequestName
1106: # - On failure, the program will die as it's a bad internal bug to try to
1107: # register a duplicate command handler.
1108: #
1109: sub RegisterHandler {
1110: my ($request_name,
1111: $procedure,
1112: $must_encode,
1113: $client_ok,
1114: $manager_ok) = @_;
1115:
1116: # Don't allow duplication#
1117:
1118: if (defined $Dispatcher{$request_name}) {
1119: die "Attempting to define a duplicate request handler for $request_name\n";
1120: }
1121: # Build the client type mask:
1122:
1123: my $client_type_mask = 0;
1124: if($client_ok) {
1125: $client_type_mask |= $CLIENT_OK;
1126: }
1127: if($manager_ok) {
1128: $client_type_mask |= $MANAGER_OK;
1129: }
1130:
1131: # Enter the hash:
1132:
1133: my @entry = ($procedure, $must_encode, $client_type_mask);
1134:
1135: $Dispatcher{$request_name} = \@entry;
1136:
1137:
1138: }
1139:
1140:
1141: #------------------------------------------------------------------
1142:
1143:
1144:
1145:
1.141 foxr 1146: #
1.96 foxr 1147: # Convert an error return code from lcpasswd to a string value.
1148: #
1149: sub lcpasswdstrerror {
1150: my $ErrorCode = shift;
1.97 foxr 1151: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 1152: return "lcpasswd Unrecognized error return value ".$ErrorCode;
1153: } else {
1.98 foxr 1154: return $passwderrors[$ErrorCode];
1.96 foxr 1155: }
1156: }
1157:
1.97 foxr 1158: #
1159: # Convert an error return code from lcuseradd to a string value:
1160: #
1161: sub lcuseraddstrerror {
1162: my $ErrorCode = shift;
1163: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
1164: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
1165: } else {
1.98 foxr 1166: return $adderrors[$ErrorCode];
1.97 foxr 1167: }
1168: }
1169:
1.23 harris41 1170: # grabs exception and records it to log before exiting
1171: sub catchexception {
1.27 albertel 1172: my ($error)=@_;
1.25 www 1173: $SIG{'QUIT'}='DEFAULT';
1174: $SIG{__DIE__}='DEFAULT';
1.165 albertel 1175: &status("Catching exception");
1.190 albertel 1176: &logthis("<font color='red'>CRITICAL: "
1.134 albertel 1177: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27 albertel 1178: ."a crash with this error msg->[$error]</font>");
1.57 www 1179: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 1180: if ($client) { print $client "error: $error\n"; }
1.59 www 1181: $server->close();
1.27 albertel 1182: die($error);
1.23 harris41 1183: }
1184:
1.63 www 1185: sub timeout {
1.165 albertel 1186: &status("Handling Timeout");
1.190 albertel 1187: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63 www 1188: &catchexception('Timeout');
1189: }
1.22 harris41 1190: # -------------------------------- Set signal handlers to record abnormal exits
1191:
1192: $SIG{'QUIT'}=\&catchexception;
1193: $SIG{__DIE__}=\&catchexception;
1194:
1.81 matthew 1195: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 1196: &status("Read loncapa.conf and loncapa_apache.conf");
1197: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 1198: %perlvar=%{$perlvarref};
1.80 harris41 1199: undef $perlvarref;
1.19 www 1200:
1.35 harris41 1201: # ----------------------------- Make sure this process is running from user=www
1202: my $wwwid=getpwnam('www');
1203: if ($wwwid!=$<) {
1.134 albertel 1204: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
1205: my $subj="LON: $currenthostid User ID mismatch";
1.37 harris41 1206: system("echo 'User ID mismatch. lond must be run as user www.' |\
1.35 harris41 1207: mailto $emailto -s '$subj' > /dev/null");
1208: exit 1;
1209: }
1210:
1.19 www 1211: # --------------------------------------------- Check if other instance running
1212:
1213: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
1214:
1215: if (-e $pidfile) {
1216: my $lfh=IO::File->new("$pidfile");
1217: my $pide=<$lfh>;
1218: chomp($pide);
1.29 harris41 1219: if (kill 0 => $pide) { die "already running"; }
1.19 www 1220: }
1.1 albertel 1221:
1222: # ------------------------------------------------------------- Read hosts file
1223:
1224:
1225:
1226: # establish SERVER socket, bind and listen.
1227: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
1228: Type => SOCK_STREAM,
1229: Proto => 'tcp',
1230: Reuse => 1,
1231: Listen => 10 )
1.29 harris41 1232: or die "making socket: $@\n";
1.1 albertel 1233:
1234: # --------------------------------------------------------- Do global variables
1235:
1236: # global variables
1237:
1.134 albertel 1238: my %children = (); # keys are current child process IDs
1.1 albertel 1239:
1240: sub REAPER { # takes care of dead children
1241: $SIG{CHLD} = \&REAPER;
1.165 albertel 1242: &status("Handling child death");
1.178 foxr 1243: my $pid;
1244: do {
1245: $pid = waitpid(-1,&WNOHANG());
1246: if (defined($children{$pid})) {
1247: &logthis("Child $pid died");
1248: delete($children{$pid});
1.183 albertel 1249: } elsif ($pid > 0) {
1.178 foxr 1250: &logthis("Unknown Child $pid died");
1251: }
1252: } while ( $pid > 0 );
1253: foreach my $child (keys(%children)) {
1254: $pid = waitpid($child,&WNOHANG());
1255: if ($pid > 0) {
1256: &logthis("Child $child - $pid looks like we missed it's death");
1257: delete($children{$pid});
1258: }
1.176 albertel 1259: }
1.165 albertel 1260: &status("Finished Handling child death");
1.1 albertel 1261: }
1262:
1263: sub HUNTSMAN { # signal handler for SIGINT
1.165 albertel 1264: &status("Killing children (INT)");
1.1 albertel 1265: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1266: kill 'INT' => keys %children;
1.59 www 1267: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 1268: my $execdir=$perlvar{'lonDaemons'};
1269: unlink("$execdir/logs/lond.pid");
1.190 albertel 1270: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165 albertel 1271: &status("Done killing children");
1.1 albertel 1272: exit; # clean up with dignity
1273: }
1274:
1275: sub HUPSMAN { # signal handler for SIGHUP
1276: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.165 albertel 1277: &status("Killing children for restart (HUP)");
1.1 albertel 1278: kill 'INT' => keys %children;
1.59 www 1279: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190 albertel 1280: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134 albertel 1281: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 1282: unlink("$execdir/logs/lond.pid");
1.165 albertel 1283: &status("Restarting self (HUP)");
1.1 albertel 1284: exec("$execdir/lond"); # here we go again
1285: }
1286:
1.144 foxr 1287: #
1.148 foxr 1288: # Kill off hashes that describe the host table prior to re-reading it.
1289: # Hashes affected are:
1.200 matthew 1290: # %hostid, %hostdom %hostip %hostdns.
1.148 foxr 1291: #
1292: sub KillHostHashes {
1293: foreach my $key (keys %hostid) {
1294: delete $hostid{$key};
1295: }
1296: foreach my $key (keys %hostdom) {
1297: delete $hostdom{$key};
1298: }
1299: foreach my $key (keys %hostip) {
1300: delete $hostip{$key};
1301: }
1.200 matthew 1302: foreach my $key (keys %hostdns) {
1303: delete $hostdns{$key};
1304: }
1.148 foxr 1305: }
1306: #
1307: # Read in the host table from file and distribute it into the various hashes:
1308: #
1309: # - %hostid - Indexed by IP, the loncapa hostname.
1310: # - %hostdom - Indexed by loncapa hostname, the domain.
1311: # - %hostip - Indexed by hostid, the Ip address of the host.
1312: sub ReadHostTable {
1313:
1314: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200 matthew 1315: my $myloncapaname = $perlvar{'lonHostID'};
1316: Debug("My loncapa name is : $myloncapaname");
1.148 foxr 1317: while (my $configline=<CONFIG>) {
1.178 foxr 1318: if (!($configline =~ /^\s*\#/)) {
1319: my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
1320: chomp($ip); $ip=~s/\D+$//;
1.200 matthew 1321: $hostid{$ip}=$id; # LonCAPA name of host by IP.
1322: $hostdom{$id}=$domain; # LonCAPA domain name of host.
1323: $hostip{$id}=$ip; # IP address of host.
1324: $hostdns{$name} = $id; # LonCAPA name of host by DNS.
1325:
1326: if ($id eq $perlvar{'lonHostID'}) {
1327: Debug("Found me in the host table: $name");
1328: $thisserver=$name;
1329: }
1.178 foxr 1330: }
1.148 foxr 1331: }
1332: close(CONFIG);
1333: }
1334: #
1335: # Reload the Apache daemon's state.
1.150 foxr 1336: # This is done by invoking /home/httpd/perl/apachereload
1337: # a setuid perl script that can be root for us to do this job.
1.148 foxr 1338: #
1339: sub ReloadApache {
1.150 foxr 1340: my $execdir = $perlvar{'lonDaemons'};
1341: my $script = $execdir."/apachereload";
1342: system($script);
1.148 foxr 1343: }
1344:
1345: #
1.144 foxr 1346: # Called in response to a USR2 signal.
1347: # - Reread hosts.tab
1348: # - All children connected to hosts that were removed from hosts.tab
1349: # are killed via SIGINT
1350: # - All children connected to previously existing hosts are sent SIGUSR1
1351: # - Our internal hosts hash is updated to reflect the new contents of
1352: # hosts.tab causing connections from hosts added to hosts.tab to
1353: # now be honored.
1354: #
1355: sub UpdateHosts {
1.165 albertel 1356: &status("Reload hosts.tab");
1.147 foxr 1357: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 1358: #
1359: # The %children hash has the set of IP's we currently have children
1360: # on. These need to be matched against records in the hosts.tab
1361: # Any ip's no longer in the table get killed off they correspond to
1362: # either dropped or changed hosts. Note that the re-read of the table
1363: # will take care of new and changed hosts as connections come into being.
1364:
1365:
1366: KillHostHashes;
1367: ReadHostTable;
1368:
1369: foreach my $child (keys %children) {
1370: my $childip = $children{$child};
1371: if(!$hostid{$childip}) {
1.149 foxr 1372: logthis('<font color="blue"> UpdateHosts killing child '
1373: ." $child for ip $childip </font>");
1.148 foxr 1374: kill('INT', $child);
1.149 foxr 1375: } else {
1376: logthis('<font color="green"> keeping child for ip '
1377: ." $childip (pid=$child) </font>");
1.148 foxr 1378: }
1379: }
1380: ReloadApache;
1.165 albertel 1381: &status("Finished reloading hosts.tab");
1.144 foxr 1382: }
1383:
1.148 foxr 1384:
1.57 www 1385: sub checkchildren {
1.165 albertel 1386: &status("Checking on the children (sending signals)");
1.57 www 1387: &initnewstatus();
1388: &logstatus();
1389: &logthis('Going to check on the children');
1.134 albertel 1390: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 1391: foreach (sort keys %children) {
1.57 www 1392: sleep 1;
1393: unless (kill 'USR1' => $_) {
1394: &logthis ('Child '.$_.' is dead');
1395: &logstatus($$.' is dead');
1396: }
1.61 harris41 1397: }
1.63 www 1398: sleep 5;
1.113 albertel 1399: $SIG{ALRM} = sub { die "timeout" };
1400: $SIG{__DIE__} = 'DEFAULT';
1.165 albertel 1401: &status("Checking on the children (waiting for reports)");
1.63 www 1402: foreach (sort keys %children) {
1403: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 1404: eval {
1405: alarm(300);
1.63 www 1406: &logthis('Child '.$_.' did not respond');
1.67 albertel 1407: kill 9 => $_;
1.131 albertel 1408: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
1409: #$subj="LON: $currenthostid killed lond process $_";
1410: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
1411: #$execdir=$perlvar{'lonDaemons'};
1412: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.113 albertel 1413: alarm(0);
1414: }
1.63 www 1415: }
1416: }
1.113 albertel 1417: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 1418: $SIG{__DIE__} = \&catchexception;
1.165 albertel 1419: &status("Finished checking children");
1.57 www 1420: }
1421:
1.1 albertel 1422: # --------------------------------------------------------------------- Logging
1423:
1424: sub logthis {
1425: my $message=shift;
1426: my $execdir=$perlvar{'lonDaemons'};
1427: my $fh=IO::File->new(">>$execdir/logs/lond.log");
1428: my $now=time;
1429: my $local=localtime($now);
1.58 www 1430: $lastlog=$local.': '.$message;
1.1 albertel 1431: print $fh "$local ($$): $message\n";
1432: }
1433:
1.77 foxr 1434: # ------------------------- Conditional log if $DEBUG true.
1435: sub Debug {
1436: my $message = shift;
1437: if($DEBUG) {
1438: &logthis($message);
1439: }
1440: }
1.161 foxr 1441:
1442: #
1443: # Sub to do replies to client.. this gives a hook for some
1444: # debug tracing too:
1445: # Parameters:
1446: # fd - File open on client.
1447: # reply - Text to send to client.
1448: # request - Original request from client.
1449: #
1450: sub Reply {
1.192 foxr 1451:
1452: my ($fd, $reply, $request) = @_;
1.161 foxr 1453:
1454: print $fd $reply;
1455: Debug("Request was $request Reply was $reply");
1456:
1457: }
1.57 www 1458: # ------------------------------------------------------------------ Log status
1459:
1460: sub logstatus {
1.178 foxr 1461: &status("Doing logging");
1462: my $docdir=$perlvar{'lonDocRoot'};
1463: {
1464: my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
1.200 matthew 1465: print $fh $$."\t".$clientname."\t".$currenthostid."\t"
1466: .$status."\t".$lastlog."\t $keymode\n";
1.178 foxr 1467: $fh->close();
1468: }
1469: &status("Finished londstatus.txt");
1470: {
1471: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200 matthew 1472: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178 foxr 1473: $fh->close();
1474: }
1475: &status("Finished logging");
1.57 www 1476: }
1477:
1478: sub initnewstatus {
1479: my $docdir=$perlvar{'lonDocRoot'};
1480: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1481: my $now=time;
1482: my $local=localtime($now);
1483: print $fh "LOND status $local - parent $$\n\n";
1.64 www 1484: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 1485: while (my $filename=readdir(DIR)) {
1.64 www 1486: unlink("$docdir/lon-status/londchld/$filename");
1487: }
1488: closedir(DIR);
1.57 www 1489: }
1490:
1491: # -------------------------------------------------------------- Status setting
1492:
1493: sub status {
1494: my $what=shift;
1495: my $now=time;
1496: my $local=localtime($now);
1.178 foxr 1497: $status=$local.': '.$what;
1498: $0='lond: '.$what.' '.$local;
1.57 www 1499: }
1.11 www 1500:
1501: # -------------------------------------------------------- Escape Special Chars
1502:
1503: sub escape {
1504: my $str=shift;
1505: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
1506: return $str;
1507: }
1508:
1509: # ----------------------------------------------------- Un-Escape Special Chars
1510:
1511: sub unescape {
1512: my $str=shift;
1513: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1514: return $str;
1515: }
1516:
1.1 albertel 1517: # ----------------------------------------------------------- Send USR1 to lonc
1518:
1519: sub reconlonc {
1520: my $peerfile=shift;
1521: &logthis("Trying to reconnect for $peerfile");
1522: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1523: if (my $fh=IO::File->new("$loncfile")) {
1524: my $loncpid=<$fh>;
1525: chomp($loncpid);
1526: if (kill 0 => $loncpid) {
1527: &logthis("lonc at pid $loncpid responding, sending USR1");
1528: kill USR1 => $loncpid;
1529: } else {
1.9 www 1530: &logthis(
1.190 albertel 1531: "<font color='red'>CRITICAL: "
1.9 www 1532: ."lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 1533: }
1534: } else {
1.190 albertel 1535: &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1 albertel 1536: }
1537: }
1538:
1539: # -------------------------------------------------- Non-critical communication
1.11 www 1540:
1.1 albertel 1541: sub subreply {
1542: my ($cmd,$server)=@_;
1543: my $peerfile="$perlvar{'lonSockDir'}/$server";
1544: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
1545: Type => SOCK_STREAM,
1546: Timeout => 10)
1547: or return "con_lost";
1548: print $sclient "$cmd\n";
1549: my $answer=<$sclient>;
1550: chomp($answer);
1551: if (!$answer) { $answer="con_lost"; }
1552: return $answer;
1553: }
1554:
1555: sub reply {
1556: my ($cmd,$server)=@_;
1557: my $answer;
1.115 albertel 1558: if ($server ne $currenthostid) {
1.1 albertel 1559: $answer=subreply($cmd,$server);
1560: if ($answer eq 'con_lost') {
1561: $answer=subreply("ping",$server);
1562: if ($answer ne $server) {
1.115 albertel 1563: &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1 albertel 1564: &reconlonc("$perlvar{'lonSockDir'}/$server");
1565: }
1566: $answer=subreply($cmd,$server);
1567: }
1568: } else {
1569: $answer='self_reply';
1570: }
1571: return $answer;
1572: }
1573:
1.13 www 1574: # -------------------------------------------------------------- Talk to lonsql
1575:
1.12 harris41 1576: sub sqlreply {
1577: my ($cmd)=@_;
1578: my $answer=subsqlreply($cmd);
1579: if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
1580: return $answer;
1581: }
1582:
1583: sub subsqlreply {
1584: my ($cmd)=@_;
1585: my $unixsock="mysqlsock";
1586: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
1587: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
1588: Type => SOCK_STREAM,
1589: Timeout => 10)
1590: or return "con_lost";
1591: print $sclient "$cmd\n";
1592: my $answer=<$sclient>;
1593: chomp($answer);
1594: if (!$answer) { $answer="con_lost"; }
1595: return $answer;
1596: }
1597:
1.1 albertel 1598: # -------------------------------------------- Return path to profile directory
1.11 www 1599:
1.1 albertel 1600: sub propath {
1601: my ($udom,$uname)=@_;
1602: $udom=~s/\W//g;
1603: $uname=~s/\W//g;
1.16 www 1604: my $subdir=$uname.'__';
1.1 albertel 1605: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
1606: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
1607: return $proname;
1608: }
1609:
1610: # --------------------------------------- Is this the home server of an author?
1.11 www 1611:
1.1 albertel 1612: sub ishome {
1613: my $author=shift;
1614: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1615: my ($udom,$uname)=split(/\//,$author);
1616: my $proname=propath($udom,$uname);
1617: if (-e $proname) {
1618: return 'owner';
1619: } else {
1620: return 'not_owner';
1621: }
1622: }
1623:
1624: # ======================================================= Continue main program
1625: # ---------------------------------------------------- Fork once and dissociate
1626:
1.134 albertel 1627: my $fpid=fork;
1.1 albertel 1628: exit if $fpid;
1.29 harris41 1629: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 1630:
1.29 harris41 1631: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 1632:
1633: # ------------------------------------------------------- Write our PID on disk
1634:
1.134 albertel 1635: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 1636: open (PIDSAVE,">$execdir/logs/lond.pid");
1637: print PIDSAVE "$$\n";
1638: close(PIDSAVE);
1.190 albertel 1639: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57 www 1640: &status('Starting');
1.1 albertel 1641:
1.106 foxr 1642:
1.1 albertel 1643:
1644: # ----------------------------------------------------- Install signal handlers
1645:
1.57 www 1646:
1.1 albertel 1647: $SIG{CHLD} = \&REAPER;
1648: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
1649: $SIG{HUP} = \&HUPSMAN;
1.57 www 1650: $SIG{USR1} = \&checkchildren;
1.144 foxr 1651: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 1652:
1.148 foxr 1653: # Read the host hashes:
1654:
1655: ReadHostTable;
1.106 foxr 1656:
1657: # --------------------------------------------------------------
1658: # Accept connections. When a connection comes in, it is validated
1659: # and if good, a child process is created to process transactions
1660: # along the connection.
1661:
1.1 albertel 1662: while (1) {
1.165 albertel 1663: &status('Starting accept');
1.106 foxr 1664: $client = $server->accept() or next;
1.165 albertel 1665: &status('Accepted '.$client.' off to spawn');
1.106 foxr 1666: make_new_child($client);
1.165 albertel 1667: &status('Finished spawning');
1.1 albertel 1668: }
1669:
1670: sub make_new_child {
1671: my $pid;
1.207 foxr 1672: # my $cipher; # Now global
1.1 albertel 1673: my $sigset;
1.106 foxr 1674:
1675: $client = shift;
1.165 albertel 1676: &status('Starting new child '.$client);
1.161 foxr 1677: &logthis('<font color="green"> Attempting to start child ('.$client.
1678: ")</font>");
1.1 albertel 1679: # block signal for fork
1680: $sigset = POSIX::SigSet->new(SIGINT);
1681: sigprocmask(SIG_BLOCK, $sigset)
1.29 harris41 1682: or die "Can't block SIGINT for fork: $!\n";
1.134 albertel 1683:
1.29 harris41 1684: die "fork: $!" unless defined ($pid = fork);
1.148 foxr 1685:
1686: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
1687: # connection liveness.
1688:
1689: #
1690: # Figure out who we're talking to so we can record the peer in
1691: # the pid hash.
1692: #
1693: my $caller = getpeername($client);
1.180 albertel 1694: my ($port,$iaddr);
1695: if (defined($caller) && length($caller) > 0) {
1696: ($port,$iaddr)=unpack_sockaddr_in($caller);
1697: } else {
1698: &logthis("Unable to determine who caller was, getpeername returned nothing");
1699: }
1700: if (defined($iaddr)) {
1.200 matthew 1701: $clientip = inet_ntoa($iaddr);
1702: Debug("Connected with $clientip");
1703: $clientdns = gethostbyaddr($iaddr, AF_INET);
1704: Debug("Connected with $clientdns by name");
1.180 albertel 1705: } else {
1.200 matthew 1706: &logthis("Unable to determine clientip");
1.180 albertel 1707: $clientip='Unavailable';
1708: }
1.1 albertel 1709:
1710: if ($pid) {
1711: # Parent records the child's birth and returns.
1712: sigprocmask(SIG_UNBLOCK, $sigset)
1.29 harris41 1713: or die "Can't unblock SIGINT for fork: $!\n";
1.148 foxr 1714: $children{$pid} = $clientip;
1.57 www 1715: &status('Started child '.$pid);
1.1 albertel 1716: return;
1717: } else {
1718: # Child can *not* return from this subroutine.
1719: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
1.126 albertel 1720: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
1721: #don't get intercepted
1.57 www 1722: $SIG{USR1}= \&logstatus;
1.63 www 1723: $SIG{ALRM}= \&timeout;
1.57 www 1724: $lastlog='Forked ';
1725: $status='Forked';
1726:
1.1 albertel 1727: # unblock signals
1728: sigprocmask(SIG_UNBLOCK, $sigset)
1.29 harris41 1729: or die "Can't unblock SIGINT for fork: $!\n";
1.13 www 1730:
1.207 foxr 1731: # my $tmpsnum=0; # Now global
1.178 foxr 1732: #---------------------------------------------------- kerberos 5 initialization
1.91 albertel 1733: &Authen::Krb5::init_context();
1734: &Authen::Krb5::init_ets();
1735:
1.161 foxr 1736: &status('Accepted connection');
1.1 albertel 1737: # =============================================================================
1738: # do something with the connection
1739: # -----------------------------------------------------------------------------
1.200 matthew 1740: # see if we know client and 'check' for spoof IP by ineffective challenge
1.148 foxr 1741:
1.161 foxr 1742: ReadManagerTable; # May also be a manager!!
1743:
1744: my $clientrec=($hostid{$clientip} ne undef);
1745: my $ismanager=($managers{$clientip} ne undef);
1746: $clientname = "[unknonwn]";
1747: if($clientrec) { # Establish client type.
1748: $ConnectionType = "client";
1749: $clientname = $hostid{$clientip};
1750: if($ismanager) {
1751: $ConnectionType = "both";
1752: }
1753: } else {
1754: $ConnectionType = "manager";
1755: $clientname = $managers{$clientip};
1756: }
1757: my $clientok;
1.200 matthew 1758:
1.161 foxr 1759: if ($clientrec || $ismanager) {
1760: &status("Waiting for init from $clientip $clientname");
1761: &logthis('<font color="yellow">INFO: Connection, '.
1762: $clientip.
1763: " ($clientname) connection type = $ConnectionType </font>" );
1764: &status("Connecting $clientip ($clientname))");
1765: my $remotereq=<$client>;
1.200 matthew 1766: chomp($remotereq);
1767: Debug("Got init: $remotereq");
1768: my $inikeyword = split(/:/, $remotereq);
1.161 foxr 1769: if ($remotereq =~ /^init/) {
1770: &sethost("sethost:$perlvar{'lonHostID'}");
1.200 matthew 1771: #
1772: # If the remote is attempting a local init... give that a try:
1773: #
1774: my ($i, $inittype) = split(/:/, $remotereq);
1775:
1776: # If the connection type is ssl, but I didn't get my
1777: # certificate files yet, then I'll drop back to
1778: # insecure (if allowed).
1779:
1780: if($inittype eq "ssl") {
1781: my ($ca, $cert) = lonssl::CertificateFile;
1782: my $kfile = lonssl::KeyFile;
1783: if((!$ca) ||
1784: (!$cert) ||
1785: (!$kfile)) {
1786: $inittype = ""; # This forces insecure attempt.
1787: &logthis("<font color=\"blue\"> Certificates not "
1788: ."installed -- trying insecure auth</font>");
1789: }
1790: else { # SSL certificates are in place so
1791: } # Leave the inittype alone.
1792: }
1793:
1794: if($inittype eq "local") {
1795: my $key = LocalConnection($client, $remotereq);
1796: if($key) {
1797: Debug("Got local key $key");
1798: $clientok = 1;
1799: my $cipherkey = pack("H32", $key);
1800: $cipher = new IDEA($cipherkey);
1801: print $client "ok:local\n";
1802: &logthis('<font color="green"'
1803: . "Successful local authentication </font>");
1804: $keymode = "local"
1805: } else {
1806: Debug("Failed to get local key");
1807: $clientok = 0;
1808: shutdown($client, 3);
1809: close $client;
1810: }
1811: } elsif ($inittype eq "ssl") {
1812: my $key = SSLConnection($client);
1813: if ($key) {
1814: $clientok = 1;
1815: my $cipherkey = pack("H32", $key);
1816: $cipher = new IDEA($cipherkey);
1817: &logthis('<font color="green">'
1818: ."Successfull ssl authentication with $clientname </font>");
1819: $keymode = "ssl";
1820:
1821: } else {
1822: $clientok = 0;
1823: close $client;
1824: }
1825:
1.161 foxr 1826: } else {
1.200 matthew 1827: my $ok = InsecureConnection($client);
1828: if($ok) {
1829: $clientok = 1;
1830: &logthis('<font color="green">'
1831: ."Successful insecure authentication with $clientname </font>");
1832: print $client "ok\n";
1833: $keymode = "insecure";
1834: } else {
1835: &logthis('<font color="yellow">'
1836: ."Attempted insecure connection disallowed </font>");
1837: close $client;
1838: $clientok = 0;
1839:
1840: }
1.161 foxr 1841: }
1.2 www 1842: } else {
1.161 foxr 1843: &logthis(
1.190 albertel 1844: "<font color='blue'>WARNING: "
1.161 foxr 1845: ."$clientip failed to initialize: >$remotereq< </font>");
1846: &status('No init '.$clientip);
1847: }
1.200 matthew 1848:
1.161 foxr 1849: } else {
1850: &logthis(
1.190 albertel 1851: "<font color='blue'>WARNING: Unknown client $clientip</font>");
1.161 foxr 1852: &status('Hung up on '.$clientip);
1853: }
1.200 matthew 1854:
1.161 foxr 1855: if ($clientok) {
1.1 albertel 1856: # ---------------- New known client connecting, could mean machine online again
1.161 foxr 1857:
1858: foreach my $id (keys(%hostip)) {
1859: if ($hostip{$id} ne $clientip ||
1860: $hostip{$currenthostid} eq $clientip) {
1861: # no need to try to do recon's to myself
1862: next;
1.115 albertel 1863: }
1.161 foxr 1864: &reconlonc("$perlvar{'lonSockDir'}/$id");
1865: }
1.190 albertel 1866: &logthis("<font color='green'>Established connection: $clientname</font>");
1.161 foxr 1867: &status('Will listen to '.$clientname);
1.178 foxr 1868: # ------------------------------------------------------------ Process requests
1869: while (my $userinput=<$client>) {
1870: chomp($userinput);
1871: Debug("Request = $userinput\n");
1872: &status('Processing '.$clientname.': '.$userinput);
1873: my $wasenc=0;
1874: alarm(120);
1875: # ------------------------------------------------------------ See if encrypted
1876: if ($userinput =~ /^enc/) {
1877: if ($cipher) {
1878: my ($cmd,$cmdlength,$encinput)=split(/:/,$userinput);
1879: $userinput='';
1880: for (my $encidx=0;$encidx<length($encinput);$encidx+=16) {
1881: $userinput.=
1882: $cipher->decrypt(
1883: pack("H16",substr($encinput,$encidx,16))
1884: );
1885: }
1886: $userinput=substr($userinput,0,$cmdlength);
1887: $wasenc=1;
1888: }
1889: }
1890:
1891: # ------------------------------------------------------------- Normal commands
1892: # ------------------------------------------------------------------------ ping
1893: if ($userinput =~ /^ping/) { # client only
1894: if(isClient) {
1895: print $client "$currenthostid\n";
1896: } else {
1897: Reply($client, "refused\n", $userinput);
1898: }
1899: # ------------------------------------------------------------------------ pong
1900: }elsif ($userinput =~ /^pong/) { # client only
1901: if(isClient) {
1902: my $reply=&reply("ping",$clientname);
1903: print $client "$currenthostid:$reply\n";
1904: } else {
1905: Reply($client, "refused\n", $userinput);
1906: }
1907: # ------------------------------------------------------------------------ ekey
1908: } elsif ($userinput =~ /^ekey/) { # ok for both clients & mgrs
1909: my $buildkey=time.$$.int(rand 100000);
1910: $buildkey=~tr/1-6/A-F/;
1911: $buildkey=int(rand 100000).$buildkey.int(rand 100000);
1912: my $key=$currenthostid.$clientname;
1913: $key=~tr/a-z/A-Z/;
1914: $key=~tr/G-P/0-9/;
1915: $key=~tr/Q-Z/0-9/;
1916: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
1917: $key=substr($key,0,32);
1918: my $cipherkey=pack("H32",$key);
1919: $cipher=new IDEA $cipherkey;
1920: print $client "$buildkey\n";
1921: # ------------------------------------------------------------------------ load
1922: } elsif ($userinput =~ /^load/) { # client only
1923: if (isClient) {
1924: my $loadavg;
1925: {
1926: my $loadfile=IO::File->new('/proc/loadavg');
1927: $loadavg=<$loadfile>;
1928: }
1929: $loadavg =~ s/\s.*//g;
1930: my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
1931: print $client "$loadpercent\n";
1932: } else {
1933: Reply($client, "refused\n", $userinput);
1934:
1935: }
1936: # -------------------------------------------------------------------- userload
1937: } elsif ($userinput =~ /^userload/) { # client only
1938: if(isClient) {
1939: my $userloadpercent=&userload();
1940: print $client "$userloadpercent\n";
1941: } else {
1942: Reply($client, "refused\n", $userinput);
1943:
1944: }
1945: #
1946: # Transactions requiring encryption:
1947: #
1948: # ----------------------------------------------------------------- currentauth
1949: } elsif ($userinput =~ /^currentauth/) {
1950: if (($wasenc==1) && isClient) { # Encoded & client only.
1951: my ($cmd,$udom,$uname)=split(/:/,$userinput);
1952: my $result = GetAuthType($udom, $uname);
1953: if($result eq "nouser") {
1954: print $client "unknown_user\n";
1955: }
1956: else {
1957: print $client "$result\n"
1958: }
1959: } else {
1960: Reply($client, "refused\n", $userinput);
1961:
1962: }
1963: #--------------------------------------------------------------------- pushfile
1964: } elsif($userinput =~ /^pushfile/) { # encoded & manager.
1965: if(($wasenc == 1) && isManager) {
1966: my $cert = GetCertificate($userinput);
1967: if(ValidManager($cert)) {
1968: my $reply = PushFile($userinput);
1969: print $client "$reply\n";
1970: } else {
1971: print $client "refused\n";
1972: }
1973: } else {
1974: Reply($client, "refused\n", $userinput);
1975:
1976: }
1977: #--------------------------------------------------------------------- reinit
1978: } elsif($userinput =~ /^reinit/) { # Encoded and manager
1979: if (($wasenc == 1) && isManager) {
1980: my $cert = GetCertificate($userinput);
1981: if(ValidManager($cert)) {
1982: chomp($userinput);
1983: my $reply = ReinitProcess($userinput);
1984: print $client "$reply\n";
1985: } else {
1986: print $client "refused\n";
1987: }
1988: } else {
1989: Reply($client, "refused\n", $userinput);
1990: }
1991: #------------------------------------------------------------------------- edit
1992: } elsif ($userinput =~ /^edit/) { # encoded and manager:
1993: if(($wasenc ==1) && (isManager)) {
1994: my $cert = GetCertificate($userinput);
1995: if(ValidManager($cert)) {
1996: my($command, $filetype, $script) = split(/:/, $userinput);
1997: if (($filetype eq "hosts") || ($filetype eq "domain")) {
1998: if($script ne "") {
1999: Reply($client, EditFile($userinput));
2000: } else {
2001: Reply($client,"refused\n",$userinput);
2002: }
2003: } else {
2004: Reply($client,"refused\n",$userinput);
2005: }
2006: } else {
2007: Reply($client,"refused\n",$userinput);
2008: }
2009: } else {
2010: Reply($client,"refused\n",$userinput);
2011: }
2012: # ------------------------------------------------------------------------ auth
2013: } elsif ($userinput =~ /^auth/) { # Encoded and client only.
2014: if (($wasenc==1) && isClient) {
2015: my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
2016: chomp($upass);
2017: $upass=unescape($upass);
2018: my $proname=propath($udom,$uname);
2019: my $passfilename="$proname/passwd";
2020: if (-e $passfilename) {
2021: my $pf = IO::File->new($passfilename);
2022: my $realpasswd=<$pf>;
2023: chomp($realpasswd);
2024: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
2025: my $pwdcorrect=0;
2026: if ($howpwd eq 'internal') {
2027: &Debug("Internal auth");
2028: $pwdcorrect=
2029: (crypt($upass,$contentpwd) eq $contentpwd);
2030: } elsif ($howpwd eq 'unix') {
2031: &Debug("Unix auth");
2032: if((getpwnam($uname))[1] eq "") { #no such user!
2033: $pwdcorrect = 0;
2034: } else {
2035: $contentpwd=(getpwnam($uname))[1];
2036: my $pwauth_path="/usr/local/sbin/pwauth";
2037: unless ($contentpwd eq 'x') {
2038: $pwdcorrect=
2039: (crypt($upass,$contentpwd) eq
2040: $contentpwd);
2041: }
2042:
2043: elsif (-e $pwauth_path) {
2044: open PWAUTH, "|$pwauth_path" or
2045: die "Cannot invoke authentication";
2046: print PWAUTH "$uname\n$upass\n";
2047: close PWAUTH;
2048: $pwdcorrect=!$?;
2049: }
2050: }
2051: } elsif ($howpwd eq 'krb4') {
2052: my $null=pack("C",0);
2053: unless ($upass=~/$null/) {
2054: my $krb4_error = &Authen::Krb4::get_pw_in_tkt
2055: ($uname,"",$contentpwd,'krbtgt',
2056: $contentpwd,1,$upass);
2057: if (!$krb4_error) {
2058: $pwdcorrect = 1;
2059: } else {
2060: $pwdcorrect=0;
2061: # log error if it is not a bad password
2062: if ($krb4_error != 62) {
1.191 albertel 2063: &logthis('krb4:'.$uname.','.
1.178 foxr 2064: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
2065: }
2066: }
2067: }
2068: } elsif ($howpwd eq 'krb5') {
2069: my $null=pack("C",0);
2070: unless ($upass=~/$null/) {
2071: my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
2072: my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
2073: my $krbserver=&Authen::Krb5::parse_name($krbservice);
2074: my $credentials=&Authen::Krb5::cc_default();
2075: $credentials->initialize($krbclient);
2076: my $krbreturn =
2077: &Authen::Krb5::get_in_tkt_with_password(
2078: $krbclient,$krbserver,$upass,$credentials);
2079: # unless ($krbreturn) {
2080: # &logthis("Krb5 Error: ".
2081: # &Authen::Krb5::error());
2082: # }
2083: $pwdcorrect = ($krbreturn == 1);
2084: } else { $pwdcorrect=0; }
2085: } elsif ($howpwd eq 'localauth') {
2086: $pwdcorrect=&localauth::localauth($uname,$upass,
2087: $contentpwd);
2088: }
2089: if ($pwdcorrect) {
2090: print $client "authorized\n";
2091: } else {
2092: print $client "non_authorized\n";
2093: }
2094: } else {
2095: print $client "unknown_user\n";
2096: }
2097: } else {
2098: Reply($client, "refused\n", $userinput);
2099:
2100: }
2101: # ---------------------------------------------------------------------- passwd
2102: } elsif ($userinput =~ /^passwd/) { # encoded and client
2103: if (($wasenc==1) && isClient) {
2104: my
2105: ($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
2106: chomp($npass);
2107: $upass=&unescape($upass);
2108: $npass=&unescape($npass);
2109: &Debug("Trying to change password for $uname");
2110: my $proname=propath($udom,$uname);
2111: my $passfilename="$proname/passwd";
2112: if (-e $passfilename) {
2113: my $realpasswd;
2114: { my $pf = IO::File->new($passfilename);
2115: $realpasswd=<$pf>; }
2116: chomp($realpasswd);
2117: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
2118: if ($howpwd eq 'internal') {
2119: &Debug("internal auth");
2120: if (crypt($upass,$contentpwd) eq $contentpwd) {
2121: my $salt=time;
2122: $salt=substr($salt,6,2);
2123: my $ncpass=crypt($npass,$salt);
2124: {
2125: my $pf;
2126: if ($pf = IO::File->new(">$passfilename")) {
2127: print $pf "internal:$ncpass\n";
2128: &logthis("Result of password change for $uname: pwchange_success");
2129: print $client "ok\n";
2130: } else {
2131: &logthis("Unable to open $uname passwd to change password");
2132: print $client "non_authorized\n";
2133: }
2134: }
2135:
2136: } else {
2137: print $client "non_authorized\n";
2138: }
2139: } elsif ($howpwd eq 'unix') {
2140: # Unix means we have to access /etc/password
2141: # one way or another.
2142: # First: Make sure the current password is
2143: # correct
2144: &Debug("auth is unix");
2145: $contentpwd=(getpwnam($uname))[1];
2146: my $pwdcorrect = "0";
2147: my $pwauth_path="/usr/local/sbin/pwauth";
2148: unless ($contentpwd eq 'x') {
2149: $pwdcorrect=
2150: (crypt($upass,$contentpwd) eq $contentpwd);
2151: } elsif (-e $pwauth_path) {
2152: open PWAUTH, "|$pwauth_path" or
2153: die "Cannot invoke authentication";
2154: print PWAUTH "$uname\n$upass\n";
2155: close PWAUTH;
2156: &Debug("exited pwauth with $? ($uname,$upass) ");
2157: $pwdcorrect=($? == 0);
2158: }
2159: if ($pwdcorrect) {
2160: my $execdir=$perlvar{'lonDaemons'};
2161: &Debug("Opening lcpasswd pipeline");
2162: my $pf = IO::File->new("|$execdir/lcpasswd > $perlvar{'lonDaemons'}/logs/lcpasswd.log");
2163: print $pf "$uname\n$npass\n$npass\n";
2164: close $pf;
2165: my $err = $?;
2166: my $result = ($err>0 ? 'pwchange_failure'
2167: : 'ok');
2168: &logthis("Result of password change for $uname: ".
2169: &lcpasswdstrerror($?));
2170: print $client "$result\n";
2171: } else {
2172: print $client "non_authorized\n";
2173: }
2174: } else {
2175: print $client "auth_mode_error\n";
2176: }
2177: } else {
2178: print $client "unknown_user\n";
2179: }
2180: } else {
2181: Reply($client, "refused\n", $userinput);
2182:
2183: }
2184: # -------------------------------------------------------------------- makeuser
2185: } elsif ($userinput =~ /^makeuser/) { # encoded and client.
2186: &Debug("Make user received");
2187: my $oldumask=umask(0077);
2188: if (($wasenc==1) && isClient) {
2189: my
2190: ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
2191: &Debug("cmd =".$cmd." $udom =".$udom.
2192: " uname=".$uname);
2193: chomp($npass);
2194: $npass=&unescape($npass);
2195: my $proname=propath($udom,$uname);
2196: my $passfilename="$proname/passwd";
2197: &Debug("Password file created will be:".
2198: $passfilename);
2199: if (-e $passfilename) {
2200: print $client "already_exists\n";
2201: } elsif ($udom ne $currentdomainid) {
2202: print $client "not_right_domain\n";
2203: } else {
2204: my @fpparts=split(/\//,$proname);
2205: my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
2206: my $fperror='';
2207: for (my $i=3;$i<=$#fpparts;$i++) {
2208: $fpnow.='/'.$fpparts[$i];
2209: unless (-e $fpnow) {
2210: unless (mkdir($fpnow,0777)) {
2211: $fperror="error: ".($!+0)
2212: ." mkdir failed while attempting "
2213: ."makeuser";
2214: }
2215: }
2216: }
2217: unless ($fperror) {
2218: my $result=&make_passwd_file($uname, $umode,$npass,
2219: $passfilename);
2220: print $client $result;
2221: } else {
2222: print $client "$fperror\n";
2223: }
2224: }
2225: } else {
2226: Reply($client, "refused\n", $userinput);
2227:
2228: }
2229: umask($oldumask);
2230: # -------------------------------------------------------------- changeuserauth
2231: } elsif ($userinput =~ /^changeuserauth/) { # encoded & client
2232: &Debug("Changing authorization");
2233: if (($wasenc==1) && isClient) {
2234: my
2235: ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
2236: chomp($npass);
2237: &Debug("cmd = ".$cmd." domain= ".$udom.
2238: "uname =".$uname." umode= ".$umode);
2239: $npass=&unescape($npass);
2240: my $proname=&propath($udom,$uname);
2241: my $passfilename="$proname/passwd";
2242: if ($udom ne $currentdomainid) {
2243: print $client "not_right_domain\n";
2244: } else {
2245: my $result=&make_passwd_file($uname, $umode,$npass,
2246: $passfilename);
2247: print $client $result;
2248: }
2249: } else {
2250: Reply($client, "refused\n", $userinput);
2251:
2252: }
2253: # ------------------------------------------------------------------------ home
2254: } elsif ($userinput =~ /^home/) { # client clear or encoded
2255: if(isClient) {
2256: my ($cmd,$udom,$uname)=split(/:/,$userinput);
2257: chomp($uname);
2258: my $proname=propath($udom,$uname);
2259: if (-e $proname) {
2260: print $client "found\n";
2261: } else {
2262: print $client "not_found\n";
2263: }
2264: } else {
2265: Reply($client, "refused\n", $userinput);
2266:
2267: }
2268: # ---------------------------------------------------------------------- update
2269: } elsif ($userinput =~ /^update/) { # client clear or encoded.
2270: if(isClient) {
2271: my ($cmd,$fname)=split(/:/,$userinput);
2272: my $ownership=ishome($fname);
2273: if ($ownership eq 'not_owner') {
2274: if (-e $fname) {
2275: my ($dev,$ino,$mode,$nlink,
2276: $uid,$gid,$rdev,$size,
2277: $atime,$mtime,$ctime,
2278: $blksize,$blocks)=stat($fname);
2279: my $now=time;
2280: my $since=$now-$atime;
2281: if ($since>$perlvar{'lonExpire'}) {
2282: my $reply=
2283: &reply("unsub:$fname","$clientname");
2284: unlink("$fname");
2285: } else {
2286: my $transname="$fname.in.transfer";
2287: my $remoteurl=
2288: &reply("sub:$fname","$clientname");
2289: my $response;
2290: {
2291: my $ua=new LWP::UserAgent;
2292: my $request=new HTTP::Request('GET',"$remoteurl");
2293: $response=$ua->request($request,$transname);
2294: }
2295: if ($response->is_error()) {
2296: unlink($transname);
2297: my $message=$response->status_line;
2298: &logthis(
2299: "LWP GET: $message for $fname ($remoteurl)");
2300: } else {
2301: if ($remoteurl!~/\.meta$/) {
2302: my $ua=new LWP::UserAgent;
2303: my $mrequest=
2304: new HTTP::Request('GET',$remoteurl.'.meta');
2305: my $mresponse=
2306: $ua->request($mrequest,$fname.'.meta');
2307: if ($mresponse->is_error()) {
2308: unlink($fname.'.meta');
2309: }
2310: }
2311: rename($transname,$fname);
2312: }
2313: }
2314: print $client "ok\n";
2315: } else {
2316: print $client "not_found\n";
2317: }
2318: } else {
2319: print $client "rejected\n";
2320: }
2321: } else {
2322: Reply($client, "refused\n", $userinput);
2323:
2324: }
2325: # -------------------------------------- fetch a user file from a remote server
2326: } elsif ($userinput =~ /^fetchuserfile/) { # Client clear or enc.
2327: if(isClient) {
1.184 raeburn 2328: my ($cmd,$fname)=split(/:/,$userinput);
1.185 albertel 2329: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.178 foxr 2330: my $udir=propath($udom,$uname).'/userfiles';
2331: unless (-e $udir) { mkdir($udir,0770); }
2332: if (-e $udir) {
1.184 raeburn 2333: $ufile=~s/^[\.\~]+//;
2334: my $path = $udir;
1.185 albertel 2335: if ($ufile =~m|(.+)/([^/]+)$|) {
2336: my @parts=split('/',$1);
1.184 raeburn 2337: foreach my $part (@parts) {
2338: $path .= '/'.$part;
2339: if ((-e $path)!=1) {
2340: mkdir($path,0770);
1.182 raeburn 2341: }
2342: }
2343: }
1.184 raeburn 2344: my $destname=$udir.'/'.$ufile;
2345: my $transname=$udir.'/'.$ufile.'.in.transit';
2346: my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
1.178 foxr 2347: my $response;
2348: {
2349: my $ua=new LWP::UserAgent;
2350: my $request=new HTTP::Request('GET',"$remoteurl");
2351: $response=$ua->request($request,$transname);
2352: }
2353: if ($response->is_error()) {
2354: unlink($transname);
2355: my $message=$response->status_line;
1.184 raeburn 2356: &logthis("LWP GET: $message for $fname ($remoteurl)");
1.178 foxr 2357: print $client "failed\n";
2358: } else {
2359: if (!rename($transname,$destname)) {
2360: &logthis("Unable to move $transname to $destname");
2361: unlink($transname);
2362: print $client "failed\n";
2363: } else {
2364: print $client "ok\n";
2365: }
2366: }
2367: } else {
2368: print $client "not_home\n";
1.187 albertel 2369: }
2370: } else {
2371: Reply($client, "refused\n", $userinput);
2372: }
2373: # --------------------------------------------------------- remove a user file
2374: } elsif ($userinput =~ /^removeuserfile/) { # Client clear or enc.
2375: if(isClient) {
2376: my ($cmd,$fname)=split(/:/,$userinput);
2377: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2378: &logthis("$udom - $uname - $ufile");
2379: if ($ufile =~m|/\.\./|) {
2380: # any files paths with /../ in them refuse
2381: # to deal with
2382: print $client "refused\n";
2383: } else {
2384: my $udir=propath($udom,$uname);
2385: if (-e $udir) {
2386: my $file=$udir.'/userfiles/'.$ufile;
2387: if (-e $file) {
2388: unlink($file);
2389: if (-e $file) {
2390: print $client "failed\n";
2391: } else {
2392: print $client "ok\n";
2393: }
2394: } else {
2395: print $client "not_found\n";
2396: }
2397: } else {
2398: print $client "not_home\n";
2399: }
1.178 foxr 2400: }
2401: } else {
2402: Reply($client, "refused\n", $userinput);
2403: }
2404: # ------------------------------------------ authenticate access to a user file
2405: } elsif ($userinput =~ /^tokenauthuserfile/) { # Client only
2406: if(isClient) {
2407: my ($cmd,$fname,$session)=split(/:/,$userinput);
2408: chomp($session);
2409: my $reply='non_auth';
2410: if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
2411: $session.'.id')) {
2412: while (my $line=<ENVIN>) {
1.185 albertel 2413: if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply='ok'; }
1.178 foxr 2414: }
2415: close(ENVIN);
2416: print $client $reply."\n";
2417: } else {
2418: print $client "invalid_token\n";
2419: }
2420: } else {
2421: Reply($client, "refused\n", $userinput);
2422:
2423: }
2424: # ----------------------------------------------------------------- unsubscribe
2425: } elsif ($userinput =~ /^unsub/) {
2426: if(isClient) {
2427: my ($cmd,$fname)=split(/:/,$userinput);
2428: if (-e $fname) {
1.188 foxr 2429: print $client &unsub($fname,$clientip);
1.178 foxr 2430: } else {
2431: print $client "not_found\n";
2432: }
2433: } else {
2434: Reply($client, "refused\n", $userinput);
2435:
2436: }
2437: # ------------------------------------------------------------------- subscribe
2438: } elsif ($userinput =~ /^sub/) {
2439: if(isClient) {
2440: print $client &subscribe($userinput,$clientip);
2441: } else {
2442: Reply($client, "refused\n", $userinput);
2443:
2444: }
2445: # ------------------------------------------------------------- current version
2446: } elsif ($userinput =~ /^currentversion/) {
2447: if(isClient) {
2448: my ($cmd,$fname)=split(/:/,$userinput);
2449: print $client ¤tversion($fname)."\n";
2450: } else {
2451: Reply($client, "refused\n", $userinput);
2452:
2453: }
2454: # ------------------------------------------------------------------------- log
2455: } elsif ($userinput =~ /^log/) {
2456: if(isClient) {
2457: my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
2458: chomp($what);
2459: my $proname=propath($udom,$uname);
2460: my $now=time;
2461: {
2462: my $hfh;
2463: if ($hfh=IO::File->new(">>$proname/activity.log")) {
2464: print $hfh "$now:$clientname:$what\n";
2465: print $client "ok\n";
2466: } else {
2467: print $client "error: ".($!+0)
2468: ." IO::File->new Failed "
2469: ."while attempting log\n";
2470: }
2471: }
2472: } else {
2473: Reply($client, "refused\n", $userinput);
2474:
2475: }
2476: # ------------------------------------------------------------------------- put
2477: } elsif ($userinput =~ /^put/) {
2478: if(isClient) {
1.208 albertel 2479: my ($cmd,$udom,$uname,$namespace,$what)
2480: =split(/:/,$userinput,5);
1.178 foxr 2481: $namespace=~s/\//\_/g;
2482: $namespace=~s/\W//g;
2483: if ($namespace ne 'roles') {
2484: chomp($what);
2485: my $proname=propath($udom,$uname);
2486: my $now=time;
2487: my @pairs=split(/\&/,$what);
2488: my %hash;
2489: if (tie(%hash,'GDBM_File',
2490: "$proname/$namespace.db",
2491: &GDBM_WRCREAT(),0640)) {
1.209 albertel 2492: unless ($namespace=~/^nohist\_/) {
2493: my $hfh;
2494: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
2495: }
2496:
1.178 foxr 2497: foreach my $pair (@pairs) {
2498: my ($key,$value)=split(/=/,$pair);
2499: $hash{$key}=$value;
2500: }
2501: if (untie(%hash)) {
2502: print $client "ok\n";
2503: } else {
2504: print $client "error: ".($!+0)
2505: ." untie(GDBM) failed ".
2506: "while attempting put\n";
2507: }
2508: } else {
2509: print $client "error: ".($!)
2510: ." tie(GDBM) Failed ".
2511: "while attempting put\n";
2512: }
2513: } else {
2514: print $client "refused\n";
2515: }
2516: } else {
2517: Reply($client, "refused\n", $userinput);
2518:
2519: }
2520: # ------------------------------------------------------------------- inc
2521: } elsif ($userinput =~ /^inc:/) {
2522: if(isClient) {
2523: my ($cmd,$udom,$uname,$namespace,$what)
2524: =split(/:/,$userinput);
2525: $namespace=~s/\//\_/g;
2526: $namespace=~s/\W//g;
2527: if ($namespace ne 'roles') {
2528: chomp($what);
2529: my $proname=propath($udom,$uname);
2530: my $now=time;
2531: my @pairs=split(/\&/,$what);
2532: my %hash;
2533: if (tie(%hash,'GDBM_File',
2534: "$proname/$namespace.db",
2535: &GDBM_WRCREAT(),0640)) {
1.209 albertel 2536: unless ($namespace=~/^nohist\_/) {
2537: my $hfh;
2538: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
2539: }
1.178 foxr 2540: foreach my $pair (@pairs) {
2541: my ($key,$value)=split(/=/,$pair);
2542: # We could check that we have a number...
2543: if (! defined($value) || $value eq '') {
2544: $value = 1;
2545: }
2546: $hash{$key}+=$value;
2547: }
2548: if (untie(%hash)) {
2549: print $client "ok\n";
2550: } else {
2551: print $client "error: ".($!+0)
2552: ." untie(GDBM) failed ".
1.181 albertel 2553: "while attempting inc\n";
1.178 foxr 2554: }
2555: } else {
2556: print $client "error: ".($!)
2557: ." tie(GDBM) Failed ".
1.181 albertel 2558: "while attempting inc\n";
1.178 foxr 2559: }
2560: } else {
2561: print $client "refused\n";
2562: }
2563: } else {
2564: Reply($client, "refused\n", $userinput);
2565:
2566: }
2567: # -------------------------------------------------------------------- rolesput
2568: } elsif ($userinput =~ /^rolesput/) {
2569: if(isClient) {
2570: &Debug("rolesput");
2571: if ($wasenc==1) {
2572: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
2573: =split(/:/,$userinput);
2574: &Debug("cmd = ".$cmd." exedom= ".$exedom.
2575: "user = ".$exeuser." udom=".$udom.
2576: "what = ".$what);
2577: my $namespace='roles';
2578: chomp($what);
2579: my $proname=propath($udom,$uname);
2580: my $now=time;
2581: my @pairs=split(/\&/,$what);
2582: my %hash;
2583: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1.209 albertel 2584: {
2585: my $hfh;
2586: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
2587: print $hfh "P:$now:$exedom:$exeuser:$what\n";
2588: }
2589: }
2590:
1.178 foxr 2591: foreach my $pair (@pairs) {
2592: my ($key,$value)=split(/=/,$pair);
2593: &ManagePermissions($key, $udom, $uname,
2594: &GetAuthType( $udom,
2595: $uname));
2596: $hash{$key}=$value;
2597: }
2598: if (untie(%hash)) {
2599: print $client "ok\n";
2600: } else {
2601: print $client "error: ".($!+0)
2602: ." untie(GDBM) Failed ".
2603: "while attempting rolesput\n";
2604: }
2605: } else {
2606: print $client "error: ".($!+0)
2607: ." tie(GDBM) Failed ".
2608: "while attempting rolesput\n";
2609: }
2610: } else {
2611: print $client "refused\n";
2612: }
2613: } else {
2614: Reply($client, "refused\n", $userinput);
2615:
2616: }
2617: # -------------------------------------------------------------------- rolesdel
2618: } elsif ($userinput =~ /^rolesdel/) {
2619: if(isClient) {
2620: &Debug("rolesdel");
2621: if ($wasenc==1) {
2622: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
2623: =split(/:/,$userinput);
2624: &Debug("cmd = ".$cmd." exedom= ".$exedom.
2625: "user = ".$exeuser." udom=".$udom.
2626: "what = ".$what);
2627: my $namespace='roles';
2628: chomp($what);
2629: my $proname=propath($udom,$uname);
2630: my $now=time;
2631: my @rolekeys=split(/\&/,$what);
2632: my %hash;
2633: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1.209 albertel 2634: {
2635: my $hfh;
2636: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
2637: print $hfh "D:$now:$exedom:$exeuser:$what\n";
2638: }
2639: }
1.178 foxr 2640: foreach my $key (@rolekeys) {
2641: delete $hash{$key};
2642: }
2643: if (untie(%hash)) {
2644: print $client "ok\n";
2645: } else {
2646: print $client "error: ".($!+0)
2647: ." untie(GDBM) Failed ".
2648: "while attempting rolesdel\n";
2649: }
2650: } else {
2651: print $client "error: ".($!+0)
2652: ." tie(GDBM) Failed ".
2653: "while attempting rolesdel\n";
2654: }
2655: } else {
2656: print $client "refused\n";
2657: }
2658: } else {
2659: Reply($client, "refused\n", $userinput);
2660:
2661: }
2662: # ------------------------------------------------------------------------- get
2663: } elsif ($userinput =~ /^get/) {
2664: if(isClient) {
2665: my ($cmd,$udom,$uname,$namespace,$what)
2666: =split(/:/,$userinput);
2667: $namespace=~s/\//\_/g;
2668: $namespace=~s/\W//g;
2669: chomp($what);
2670: my @queries=split(/\&/,$what);
2671: my $proname=propath($udom,$uname);
2672: my $qresult='';
2673: my %hash;
2674: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2675: for (my $i=0;$i<=$#queries;$i++) {
2676: $qresult.="$hash{$queries[$i]}&";
2677: }
2678: if (untie(%hash)) {
2679: $qresult=~s/\&$//;
2680: print $client "$qresult\n";
2681: } else {
2682: print $client "error: ".($!+0)
2683: ." untie(GDBM) Failed ".
2684: "while attempting get\n";
2685: }
2686: } else {
2687: if ($!+0 == 2) {
2688: print $client "error:No such file or ".
2689: "GDBM reported bad block error\n";
2690: } else {
2691: print $client "error: ".($!+0)
2692: ." tie(GDBM) Failed ".
2693: "while attempting get\n";
2694: }
2695: }
2696: } else {
2697: Reply($client, "refused\n", $userinput);
2698:
2699: }
2700: # ------------------------------------------------------------------------ eget
2701: } elsif ($userinput =~ /^eget/) {
2702: if (isClient) {
2703: my ($cmd,$udom,$uname,$namespace,$what)
2704: =split(/:/,$userinput);
2705: $namespace=~s/\//\_/g;
2706: $namespace=~s/\W//g;
2707: chomp($what);
2708: my @queries=split(/\&/,$what);
2709: my $proname=propath($udom,$uname);
2710: my $qresult='';
2711: my %hash;
2712: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2713: for (my $i=0;$i<=$#queries;$i++) {
2714: $qresult.="$hash{$queries[$i]}&";
2715: }
2716: if (untie(%hash)) {
2717: $qresult=~s/\&$//;
2718: if ($cipher) {
2719: my $cmdlength=length($qresult);
2720: $qresult.=" ";
2721: my $encqresult='';
2722: for
2723: (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
2724: $encqresult.=
2725: unpack("H16",
2726: $cipher->encrypt(substr($qresult,$encidx,8)));
2727: }
2728: print $client "enc:$cmdlength:$encqresult\n";
2729: } else {
2730: print $client "error:no_key\n";
2731: }
2732: } else {
2733: print $client "error: ".($!+0)
2734: ." untie(GDBM) Failed ".
2735: "while attempting eget\n";
2736: }
2737: } else {
2738: print $client "error: ".($!+0)
2739: ." tie(GDBM) Failed ".
2740: "while attempting eget\n";
2741: }
2742: } else {
2743: Reply($client, "refused\n", $userinput);
2744:
2745: }
2746: # ------------------------------------------------------------------------- del
2747: } elsif ($userinput =~ /^del/) {
2748: if(isClient) {
2749: my ($cmd,$udom,$uname,$namespace,$what)
2750: =split(/:/,$userinput);
2751: $namespace=~s/\//\_/g;
2752: $namespace=~s/\W//g;
2753: chomp($what);
2754: my $proname=propath($udom,$uname);
2755: my $now=time;
2756: my @keys=split(/\&/,$what);
2757: my %hash;
2758: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1.209 albertel 2759: unless ($namespace=~/^nohist\_/) {
2760: my $hfh;
2761: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "D:$now:$what\n"; }
2762: }
1.178 foxr 2763: foreach my $key (@keys) {
2764: delete($hash{$key});
2765: }
2766: if (untie(%hash)) {
2767: print $client "ok\n";
2768: } else {
2769: print $client "error: ".($!+0)
2770: ." untie(GDBM) Failed ".
2771: "while attempting del\n";
2772: }
2773: } else {
2774: print $client "error: ".($!+0)
2775: ." tie(GDBM) Failed ".
2776: "while attempting del\n";
2777: }
2778: } else {
2779: Reply($client, "refused\n", $userinput);
2780:
2781: }
2782: # ------------------------------------------------------------------------ keys
2783: } elsif ($userinput =~ /^keys/) {
2784: if(isClient) {
2785: my ($cmd,$udom,$uname,$namespace)
2786: =split(/:/,$userinput);
2787: $namespace=~s/\//\_/g;
2788: $namespace=~s/\W//g;
2789: my $proname=propath($udom,$uname);
2790: my $qresult='';
2791: my %hash;
2792: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2793: foreach my $key (keys %hash) {
2794: $qresult.="$key&";
2795: }
2796: if (untie(%hash)) {
2797: $qresult=~s/\&$//;
2798: print $client "$qresult\n";
2799: } else {
2800: print $client "error: ".($!+0)
2801: ." untie(GDBM) Failed ".
2802: "while attempting keys\n";
2803: }
2804: } else {
2805: print $client "error: ".($!+0)
2806: ." tie(GDBM) Failed ".
2807: "while attempting keys\n";
2808: }
2809: } else {
2810: Reply($client, "refused\n", $userinput);
2811:
2812: }
2813: # ----------------------------------------------------------------- dumpcurrent
2814: } elsif ($userinput =~ /^currentdump/) {
2815: if (isClient) {
2816: my ($cmd,$udom,$uname,$namespace)
2817: =split(/:/,$userinput);
2818: $namespace=~s/\//\_/g;
2819: $namespace=~s/\W//g;
2820: my $qresult='';
2821: my $proname=propath($udom,$uname);
2822: my %hash;
2823: if (tie(%hash,'GDBM_File',
2824: "$proname/$namespace.db",
2825: &GDBM_READER(),0640)) {
2826: # Structure of %data:
2827: # $data{$symb}->{$parameter}=$value;
2828: # $data{$symb}->{'v.'.$parameter}=$version;
2829: # since $parameter will be unescaped, we do not
2830: # have to worry about silly parameter names...
2831: my %data = ();
2832: while (my ($key,$value) = each(%hash)) {
2833: my ($v,$symb,$param) = split(/:/,$key);
2834: next if ($v eq 'version' || $symb eq 'keys');
2835: next if (exists($data{$symb}) &&
2836: exists($data{$symb}->{$param}) &&
2837: $data{$symb}->{'v.'.$param} > $v);
2838: $data{$symb}->{$param}=$value;
2839: $data{$symb}->{'v.'.$param}=$v;
2840: }
2841: if (untie(%hash)) {
2842: while (my ($symb,$param_hash) = each(%data)) {
2843: while(my ($param,$value) = each (%$param_hash)){
2844: next if ($param =~ /^v\./);
2845: $qresult.=$symb.':'.$param.'='.$value.'&';
2846: }
2847: }
2848: chop($qresult);
2849: print $client "$qresult\n";
2850: } else {
2851: print $client "error: ".($!+0)
2852: ." untie(GDBM) Failed ".
2853: "while attempting currentdump\n";
2854: }
2855: } else {
2856: print $client "error: ".($!+0)
2857: ." tie(GDBM) Failed ".
2858: "while attempting currentdump\n";
2859: }
2860: } else {
2861: Reply($client, "refused\n", $userinput);
2862: }
2863: # ------------------------------------------------------------------------ dump
2864: } elsif ($userinput =~ /^dump/) {
2865: if(isClient) {
2866: my ($cmd,$udom,$uname,$namespace,$regexp)
2867: =split(/:/,$userinput);
2868: $namespace=~s/\//\_/g;
2869: $namespace=~s/\W//g;
2870: if (defined($regexp)) {
2871: $regexp=&unescape($regexp);
2872: } else {
2873: $regexp='.';
2874: }
2875: my $qresult='';
2876: my $proname=propath($udom,$uname);
2877: my %hash;
2878: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2879: while (my ($key,$value) = each(%hash)) {
2880: if ($regexp eq '.') {
2881: $qresult.=$key.'='.$value.'&';
2882: } else {
2883: my $unescapeKey = &unescape($key);
2884: if (eval('$unescapeKey=~/$regexp/')) {
2885: $qresult.="$key=$value&";
2886: }
2887: }
2888: }
2889: if (untie(%hash)) {
2890: chop($qresult);
2891: print $client "$qresult\n";
2892: } else {
2893: print $client "error: ".($!+0)
2894: ." untie(GDBM) Failed ".
2895: "while attempting dump\n";
2896: }
2897: } else {
2898: print $client "error: ".($!+0)
2899: ." tie(GDBM) Failed ".
2900: "while attempting dump\n";
2901: }
2902: } else {
2903: Reply($client, "refused\n", $userinput);
2904:
2905: }
2906: # ----------------------------------------------------------------------- store
2907: } elsif ($userinput =~ /^store/) {
2908: if(isClient) {
2909: my ($cmd,$udom,$uname,$namespace,$rid,$what)
2910: =split(/:/,$userinput);
2911: $namespace=~s/\//\_/g;
2912: $namespace=~s/\W//g;
2913: if ($namespace ne 'roles') {
2914: chomp($what);
2915: my $proname=propath($udom,$uname);
2916: my $now=time;
2917: my @pairs=split(/\&/,$what);
2918: my %hash;
2919: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1.209 albertel 2920: unless ($namespace=~/^nohist\_/) {
2921: my $hfh;
2922: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
2923: print $hfh "P:$now:$rid:$what\n";
2924: }
2925: }
1.178 foxr 2926: my @previouskeys=split(/&/,$hash{"keys:$rid"});
2927: my $key;
2928: $hash{"version:$rid"}++;
2929: my $version=$hash{"version:$rid"};
2930: my $allkeys='';
2931: foreach my $pair (@pairs) {
2932: my ($key,$value)=split(/=/,$pair);
2933: $allkeys.=$key.':';
2934: $hash{"$version:$rid:$key"}=$value;
2935: }
2936: $hash{"$version:$rid:timestamp"}=$now;
2937: $allkeys.='timestamp';
2938: $hash{"$version:keys:$rid"}=$allkeys;
2939: if (untie(%hash)) {
2940: print $client "ok\n";
2941: } else {
2942: print $client "error: ".($!+0)
2943: ." untie(GDBM) Failed ".
2944: "while attempting store\n";
2945: }
2946: } else {
2947: print $client "error: ".($!+0)
2948: ." tie(GDBM) Failed ".
2949: "while attempting store\n";
2950: }
2951: } else {
2952: print $client "refused\n";
2953: }
2954: } else {
2955: Reply($client, "refused\n", $userinput);
2956:
2957: }
2958: # --------------------------------------------------------------------- restore
2959: } elsif ($userinput =~ /^restore/) {
2960: if(isClient) {
2961: my ($cmd,$udom,$uname,$namespace,$rid)
2962: =split(/:/,$userinput);
2963: $namespace=~s/\//\_/g;
2964: $namespace=~s/\W//g;
2965: chomp($rid);
2966: my $proname=propath($udom,$uname);
2967: my $qresult='';
2968: my %hash;
2969: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2970: my $version=$hash{"version:$rid"};
2971: $qresult.="version=$version&";
2972: my $scope;
2973: for ($scope=1;$scope<=$version;$scope++) {
2974: my $vkeys=$hash{"$scope:keys:$rid"};
2975: my @keys=split(/:/,$vkeys);
2976: my $key;
2977: $qresult.="$scope:keys=$vkeys&";
2978: foreach $key (@keys) {
2979: $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
2980: }
2981: }
2982: if (untie(%hash)) {
2983: $qresult=~s/\&$//;
2984: print $client "$qresult\n";
2985: } else {
2986: print $client "error: ".($!+0)
2987: ." untie(GDBM) Failed ".
2988: "while attempting restore\n";
2989: }
2990: } else {
2991: print $client "error: ".($!+0)
2992: ." tie(GDBM) Failed ".
2993: "while attempting restore\n";
2994: }
2995: } else {
2996: Reply($client, "refused\n", $userinput);
2997:
2998: }
2999: # -------------------------------------------------------------------- chatsend
3000: } elsif ($userinput =~ /^chatsend/) {
3001: if(isClient) {
3002: my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
3003: &chatadd($cdom,$cnum,$newpost);
3004: print $client "ok\n";
3005: } else {
3006: Reply($client, "refused\n", $userinput);
3007:
3008: }
3009: # -------------------------------------------------------------------- chatretr
3010: } elsif ($userinput =~ /^chatretr/) {
3011: if(isClient) {
3012: my
3013: ($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
3014: my $reply='';
3015: foreach (&getchat($cdom,$cnum,$udom,$uname)) {
3016: $reply.=&escape($_).':';
3017: }
3018: $reply=~s/\:$//;
3019: print $client $reply."\n";
3020: } else {
3021: Reply($client, "refused\n", $userinput);
3022:
3023: }
3024: # ------------------------------------------------------------------- querysend
3025: } elsif ($userinput =~ /^querysend/) {
1.193 raeburn 3026: if (isClient) {
1.178 foxr 3027: my ($cmd,$query,
3028: $arg1,$arg2,$arg3)=split(/\:/,$userinput);
3029: $query=~s/\n*$//g;
3030: print $client "".
3031: sqlreply("$clientname\&$query".
3032: "\&$arg1"."\&$arg2"."\&$arg3")."\n";
3033: } else {
3034: Reply($client, "refused\n", $userinput);
3035:
3036: }
3037: # ------------------------------------------------------------------ queryreply
3038: } elsif ($userinput =~ /^queryreply/) {
3039: if(isClient) {
3040: my ($cmd,$id,$reply)=split(/:/,$userinput);
3041: my $store;
3042: my $execdir=$perlvar{'lonDaemons'};
3043: if ($store=IO::File->new(">$execdir/tmp/$id")) {
3044: $reply=~s/\&/\n/g;
3045: print $store $reply;
3046: close $store;
3047: my $store2=IO::File->new(">$execdir/tmp/$id.end");
3048: print $store2 "done\n";
3049: close $store2;
3050: print $client "ok\n";
3051: }
3052: else {
3053: print $client "error: ".($!+0)
3054: ." IO::File->new Failed ".
3055: "while attempting queryreply\n";
3056: }
3057: } else {
3058: Reply($client, "refused\n", $userinput);
3059:
3060: }
3061: # ----------------------------------------------------------------- courseidput
3062: } elsif ($userinput =~ /^courseidput/) {
3063: if(isClient) {
3064: my ($cmd,$udom,$what)=split(/:/,$userinput);
3065: chomp($what);
3066: $udom=~s/\W//g;
3067: my $proname=
3068: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
3069: my $now=time;
3070: my @pairs=split(/\&/,$what);
3071: my %hash;
3072: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
3073: foreach my $pair (@pairs) {
1.202 raeburn 3074: my ($key,$descr,$inst_code)=split(/=/,$pair);
3075: $hash{$key}=$descr.':'.$inst_code.':'.$now;
1.178 foxr 3076: }
3077: if (untie(%hash)) {
3078: print $client "ok\n";
3079: } else {
3080: print $client "error: ".($!+0)
3081: ." untie(GDBM) Failed ".
3082: "while attempting courseidput\n";
3083: }
3084: } else {
3085: print $client "error: ".($!+0)
3086: ." tie(GDBM) Failed ".
3087: "while attempting courseidput\n";
3088: }
3089: } else {
3090: Reply($client, "refused\n", $userinput);
3091:
3092: }
3093: # ---------------------------------------------------------------- courseiddump
3094: } elsif ($userinput =~ /^courseiddump/) {
3095: if(isClient) {
3096: my ($cmd,$udom,$since,$description)
3097: =split(/:/,$userinput);
3098: if (defined($description)) {
3099: $description=&unescape($description);
3100: } else {
3101: $description='.';
3102: }
3103: unless (defined($since)) { $since=0; }
3104: my $qresult='';
3105: my $proname=
3106: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
3107: my %hash;
3108: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
3109: while (my ($key,$value) = each(%hash)) {
1.202 raeburn 3110: my ($descr,$lasttime,$inst_code);
3111: if ($value =~ m/^([^\:]*):([^\:]*):(\d+)$/) {
3112: ($descr,$inst_code,$lasttime)=($1,$2,$3);
3113: } else {
3114: ($descr,$lasttime) = split(/\:/,$value);
3115: }
1.178 foxr 3116: if ($lasttime<$since) { next; }
3117: if ($description eq '.') {
1.202 raeburn 3118: $qresult.=$key.'='.$descr.':'.$inst_code.'&';
1.178 foxr 3119: } else {
3120: my $unescapeVal = &unescape($descr);
1.189 www 3121: if (eval('$unescapeVal=~/\Q$description\E/i')) {
1.202 raeburn 3122: $qresult.=$key.'='.$descr.':'.$inst_code.'&';
1.178 foxr 3123: }
3124: }
3125: }
3126: if (untie(%hash)) {
3127: chop($qresult);
3128: print $client "$qresult\n";
3129: } else {
3130: print $client "error: ".($!+0)
3131: ." untie(GDBM) Failed ".
3132: "while attempting courseiddump\n";
3133: }
3134: } else {
3135: print $client "error: ".($!+0)
3136: ." tie(GDBM) Failed ".
3137: "while attempting courseiddump\n";
3138: }
3139: } else {
3140: Reply($client, "refused\n", $userinput);
3141:
3142: }
3143: # ----------------------------------------------------------------------- idput
3144: } elsif ($userinput =~ /^idput/) {
3145: if(isClient) {
3146: my ($cmd,$udom,$what)=split(/:/,$userinput);
3147: chomp($what);
3148: $udom=~s/\W//g;
3149: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
3150: my $now=time;
3151: my @pairs=split(/\&/,$what);
3152: my %hash;
3153: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
1.209 albertel 3154: {
3155: my $hfh;
3156: if ($hfh=IO::File->new(">>$proname.hist")) {
3157: print $hfh "P:$now:$what\n";
3158: }
3159: }
1.178 foxr 3160: foreach my $pair (@pairs) {
3161: my ($key,$value)=split(/=/,$pair);
3162: $hash{$key}=$value;
3163: }
3164: if (untie(%hash)) {
3165: print $client "ok\n";
3166: } else {
3167: print $client "error: ".($!+0)
3168: ." untie(GDBM) Failed ".
3169: "while attempting idput\n";
3170: }
3171: } else {
3172: print $client "error: ".($!+0)
3173: ." tie(GDBM) Failed ".
3174: "while attempting idput\n";
3175: }
3176: } else {
3177: Reply($client, "refused\n", $userinput);
3178:
3179: }
3180: # ----------------------------------------------------------------------- idget
3181: } elsif ($userinput =~ /^idget/) {
3182: if(isClient) {
3183: my ($cmd,$udom,$what)=split(/:/,$userinput);
3184: chomp($what);
3185: $udom=~s/\W//g;
3186: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
3187: my @queries=split(/\&/,$what);
3188: my $qresult='';
3189: my %hash;
3190: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
3191: for (my $i=0;$i<=$#queries;$i++) {
3192: $qresult.="$hash{$queries[$i]}&";
3193: }
3194: if (untie(%hash)) {
3195: $qresult=~s/\&$//;
3196: print $client "$qresult\n";
3197: } else {
3198: print $client "error: ".($!+0)
3199: ." untie(GDBM) Failed ".
3200: "while attempting idget\n";
3201: }
3202: } else {
3203: print $client "error: ".($!+0)
3204: ." tie(GDBM) Failed ".
3205: "while attempting idget\n";
3206: }
3207: } else {
3208: Reply($client, "refused\n", $userinput);
3209:
3210: }
3211: # ---------------------------------------------------------------------- tmpput
3212: } elsif ($userinput =~ /^tmpput/) {
3213: if(isClient) {
3214: my ($cmd,$what)=split(/:/,$userinput);
3215: my $store;
3216: $tmpsnum++;
3217: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
3218: $id=~s/\W/\_/g;
3219: $what=~s/\n//g;
3220: my $execdir=$perlvar{'lonDaemons'};
3221: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
3222: print $store $what;
3223: close $store;
3224: print $client "$id\n";
3225: }
3226: else {
3227: print $client "error: ".($!+0)
3228: ."IO::File->new Failed ".
3229: "while attempting tmpput\n";
3230: }
3231: } else {
3232: Reply($client, "refused\n", $userinput);
3233:
3234: }
3235:
3236: # ---------------------------------------------------------------------- tmpget
3237: } elsif ($userinput =~ /^tmpget/) {
3238: if(isClient) {
3239: my ($cmd,$id)=split(/:/,$userinput);
3240: chomp($id);
3241: $id=~s/\W/\_/g;
3242: my $store;
3243: my $execdir=$perlvar{'lonDaemons'};
3244: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
3245: my $reply=<$store>;
3246: print $client "$reply\n";
3247: close $store;
3248: }
3249: else {
3250: print $client "error: ".($!+0)
3251: ."IO::File->new Failed ".
3252: "while attempting tmpget\n";
3253: }
3254: } else {
3255: Reply($client, "refused\n", $userinput);
3256:
3257: }
3258: # ---------------------------------------------------------------------- tmpdel
3259: } elsif ($userinput =~ /^tmpdel/) {
3260: if(isClient) {
3261: my ($cmd,$id)=split(/:/,$userinput);
3262: chomp($id);
3263: $id=~s/\W/\_/g;
3264: my $execdir=$perlvar{'lonDaemons'};
3265: if (unlink("$execdir/tmp/$id.tmp")) {
3266: print $client "ok\n";
3267: } else {
3268: print $client "error: ".($!+0)
3269: ."Unlink tmp Failed ".
3270: "while attempting tmpdel\n";
3271: }
3272: } else {
3273: Reply($client, "refused\n", $userinput);
3274:
3275: }
1.201 matthew 3276: # ----------------------------------------- portfolio directory list (portls)
3277: } elsif ($userinput =~ /^portls/) {
3278: if(isClient) {
3279: my ($cmd,$uname,$udom)=split(/:/,$userinput);
3280: my $udir=propath($udom,$uname).'/userfiles/portfolio';
3281: my $dirLine='';
3282: my $dirContents='';
3283: if (opendir(LSDIR,$udir.'/')){
3284: while ($dirLine = readdir(LSDIR)){
3285: $dirContents = $dirContents.$dirLine.'<br />';
3286: }
3287: } else {
3288: $dirContents = "No directory found\n";
3289: }
3290: print $client $dirContents."\n";
3291: } else {
3292: Reply($client, "refused\n", $userinput);
3293: }
1.178 foxr 3294: # -------------------------------------------------------------------------- ls
3295: } elsif ($userinput =~ /^ls/) {
3296: if(isClient) {
3297: my $obs;
3298: my $rights;
3299: my ($cmd,$ulsdir)=split(/:/,$userinput);
3300: my $ulsout='';
3301: my $ulsfn;
3302: if (-e $ulsdir) {
3303: if(-d $ulsdir) {
3304: if (opendir(LSDIR,$ulsdir)) {
3305: while ($ulsfn=readdir(LSDIR)) {
3306: undef $obs, $rights;
3307: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
3308: #We do some obsolete checking here
3309: if(-e $ulsdir.'/'.$ulsfn.".meta") {
3310: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
3311: my @obsolete=<FILE>;
3312: foreach my $obsolete (@obsolete) {
3313: if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; }
3314: if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
3315: }
3316: }
3317: $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
3318: if($obs eq '1') { $ulsout.="&1"; }
3319: else { $ulsout.="&0"; }
3320: if($rights eq '1') { $ulsout.="&1:"; }
3321: else { $ulsout.="&0:"; }
3322: }
3323: closedir(LSDIR);
3324: }
3325: } else {
3326: my @ulsstats=stat($ulsdir);
3327: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
3328: }
3329: } else {
3330: $ulsout='no_such_dir';
3331: }
3332: if ($ulsout eq '') { $ulsout='empty'; }
3333: print $client "$ulsout\n";
3334: } else {
3335: Reply($client, "refused\n", $userinput);
3336:
3337: }
3338: # ----------------------------------------------------------------- setannounce
3339: } elsif ($userinput =~ /^setannounce/) {
3340: if (isClient) {
3341: my ($cmd,$announcement)=split(/:/,$userinput);
3342: chomp($announcement);
3343: $announcement=&unescape($announcement);
3344: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
3345: '/announcement.txt')) {
3346: print $store $announcement;
3347: close $store;
3348: print $client "ok\n";
3349: } else {
3350: print $client "error: ".($!+0)."\n";
3351: }
3352: } else {
3353: Reply($client, "refused\n", $userinput);
3354:
3355: }
3356: # ------------------------------------------------------------------ Hanging up
3357: } elsif (($userinput =~ /^exit/) ||
3358: ($userinput =~ /^init/)) { # no restrictions.
3359: &logthis(
3360: "Client $clientip ($clientname) hanging up: $userinput");
3361: print $client "bye\n";
3362: $client->shutdown(2); # shutdown the socket forcibly.
3363: $client->close();
3364: last;
1.161 foxr 3365:
1.178 foxr 3366: # ---------------------------------- set current host/domain
3367: } elsif ($userinput =~ /^sethost:/) {
3368: if (isClient) {
3369: print $client &sethost($userinput)."\n";
3370: } else {
3371: print $client "refused\n";
3372: }
3373: #---------------------------------- request file (?) version.
3374: } elsif ($userinput =~/^version:/) {
3375: if (isClient) {
3376: print $client &version($userinput)."\n";
3377: } else {
3378: print $client "refused\n";
3379: }
1.193 raeburn 3380: #------------------------------- is auto-enrollment enabled?
1.200 matthew 3381: } elsif ($userinput =~/^autorun:/) {
1.193 raeburn 3382: if (isClient) {
1.200 matthew 3383: my ($cmd,$cdom) = split(/:/,$userinput);
3384: my $outcome = &localenroll::run($cdom);
1.193 raeburn 3385: print $client "$outcome\n";
3386: } else {
3387: print $client "0\n";
3388: }
3389: #------------------------------- get official sections (for auto-enrollment).
1.200 matthew 3390: } elsif ($userinput =~/^autogetsections:/) {
1.193 raeburn 3391: if (isClient) {
1.200 matthew 3392: my ($cmd,$coursecode,$cdom)=split(/:/,$userinput);
3393: my @secs = &localenroll::get_sections($coursecode,$cdom);
1.193 raeburn 3394: my $seclist = &escape(join(':',@secs));
3395: print $client "$seclist\n";
3396: } else {
3397: print $client "refused\n";
3398: }
3399: #----------------------- validate owner of new course section (for auto-enrollment).
1.200 matthew 3400: } elsif ($userinput =~/^autonewcourse:/) {
1.193 raeburn 3401: if (isClient) {
1.200 matthew 3402: my ($cmd,$inst_course_id,$owner,$cdom)=split(/:/,$userinput);
3403: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
1.193 raeburn 3404: print $client "$outcome\n";
3405: } else {
3406: print $client "refused\n";
3407: }
3408: #-------------- validate course section in schedule of classes (for auto-enrollment).
1.200 matthew 3409: } elsif ($userinput =~/^autovalidatecourse:/) {
1.193 raeburn 3410: if (isClient) {
1.200 matthew 3411: my ($cmd,$inst_course_id,$cdom)=split(/:/,$userinput);
3412: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.193 raeburn 3413: print $client "$outcome\n";
3414: } else {
3415: print $client "refused\n";
3416: }
3417: #--------------------------- create password for new user (for auto-enrollment).
1.200 matthew 3418: } elsif ($userinput =~/^autocreatepassword:/) {
1.193 raeburn 3419: if (isClient) {
1.200 matthew 3420: my ($cmd,$authparam,$cdom)=split(/:/,$userinput);
3421: my ($create_passwd,$authchk);
3422: ($authparam,$create_passwd,$authchk) = &localenroll::create_password($authparam,$cdom);
1.193 raeburn 3423: print $client &escape($authparam.':'.$create_passwd.':'.$authchk)."\n";
3424: } else {
3425: print $client "refused\n";
3426: }
3427: #--------------------------- read and remove temporary files (for auto-enrollment).
1.200 matthew 3428: } elsif ($userinput =~/^autoretrieve:/) {
1.193 raeburn 3429: if (isClient) {
3430: my ($cmd,$filename) = split(/:/,$userinput);
3431: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
3432: if ( (-e $source) && ($filename ne '') ) {
3433: my $reply = '';
3434: if (open(my $fh,$source)) {
3435: while (<$fh>) {
3436: chomp($_);
3437: $_ =~ s/^\s+//g;
3438: $_ =~ s/\s+$//g;
3439: $reply .= $_;
3440: }
3441: close($fh);
3442: print $client &escape($reply)."\n";
3443: # unlink($source);
3444: } else {
3445: print $client "error\n";
3446: }
3447: } else {
3448: print $client "error\n";
3449: }
3450: } else {
3451: print $client "refused\n";
3452: }
1.205 raeburn 3453: #--------------------- read and retrieve institutional code format (for support form).
3454: } elsif ($userinput =~/^autoinstcodeformat:/) {
3455: if (isClient) {
3456: my $reply;
3457: my($cmd,$cdom,$course) = split(/:/,$userinput);
3458: my @pairs = split/\&/,$course;
3459: my %instcodes = ();
3460: my %codes = ();
3461: my @codetitles = ();
3462: my %cat_titles = ();
3463: my %cat_order = ();
3464: foreach (@pairs) {
3465: my ($key,$value) = split/=/,$_;
3466: $instcodes{&unescape($key)} = &unescape($value);
3467: }
3468: my $formatreply = &localenroll::instcode_format($cdom,\%instcodes,\%codes,\@codetitles,\%cat_titles,\%cat_order);
3469: if ($formatreply eq 'ok') {
3470: my $codes_str = &hash2str(%codes);
3471: my $codetitles_str = &array2str(@codetitles);
3472: my $cat_titles_str = &hash2str(%cat_titles);
3473: my $cat_order_str = &hash2str(%cat_order);
3474: print $client $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'.$cat_order_str."\n";
3475: }
3476: } else {
3477: print $client "refused\n";
3478: }
1.178 foxr 3479: # ------------------------------------------------------------- unknown command
1.161 foxr 3480:
1.178 foxr 3481: } else {
3482: # unknown command
3483: print $client "unknown_cmd\n";
3484: }
1.177 foxr 3485: # -------------------------------------------------------------------- complete
1.178 foxr 3486: alarm(0);
1.200 matthew 3487: &status('Listening to '.$clientname." ($keymode)");
1.161 foxr 3488: }
1.59 www 3489: # --------------------------------------------- client unknown or fishy, refuse
1.161 foxr 3490: } else {
3491: print $client "refused\n";
3492: $client->close();
1.190 albertel 3493: &logthis("<font color='blue'>WARNING: "
1.161 foxr 3494: ."Rejected client $clientip, closing connection</font>");
3495: }
3496: }
3497:
1.1 albertel 3498: # =============================================================================
1.161 foxr 3499:
1.190 albertel 3500: &logthis("<font color='red'>CRITICAL: "
1.161 foxr 3501: ."Disconnect from $clientip ($clientname)</font>");
3502:
3503:
3504: # this exit is VERY important, otherwise the child will become
3505: # a producer of more and more children, forking yourself into
3506: # process death.
3507: exit;
1.106 foxr 3508:
1.78 foxr 3509: }
3510:
3511:
3512: #
3513: # Checks to see if the input roleput request was to set
3514: # an author role. If so, invokes the lchtmldir script to set
3515: # up a correct public_html
3516: # Parameters:
3517: # request - The request sent to the rolesput subchunk.
3518: # We're looking for /domain/_au
3519: # domain - The domain in which the user is having roles doctored.
3520: # user - Name of the user for which the role is being put.
3521: # authtype - The authentication type associated with the user.
3522: #
3523: sub ManagePermissions
3524: {
1.192 foxr 3525:
3526: my ($request, $domain, $user, $authtype) = @_;
1.78 foxr 3527:
3528: # See if the request is of the form /$domain/_au
3529: if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
3530: my $execdir = $perlvar{'lonDaemons'};
3531: my $userhome= "/home/$user" ;
1.134 albertel 3532: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.78 foxr 3533: system("$execdir/lchtmldir $userhome $user $authtype");
3534: }
3535: }
3536: #
3537: # GetAuthType - Determines the authorization type of a user in a domain.
3538:
3539: # Returns the authorization type or nouser if there is no such user.
3540: #
3541: sub GetAuthType
3542: {
1.192 foxr 3543:
3544: my ($domain, $user) = @_;
1.78 foxr 3545:
1.79 foxr 3546: Debug("GetAuthType( $domain, $user ) \n");
1.78 foxr 3547: my $proname = &propath($domain, $user);
3548: my $passwdfile = "$proname/passwd";
3549: if( -e $passwdfile ) {
3550: my $pf = IO::File->new($passwdfile);
3551: my $realpassword = <$pf>;
3552: chomp($realpassword);
1.79 foxr 3553: Debug("Password info = $realpassword\n");
1.78 foxr 3554: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 3555: Debug("Authtype = $authtype, content = $contentpwd\n");
1.78 foxr 3556: my $availinfo = '';
1.91 albertel 3557: if($authtype eq 'krb4' or $authtype eq 'krb5') {
1.78 foxr 3558: $availinfo = $contentpwd;
3559: }
1.79 foxr 3560:
1.78 foxr 3561: return "$authtype:$availinfo";
3562: }
3563: else {
1.79 foxr 3564: Debug("Returning nouser");
1.78 foxr 3565: return "nouser";
3566: }
1.1 albertel 3567: }
3568:
1.84 albertel 3569: sub addline {
3570: my ($fname,$hostid,$ip,$newline)=@_;
3571: my $contents;
3572: my $found=0;
3573: my $expr='^'.$hostid.':'.$ip.':';
3574: $expr =~ s/\./\\\./g;
1.134 albertel 3575: my $sh;
1.84 albertel 3576: if ($sh=IO::File->new("$fname.subscription")) {
3577: while (my $subline=<$sh>) {
3578: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
3579: }
3580: $sh->close();
3581: }
3582: $sh=IO::File->new(">$fname.subscription");
3583: if ($contents) { print $sh $contents; }
3584: if ($newline) { print $sh $newline; }
3585: $sh->close();
3586: return $found;
1.86 www 3587: }
3588:
3589: sub getchat {
1.122 www 3590: my ($cdom,$cname,$udom,$uname)=@_;
1.87 www 3591: my %hash;
3592: my $proname=&propath($cdom,$cname);
3593: my @entries=();
1.88 albertel 3594: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
3595: &GDBM_READER(),0640)) {
3596: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
3597: untie %hash;
1.123 www 3598: }
1.124 www 3599: my @participants=();
1.134 albertel 3600: my $cutoff=time-60;
1.123 www 3601: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124 www 3602: &GDBM_WRCREAT(),0640)) {
3603: $hash{$uname.':'.$udom}=time;
1.123 www 3604: foreach (sort keys %hash) {
3605: if ($hash{$_}>$cutoff) {
1.124 www 3606: $participants[$#participants+1]='active_participant:'.$_;
1.123 www 3607: }
3608: }
3609: untie %hash;
1.86 www 3610: }
1.124 www 3611: return (@participants,@entries);
1.86 www 3612: }
3613:
3614: sub chatadd {
1.88 albertel 3615: my ($cdom,$cname,$newchat)=@_;
3616: my %hash;
3617: my $proname=&propath($cdom,$cname);
3618: my @entries=();
1.142 www 3619: my $time=time;
1.88 albertel 3620: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
3621: &GDBM_WRCREAT(),0640)) {
3622: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
3623: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
3624: my ($thentime,$idnum)=split(/\_/,$lastid);
3625: my $newid=$time.'_000000';
3626: if ($thentime==$time) {
3627: $idnum=~s/^0+//;
3628: $idnum++;
3629: $idnum=substr('000000'.$idnum,-6,6);
3630: $newid=$time.'_'.$idnum;
3631: }
3632: $hash{$newid}=$newchat;
3633: my $expired=$time-3600;
3634: foreach (keys %hash) {
3635: my ($thistime)=($_=~/(\d+)\_/);
3636: if ($thistime<$expired) {
1.89 www 3637: delete $hash{$_};
1.88 albertel 3638: }
3639: }
3640: untie %hash;
1.142 www 3641: }
3642: {
3643: my $hfh;
3644: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
3645: print $hfh "$time:".&unescape($newchat)."\n";
3646: }
1.86 www 3647: }
1.84 albertel 3648: }
3649:
3650: sub unsub {
3651: my ($fname,$clientip)=@_;
3652: my $result;
1.188 foxr 3653: my $unsubs = 0; # Number of successful unsubscribes:
3654:
3655:
3656: # An old way subscriptions were handled was to have a
3657: # subscription marker file:
3658:
3659: Debug("Attempting unlink of $fname.$clientname");
1.161 foxr 3660: if (unlink("$fname.$clientname")) {
1.188 foxr 3661: $unsubs++; # Successful unsub via marker file.
3662: }
3663:
3664: # The more modern way to do it is to have a subscription list
3665: # file:
3666:
1.84 albertel 3667: if (-e "$fname.subscription") {
1.161 foxr 3668: my $found=&addline($fname,$clientname,$clientip,'');
1.188 foxr 3669: if ($found) {
3670: $unsubs++;
3671: }
3672: }
3673:
3674: # If either or both of these mechanisms succeeded in unsubscribing a
3675: # resource we can return ok:
3676:
3677: if($unsubs) {
3678: $result = "ok\n";
1.84 albertel 3679: } else {
1.188 foxr 3680: $result = "not_subscribed\n";
1.84 albertel 3681: }
1.188 foxr 3682:
1.84 albertel 3683: return $result;
3684: }
3685:
1.101 www 3686: sub currentversion {
3687: my $fname=shift;
3688: my $version=-1;
3689: my $ulsdir='';
3690: if ($fname=~/^(.+)\/[^\/]+$/) {
3691: $ulsdir=$1;
3692: }
1.114 albertel 3693: my ($fnamere1,$fnamere2);
3694: # remove version if already specified
1.101 www 3695: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 3696: # get the bits that go before and after the version number
3697: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
3698: $fnamere1=$1;
3699: $fnamere2='.'.$2;
3700: }
1.101 www 3701: if (-e $fname) { $version=1; }
3702: if (-e $ulsdir) {
1.134 albertel 3703: if(-d $ulsdir) {
3704: if (opendir(LSDIR,$ulsdir)) {
3705: my $ulsfn;
3706: while ($ulsfn=readdir(LSDIR)) {
1.101 www 3707: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 3708: my $thisfile=$ulsdir.'/'.$ulsfn;
3709: unless (-l $thisfile) {
1.160 www 3710: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 3711: if ($1>$version) { $version=$1; }
3712: }
3713: }
3714: }
3715: closedir(LSDIR);
3716: $version++;
3717: }
3718: }
3719: }
3720: return $version;
1.101 www 3721: }
3722:
3723: sub thisversion {
3724: my $fname=shift;
3725: my $version=-1;
3726: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
3727: $version=$1;
3728: }
3729: return $version;
3730: }
3731:
1.84 albertel 3732: sub subscribe {
3733: my ($userinput,$clientip)=@_;
3734: my $result;
3735: my ($cmd,$fname)=split(/:/,$userinput);
3736: my $ownership=&ishome($fname);
3737: if ($ownership eq 'owner') {
1.101 www 3738: # explitly asking for the current version?
3739: unless (-e $fname) {
3740: my $currentversion=¤tversion($fname);
3741: if (&thisversion($fname)==$currentversion) {
3742: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
3743: my $root=$1;
3744: my $extension=$2;
3745: symlink($root.'.'.$extension,
3746: $root.'.'.$currentversion.'.'.$extension);
1.102 www 3747: unless ($extension=~/\.meta$/) {
3748: symlink($root.'.'.$extension.'.meta',
3749: $root.'.'.$currentversion.'.'.$extension.'.meta');
3750: }
1.101 www 3751: }
3752: }
3753: }
1.84 albertel 3754: if (-e $fname) {
3755: if (-d $fname) {
3756: $result="directory\n";
3757: } else {
1.161 foxr 3758: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 3759: my $now=time;
1.161 foxr 3760: my $found=&addline($fname,$clientname,$clientip,
3761: "$clientname:$clientip:$now\n");
1.84 albertel 3762: if ($found) { $result="$fname\n"; }
3763: # if they were subscribed to only meta data, delete that
3764: # subscription, when you subscribe to a file you also get
3765: # the metadata
3766: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
3767: $fname=~s/\/home\/httpd\/html\/res/raw/;
3768: $fname="http://$thisserver/".$fname;
3769: $result="$fname\n";
3770: }
3771: } else {
3772: $result="not_found\n";
3773: }
3774: } else {
3775: $result="rejected\n";
3776: }
3777: return $result;
3778: }
1.91 albertel 3779:
3780: sub make_passwd_file {
1.98 foxr 3781: my ($uname, $umode,$npass,$passfilename)=@_;
1.91 albertel 3782: my $result="ok\n";
3783: if ($umode eq 'krb4' or $umode eq 'krb5') {
3784: {
3785: my $pf = IO::File->new(">$passfilename");
3786: print $pf "$umode:$npass\n";
3787: }
3788: } elsif ($umode eq 'internal') {
3789: my $salt=time;
3790: $salt=substr($salt,6,2);
3791: my $ncpass=crypt($npass,$salt);
3792: {
3793: &Debug("Creating internal auth");
3794: my $pf = IO::File->new(">$passfilename");
3795: print $pf "internal:$ncpass\n";
3796: }
3797: } elsif ($umode eq 'localauth') {
3798: {
3799: my $pf = IO::File->new(">$passfilename");
3800: print $pf "localauth:$npass\n";
3801: }
3802: } elsif ($umode eq 'unix') {
3803: {
1.186 foxr 3804: #
3805: # Don't allow the creation of privileged accounts!!! that would
3806: # be real bad!!!
3807: #
3808: my $uid = getpwnam($uname);
3809: if((defined $uid) && ($uid == 0)) {
3810: &logthis(">>>Attempted to create privilged account blocked");
3811: return "no_priv_account_error\n";
3812: }
3813:
1.91 albertel 3814: my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
3815: {
3816: &Debug("Executing external: ".$execpath);
1.98 foxr 3817: &Debug("user = ".$uname.", Password =". $npass);
1.132 matthew 3818: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91 albertel 3819: print $se "$uname\n";
3820: print $se "$npass\n";
3821: print $se "$npass\n";
1.97 foxr 3822: }
3823: my $useraddok = $?;
3824: if($useraddok > 0) {
3825: &logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
1.91 albertel 3826: }
3827: my $pf = IO::File->new(">$passfilename");
3828: print $pf "unix:\n";
3829: }
3830: } elsif ($umode eq 'none') {
3831: {
3832: my $pf = IO::File->new(">$passfilename");
3833: print $pf "none:\n";
3834: }
3835: } else {
3836: $result="auth_mode_error\n";
3837: }
3838: return $result;
1.121 albertel 3839: }
3840:
3841: sub sethost {
3842: my ($remotereq) = @_;
3843: my (undef,$hostid)=split(/:/,$remotereq);
3844: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
3845: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200 matthew 3846: $currenthostid =$hostid;
1.121 albertel 3847: $currentdomainid=$hostdom{$hostid};
3848: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
3849: } else {
3850: &logthis("Requested host id $hostid not an alias of ".
3851: $perlvar{'lonHostID'}." refusing connection");
3852: return 'unable_to_set';
3853: }
3854: return 'ok';
3855: }
3856:
3857: sub version {
3858: my ($userinput)=@_;
3859: $remoteVERSION=(split(/:/,$userinput))[1];
3860: return "version:$VERSION";
1.127 albertel 3861: }
1.178 foxr 3862:
1.128 albertel 3863: #There is a copy of this in lonnet.pm
1.127 albertel 3864: sub userload {
3865: my $numusers=0;
3866: {
3867: opendir(LONIDS,$perlvar{'lonIDsDir'});
3868: my $filename;
3869: my $curtime=time;
3870: while ($filename=readdir(LONIDS)) {
3871: if ($filename eq '.' || $filename eq '..') {next;}
1.138 albertel 3872: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159 albertel 3873: if ($curtime-$mtime < 1800) { $numusers++; }
1.127 albertel 3874: }
3875: closedir(LONIDS);
3876: }
3877: my $userloadpercent=0;
3878: my $maxuserload=$perlvar{'lonUserLoadLim'};
3879: if ($maxuserload) {
1.129 albertel 3880: $userloadpercent=100*$numusers/$maxuserload;
1.127 albertel 3881: }
1.130 albertel 3882: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127 albertel 3883: return $userloadpercent;
1.91 albertel 3884: }
3885:
1.205 raeburn 3886: # Routines for serializing arrays and hashes (copies from lonnet)
3887:
3888: sub array2str {
3889: my (@array) = @_;
3890: my $result=&arrayref2str(\@array);
3891: $result=~s/^__ARRAY_REF__//;
3892: $result=~s/__END_ARRAY_REF__$//;
3893: return $result;
3894: }
3895:
3896: sub arrayref2str {
3897: my ($arrayref) = @_;
3898: my $result='__ARRAY_REF__';
3899: foreach my $elem (@$arrayref) {
3900: if(ref($elem) eq 'ARRAY') {
3901: $result.=&arrayref2str($elem).'&';
3902: } elsif(ref($elem) eq 'HASH') {
3903: $result.=&hashref2str($elem).'&';
3904: } elsif(ref($elem)) {
3905: #print("Got a ref of ".(ref($elem))." skipping.");
3906: } else {
3907: $result.=&escape($elem).'&';
3908: }
3909: }
3910: $result=~s/\&$//;
3911: $result .= '__END_ARRAY_REF__';
3912: return $result;
3913: }
3914:
3915: sub hash2str {
3916: my (%hash) = @_;
3917: my $result=&hashref2str(\%hash);
3918: $result=~s/^__HASH_REF__//;
3919: $result=~s/__END_HASH_REF__$//;
3920: return $result;
3921: }
3922:
3923: sub hashref2str {
3924: my ($hashref)=@_;
3925: my $result='__HASH_REF__';
3926: foreach (sort(keys(%$hashref))) {
3927: if (ref($_) eq 'ARRAY') {
3928: $result.=&arrayref2str($_).'=';
3929: } elsif (ref($_) eq 'HASH') {
3930: $result.=&hashref2str($_).'=';
3931: } elsif (ref($_)) {
3932: $result.='=';
3933: #print("Got a ref of ".(ref($_))." skipping.");
3934: } else {
3935: if ($_) {$result.=&escape($_).'=';} else { last; }
3936: }
3937:
3938: if(ref($hashref->{$_}) eq 'ARRAY') {
3939: $result.=&arrayref2str($hashref->{$_}).'&';
3940: } elsif(ref($hashref->{$_}) eq 'HASH') {
3941: $result.=&hashref2str($hashref->{$_}).'&';
3942: } elsif(ref($hashref->{$_})) {
3943: $result.='&';
3944: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
3945: } else {
3946: $result.=&escape($hashref->{$_}).'&';
3947: }
3948: }
3949: $result=~s/\&$//;
3950: $result .= '__END_HASH_REF__';
3951: return $result;
3952: }
1.200 matthew 3953:
1.61 harris41 3954: # ----------------------------------- POD (plain old documentation, CPAN style)
3955:
3956: =head1 NAME
3957:
3958: lond - "LON Daemon" Server (port "LOND" 5663)
3959:
3960: =head1 SYNOPSIS
3961:
1.74 harris41 3962: Usage: B<lond>
3963:
3964: Should only be run as user=www. This is a command-line script which
3965: is invoked by B<loncron>. There is no expectation that a typical user
3966: will manually start B<lond> from the command-line. (In other words,
3967: DO NOT START B<lond> YOURSELF.)
1.61 harris41 3968:
3969: =head1 DESCRIPTION
3970:
1.74 harris41 3971: There are two characteristics associated with the running of B<lond>,
3972: PROCESS MANAGEMENT (starting, stopping, handling child processes)
3973: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
3974: subscriptions, etc). These are described in two large
3975: sections below.
3976:
3977: B<PROCESS MANAGEMENT>
3978:
1.61 harris41 3979: Preforker - server who forks first. Runs as a daemon. HUPs.
3980: Uses IDEA encryption
3981:
1.74 harris41 3982: B<lond> forks off children processes that correspond to the other servers
3983: in the network. Management of these processes can be done at the
3984: parent process level or the child process level.
3985:
3986: B<logs/lond.log> is the location of log messages.
3987:
3988: The process management is now explained in terms of linux shell commands,
3989: subroutines internal to this code, and signal assignments:
3990:
3991: =over 4
3992:
3993: =item *
3994:
3995: PID is stored in B<logs/lond.pid>
3996:
3997: This is the process id number of the parent B<lond> process.
3998:
3999: =item *
4000:
4001: SIGTERM and SIGINT
4002:
4003: Parent signal assignment:
4004: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
4005:
4006: Child signal assignment:
4007: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
4008: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
4009: to restart a new child.)
4010:
4011: Command-line invocations:
4012: B<kill> B<-s> SIGTERM I<PID>
4013: B<kill> B<-s> SIGINT I<PID>
4014:
4015: Subroutine B<HUNTSMAN>:
4016: This is only invoked for the B<lond> parent I<PID>.
4017: This kills all the children, and then the parent.
4018: The B<lonc.pid> file is cleared.
4019:
4020: =item *
4021:
4022: SIGHUP
4023:
4024: Current bug:
4025: This signal can only be processed the first time
4026: on the parent process. Subsequent SIGHUP signals
4027: have no effect.
4028:
4029: Parent signal assignment:
4030: $SIG{HUP} = \&HUPSMAN;
4031:
4032: Child signal assignment:
4033: none (nothing happens)
4034:
4035: Command-line invocations:
4036: B<kill> B<-s> SIGHUP I<PID>
4037:
4038: Subroutine B<HUPSMAN>:
4039: This is only invoked for the B<lond> parent I<PID>,
4040: This kills all the children, and then the parent.
4041: The B<lond.pid> file is cleared.
4042:
4043: =item *
4044:
4045: SIGUSR1
4046:
4047: Parent signal assignment:
4048: $SIG{USR1} = \&USRMAN;
4049:
4050: Child signal assignment:
4051: $SIG{USR1}= \&logstatus;
4052:
4053: Command-line invocations:
4054: B<kill> B<-s> SIGUSR1 I<PID>
4055:
4056: Subroutine B<USRMAN>:
4057: When invoked for the B<lond> parent I<PID>,
4058: SIGUSR1 is sent to all the children, and the status of
4059: each connection is logged.
1.144 foxr 4060:
4061: =item *
4062:
4063: SIGUSR2
4064:
4065: Parent Signal assignment:
4066: $SIG{USR2} = \&UpdateHosts
4067:
4068: Child signal assignment:
4069: NONE
4070:
1.74 harris41 4071:
4072: =item *
4073:
4074: SIGCHLD
4075:
4076: Parent signal assignment:
4077: $SIG{CHLD} = \&REAPER;
4078:
4079: Child signal assignment:
4080: none
4081:
4082: Command-line invocations:
4083: B<kill> B<-s> SIGCHLD I<PID>
4084:
4085: Subroutine B<REAPER>:
4086: This is only invoked for the B<lond> parent I<PID>.
4087: Information pertaining to the child is removed.
4088: The socket port is cleaned up.
4089:
4090: =back
4091:
4092: B<SERVER-SIDE ACTIVITIES>
4093:
4094: Server-side information can be accepted in an encrypted or non-encrypted
4095: method.
4096:
4097: =over 4
4098:
4099: =item ping
4100:
4101: Query a client in the hosts.tab table; "Are you there?"
4102:
4103: =item pong
4104:
4105: Respond to a ping query.
4106:
4107: =item ekey
4108:
4109: Read in encrypted key, make cipher. Respond with a buildkey.
4110:
4111: =item load
4112:
4113: Respond with CPU load based on a computation upon /proc/loadavg.
4114:
4115: =item currentauth
4116:
4117: Reply with current authentication information (only over an
4118: encrypted channel).
4119:
4120: =item auth
4121:
4122: Only over an encrypted channel, reply as to whether a user's
4123: authentication information can be validated.
4124:
4125: =item passwd
4126:
4127: Allow for a password to be set.
4128:
4129: =item makeuser
4130:
4131: Make a user.
4132:
4133: =item passwd
4134:
4135: Allow for authentication mechanism and password to be changed.
4136:
4137: =item home
1.61 harris41 4138:
1.74 harris41 4139: Respond to a question "are you the home for a given user?"
4140:
4141: =item update
4142:
4143: Update contents of a subscribed resource.
4144:
4145: =item unsubscribe
4146:
4147: The server is unsubscribing from a resource.
4148:
4149: =item subscribe
4150:
4151: The server is subscribing to a resource.
4152:
4153: =item log
4154:
4155: Place in B<logs/lond.log>
4156:
4157: =item put
4158:
4159: stores hash in namespace
4160:
4161: =item rolesput
4162:
4163: put a role into a user's environment
4164:
4165: =item get
4166:
4167: returns hash with keys from array
4168: reference filled in from namespace
4169:
4170: =item eget
4171:
4172: returns hash with keys from array
4173: reference filled in from namesp (encrypts the return communication)
4174:
4175: =item rolesget
4176:
4177: get a role from a user's environment
4178:
4179: =item del
4180:
4181: deletes keys out of array from namespace
4182:
4183: =item keys
4184:
4185: returns namespace keys
4186:
4187: =item dump
4188:
4189: dumps the complete (or key matching regexp) namespace into a hash
4190:
4191: =item store
4192:
4193: stores hash permanently
4194: for this url; hashref needs to be given and should be a \%hashname; the
4195: remaining args aren't required and if they aren't passed or are '' they will
4196: be derived from the ENV
4197:
4198: =item restore
4199:
4200: returns a hash for a given url
4201:
4202: =item querysend
4203:
4204: Tells client about the lonsql process that has been launched in response
4205: to a sent query.
4206:
4207: =item queryreply
4208:
4209: Accept information from lonsql and make appropriate storage in temporary
4210: file space.
4211:
4212: =item idput
4213:
4214: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
4215: for each student, defined perhaps by the institutional Registrar.)
4216:
4217: =item idget
4218:
4219: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
4220: for each student, defined perhaps by the institutional Registrar.)
4221:
4222: =item tmpput
4223:
4224: Accept and store information in temporary space.
4225:
4226: =item tmpget
4227:
4228: Send along temporarily stored information.
4229:
4230: =item ls
4231:
4232: List part of a user's directory.
4233:
1.135 foxr 4234: =item pushtable
4235:
4236: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
4237: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
4238: must be restored manually in case of a problem with the new table file.
4239: pushtable requires that the request be encrypted and validated via
4240: ValidateManager. The form of the command is:
4241: enc:pushtable tablename <tablecontents> \n
4242: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
4243: cleartext newline.
4244:
1.74 harris41 4245: =item Hanging up (exit or init)
4246:
4247: What to do when a client tells the server that they (the client)
4248: are leaving the network.
4249:
4250: =item unknown command
4251:
4252: If B<lond> is sent an unknown command (not in the list above),
4253: it replys to the client "unknown_cmd".
1.135 foxr 4254:
1.74 harris41 4255:
4256: =item UNKNOWN CLIENT
4257:
4258: If the anti-spoofing algorithm cannot verify the client,
4259: the client is rejected (with a "refused" message sent
4260: to the client, and the connection is closed.
4261:
4262: =back
1.61 harris41 4263:
4264: =head1 PREREQUISITES
4265:
4266: IO::Socket
4267: IO::File
4268: Apache::File
4269: Symbol
4270: POSIX
4271: Crypt::IDEA
4272: LWP::UserAgent()
4273: GDBM_File
4274: Authen::Krb4
1.91 albertel 4275: Authen::Krb5
1.61 harris41 4276:
4277: =head1 COREQUISITES
4278:
4279: =head1 OSNAMES
4280:
4281: linux
4282:
4283: =head1 SCRIPT CATEGORIES
4284:
4285: Server/Process
4286:
4287: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>