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