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