File:  [LON-CAPA] / loncom / LondConnection.pm
Revision 1.25: download - view: text, annotated - select for diffs
Mon Feb 9 13:33:16 2004 UTC (20 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
-fix tabination

    1: #   This module defines and implements a class that represents
    2: #   a connection to a lond daemon.
    3: #
    4: # $Id: LondConnection.pm,v 1.25 2004/02/09 13:33:16 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package LondConnection;
   30: 
   31: use strict;
   32: use IO::Socket;
   33: use IO::Socket::INET;
   34: use IO::Handle;
   35: use IO::File;
   36: use Fcntl;
   37: use POSIX;
   38: use Crypt::IDEA;
   39: 
   40: 
   41: 
   42: 
   43: 
   44: my $DebugLevel=0;
   45: my %hostshash;
   46: my %perlvar;
   47: 
   48: #
   49: #  Set debugging level
   50: #
   51: sub SetDebug {
   52:     $DebugLevel = shift;
   53: }
   54: 
   55: #
   56: #   The config read is done in this way to support the read of
   57: #   the non-default configuration file in the
   58: #   event we are being used outside of loncapa.
   59: #
   60: 
   61: my $ConfigRead = 0;
   62: 
   63: #   Read the configuration file for apache to get the perl
   64: #   variable set.
   65: 
   66: sub ReadConfig {
   67:     my $perlvarref = read_conf('loncapa.conf');
   68:     %perlvar    = %{$perlvarref};
   69:     my $hoststab   = read_hosts(
   70: 				"$perlvar{lonTabDir}/hosts.tab") || 
   71: 				die "Can't read host table!!";
   72:     %hostshash  = %{$hoststab};
   73:     $ConfigRead = 1;
   74:     
   75: }
   76: 
   77: #
   78: #  Read a foreign configuration.
   79: #  This sub is intended for the cases where the package
   80: #  will be read from outside the LonCAPA environment, in that case
   81: #  the client will need to explicitly provide:
   82: #   - A file in hosts.tab format.
   83: #   - Some idea of the 'lonCAPA' name of the local host (for building
   84: #     the encryption key).
   85: #
   86: #  Parameters:
   87: #      MyHost   - Name of this host as far as LonCAPA is concerned.
   88: #      Filename - Name of a hosts.tab formatted file that will be used
   89: #                 to build up the hosts table.
   90: #
   91: sub ReadForeignConfig {
   92:     my $MyHost   = shift;
   93:     my $Filename = shift;
   94: 
   95:     &Debug(4, "ReadForeignConfig $MyHost $Filename\n");
   96: 
   97:     $perlvar{lonHostID} = $MyHost; # Rmember my host.
   98:     my $hosttab = read_hosts($Filename) ||
   99: 	die "Can't read hosts table!!";
  100:     %hostshash = %{$hosttab};
  101:     if($DebugLevel > 3) {
  102: 	foreach my $host (keys %hostshash) {
  103: 	    print "host $host => $hostshash{$host}\n";
  104: 	}
  105:     }
  106:     $ConfigRead = 1;
  107: 
  108: }
  109: 
  110: sub Debug {
  111:     my $level   = shift;
  112:     my $message = shift;
  113:     if ($level < $DebugLevel) {
  114: 	print($message."\n");
  115:     }
  116: }
  117: 
  118: =pod
  119: 
  120: =head2 Dump
  121: 
  122: Dump the internal state of the object: For debugging purposes, to stderr.
  123: 
  124: =cut
  125: 
  126: sub Dump {
  127:     my $self   = shift;
  128:     my $key;
  129:     my $value;
  130:     print STDERR "Dumping LondConnectionObject:\n";
  131:     while(($key, $value) = each %$self) {
  132: 	print STDERR "$key -> $value\n";
  133:     }
  134:     print STDERR "-------------------------------\n";
  135: }
  136: 
  137: =pod
  138: 
  139: Local function to do a state transition.  If the state transition
  140: callback is defined it is called with two parameters: the self and the
  141: old state.
  142: 
  143: =cut
  144: 
  145: sub Transition {
  146:     my $self     = shift;
  147:     my $newstate = shift;
  148:     my $oldstate = $self->{State};
  149:     $self->{State} = $newstate;
  150:     $self->{TimeoutRemaining} = $self->{TimeoutValue};
  151:     if($self->{TransitionCallback}) {
  152: 	($self->{TransitionCallback})->($self, $oldstate); 
  153:     }
  154: }
  155: 
  156: 
  157: 
  158: =pod
  159: 
  160: =head2 new
  161: 
  162: Construct a new lond connection.
  163: 
  164: Parameters (besides the class name) include:
  165: 
  166: =item hostname
  167: 
  168: host the remote lond is on. This host is a host in the hosts.tab file
  169: 
  170: =item port
  171: 
  172:  port number the remote lond is listening on.
  173: 
  174: =cut
  175: 
  176: sub new {
  177:     my $class    = shift;	# class name.
  178:     my $Hostname = shift;	# Name of host to connect to.
  179:     my $Port     = shift;	# Port to connect 
  180: 
  181:     if (!$ConfigRead) {
  182: 	ReadConfig();
  183: 	$ConfigRead = 1;
  184:     }
  185:     &Debug(4,$class."::new( ".$Hostname.",".$Port.")\n");
  186: 
  187:     # The host must map to an entry in the hosts table:
  188:     #  We connect to the dns host that corresponds to that
  189:     #  system and use the hostname for the encryption key 
  190:     #  negotion.  In the objec these become the Host and
  191:     #  LoncapaHim fields of the object respectively.
  192:     #
  193:     if (!exists $hostshash{$Hostname}) {
  194: 	&Debug(8, "No Such host $Hostname");
  195: 	return undef;		# No such host!!!
  196:     }
  197:     my @ConfigLine = @{$hostshash{$Hostname}};
  198:     my $DnsName    = $ConfigLine[3]; # 4'th item is dns of host.
  199:     Debug(5, "Connecting to ".$DnsName);
  200:     # Now create the object...
  201:     my $self     = { Host               => $DnsName,
  202:                      LoncapaHim         => $Hostname,
  203:                      Port               => $Port,
  204:                      State              => "Initialized",
  205:                      TransactionRequest => "",
  206:                      TransactionReply   => "",
  207:                      InformReadable     => 0,
  208:                      InformWritable     => 0,
  209:                      TimeoutCallback    => undef,
  210:                      TransitionCallback => undef,
  211:                      Timeoutable        => 0,
  212:                      TimeoutValue       => 30,
  213:                      TimeoutRemaining   => 0,
  214:                      CipherKey          => "",
  215:                      LondVersion        => "Unknown",
  216:                      Cipher             => undef};
  217:     bless($self, $class);
  218:     unless ($self->{Socket} = IO::Socket::INET->new(PeerHost => $self->{Host},
  219: 						    PeerPort => $self->{Port},
  220: 						    Type     => SOCK_STREAM,
  221: 						    Proto    => "tcp",
  222: 						    Timeout  => 3)) {
  223: 	return undef;		# Inidicates the socket could not be made.
  224:     }
  225:     #
  226:     # We're connected.  Set the state, and the events we'll accept:
  227:     #
  228:     $self->Transition("Connected");
  229:     $self->{InformWritable}     = 1;    # When  socket is writable we send init
  230:     $self->{Timeoutable}        = 1;    # Timeout allowed during startup negotiation. 
  231:     $self->{TransactionRequest} = "init\n";
  232:     
  233:     #
  234:     # Set socket to nonblocking I/O.
  235:     #
  236:     my $socket = $self->{Socket};
  237:     my $flags    = fcntl($socket->fileno, F_GETFL,0);
  238:     if($flags == -1) {
  239: 	$socket->close;
  240: 	return undef;
  241:     }
  242:     if(fcntl($socket, F_SETFL, $flags | O_NONBLOCK) == -1) {
  243: 	$socket->close;
  244: 	return undef;
  245:     }
  246: 
  247:     # return the object :
  248: 
  249:     return $self;
  250: }
  251: 
  252: =pod
  253: 
  254: =head2 Readable
  255: 
  256: This member should be called when the Socket becomes readable.  Until
  257: the read completes, action is state independet. Data are accepted into
  258: the TransactionReply until a newline character is received.  At that
  259: time actionis state dependent:
  260: 
  261: =item Connected
  262: 
  263: in this case we received challenge, the state changes to
  264: ChallengeReceived, and we initiate a send with the challenge response.
  265: 
  266: =item ReceivingReply
  267: 
  268: In this case a reply has been received for a transaction, the state
  269: goes to Idle and we disable write and read notification.
  270: 
  271: =item ChallengeReeived
  272: 
  273: we just got what should be an ok\n and the connection can now handle
  274: transactions.
  275: 
  276: =cut
  277: 
  278: sub Readable {
  279:     my $self    = shift;
  280:     my $socket  = $self->{Socket};
  281:     my $data    = '';
  282:     my $rv      = $socket->recv($data, POSIX::BUFSIZ,  0);
  283:     my $errno   = $! + 0;	             # Force numeric context.
  284: 
  285:     unless (defined($rv) && length $data) {# Read failed,
  286: 	if(($errno == POSIX::EWOULDBLOCK)   ||
  287: 	   ($errno == POSIX::EAGAIN)        ||
  288: 	   ($errno == POSIX::EINTR)) {
  289: 	    return 0;
  290: 	}
  291: 
  292: 	# Connection likely lost.
  293: 	&Debug(4, "Connection lost");
  294: 	$self->{TransactionRequest} = '';
  295: 	$socket->close();
  296: 	$self->Transition("Disconnected");
  297: 	return -1;
  298:     }
  299:     #  Append the data to the buffer.  And figure out if the read is done:
  300: 
  301:     &Debug(9,"Received from host: ".$data);
  302:     $self->{TransactionReply} .= $data;
  303:     if($self->{TransactionReply} =~ /(.*\n)/) {
  304: 	&Debug(8,"Readable End of line detected");
  305: 	if ($self->{State}  eq "Initialized") { # We received the challenge:
  306: 	    if($self->{TransactionReply} eq "refused\n") {	# Remote doesn't have
  307: 		
  308: 		$self->Transition("Disconnected"); # in host tables.
  309: 		$socket->close();
  310: 		return -1;
  311: 	    }
  312: 	    
  313: 	    &Debug(8," Transition out of Initialized");
  314: 	    $self->{TransactionRequest} = $self->{TransactionReply};
  315: 	    $self->{InformWritable}     = 1;
  316: 	    $self->{InformReadable}     = 0;
  317: 	    $self->Transition("ChallengeReceived");
  318: 	    $self->{TimeoutRemaining}   = $self->{TimeoutValue};
  319: 	    return 0;
  320: 	}  elsif ($self->{State} eq "ChallengeReplied") {
  321: 	    if($self->{TransactionReply} ne "ok\n") {
  322: 		$self->Transition("Disconnected");
  323: 		$socket->close();
  324: 		return -1;
  325: 	    }
  326: 	    $self->Transition("RequestingVersion");
  327: 	    $self->{InformReadable}   = 0;
  328: 	    $self->{InformWritable}   = 1;
  329: 	    $self->{TransactionRequest} = "version\n";
  330: 	    return 0;
  331: 	} elsif ($self->{State} eq "ReadingVersionString") {
  332: 	    $self->{LondVersion}       = chomp($self->{TransactionReply});
  333: 	    $self->Transition("SetHost");
  334: 	    $self->{InformReadable}    = 0;
  335: 	    $self->{InformWritable}    = 1;
  336: 	    my $peer = $self->{LoncapaHim};
  337: 	    $self->{TransactionRequest}= "sethost:$peer\n";
  338: 	    return 0;
  339: 	} elsif ($self->{State} eq "HostSet") { # should be ok.
  340: 	    if($self->{TransactionReply} ne "ok\n") {
  341: 		$self->Transition("Disconnected");
  342: 		$socket->close();
  343: 		return -1;
  344: 	    }
  345: 	    $self->Transition("RequestingKey");
  346: 	    $self->{InformReadable}  = 0;
  347: 	    $self->{InformWritable}  = 1;
  348: 	    $self->{TransactionRequest} = "ekey\n";
  349: 	    return 0;
  350: 	} elsif ($self->{State}  eq "ReceivingKey") {
  351: 	    my $buildkey = $self->{TransactionReply};
  352: 	    my $key = $self->{LoncapaHim}.$perlvar{'lonHostID'};
  353: 	    $key=~tr/a-z/A-Z/;
  354: 	    $key=~tr/G-P/0-9/;
  355: 	    $key=~tr/Q-Z/0-9/;
  356: 	    $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
  357: 	    $key=substr($key,0,32);
  358: 	    my $cipherkey=pack("H32",$key);
  359: 	    $self->{Cipher} = new IDEA $cipherkey;
  360: 	    if($self->{Cipher} eq undef) {
  361: 		$self->Transition("Disconnected");
  362: 		$socket->close();
  363: 		return -1;
  364: 	    } else {
  365: 		$self->Transition("Idle");
  366: 		$self->{InformWritable}  =  0;
  367: 		$self->{InformReadable}  =  0;
  368: 		$self->{Timeoutable}     = 0;
  369: 		return 0;
  370: 	    }
  371: 	} elsif ($self->{State}  eq "ReceivingReply") {
  372: 
  373: 	    # If the data are encrypted, decrypt first.
  374: 
  375: 	    my $answer = $self->{TransactionReply};
  376: 	    if($answer =~ /^enc\:/) {
  377: 		$answer = $self->Decrypt($answer);
  378: 		$self->{TransactionReply} = $answer;
  379: 	    }
  380: 
  381: 	    # finish the transaction
  382: 
  383: 	    $self->{InformWritable}     = 0;
  384: 	    $self->{InformReadable}     = 0;
  385: 	    $self->{Timeoutable}        = 0;
  386: 	    $self->Transition("Idle");
  387: 	    return 0;
  388: 	} elsif ($self->{State} eq "Disconnected") { # No connection.
  389: 	    return -1;
  390: 	} else {			# Internal error: Invalid state.
  391: 	    $self->Transition("Disconnected");
  392: 	    $socket->close();
  393: 	    return -1;
  394: 	}
  395:     }
  396: 
  397:     return 0;
  398: 
  399: }
  400: 
  401: 
  402: =pod
  403: 
  404: This member should be called when the Socket becomes writable.
  405: 
  406: The action is state independent. An attempt is made to drain the
  407: contents of the TransactionRequest member.  Once this is drained, we
  408: mark the object as waiting for readability.
  409: 
  410: Returns  0 if successful, or -1 if not.
  411: 
  412: =cut
  413: 
  414: sub Writable {
  415:     my $self     = shift;		# Get reference to the object.
  416:     my $socket   = $self->{Socket};
  417:     my $nwritten = $socket->send($self->{TransactionRequest}, 0);
  418:     my $errno    = $! + 0;
  419:     unless (defined $nwritten) {
  420: 	if($errno != POSIX::EINTR) {
  421: 	    $self->Transition("Disconnected");
  422: 	    return -1;
  423: 	}
  424:       
  425:     }
  426:     if (($nwritten >= 0)                        ||
  427:         ($errno == POSIX::EWOULDBLOCK)    ||
  428: 	($errno == POSIX::EAGAIN)         ||
  429: 	($errno == POSIX::EINTR)          ||
  430: 	($errno ==  0)) {
  431: 	substr($self->{TransactionRequest}, 0, $nwritten) = ""; # rmv written part
  432: 	if(length $self->{TransactionRequest} == 0) {
  433: 	    $self->{InformWritable} = 0;
  434: 	    $self->{InformReadable} = 1;
  435: 	    $self->{TransactionReply} = '';
  436: 	    #
  437: 	    # Figure out the next state:
  438: 	    #
  439: 	    if($self->{State} eq "Connected") {
  440: 		$self->Transition("Initialized");
  441: 	    } elsif($self->{State} eq "ChallengeReceived") {
  442: 		$self->Transition("ChallengeReplied");
  443: 	    } elsif($self->{State} eq "RequestingVersion") {
  444: 		$self->Transition("ReadingVersionString");
  445: 	    } elsif ($self->{State} eq "SetHost") {
  446: 		$self->Transition("HostSet");
  447: 	    } elsif($self->{State} eq "RequestingKey") {
  448: 		$self->Transition("ReceivingKey");
  449: #            $self->{InformWritable} = 0;
  450: #            $self->{InformReadable} = 1;
  451: #            $self->{TransactionReply} = '';
  452: 	    } elsif ($self->{State} eq "SendingRequest") {
  453: 		$self->Transition("ReceivingReply");
  454: 		$self->{TimeoutRemaining} = $self->{TimeoutValue};
  455: 	    } elsif ($self->{State} eq "Disconnected") {
  456: 		return -1;
  457: 	    }
  458: 	    return 0;
  459: 	}
  460:     } else {			# The write failed (e.g. partner disconnected).
  461: 	$self->Transition("Disconnected");
  462: 	$socket->close();
  463: 	return -1;
  464:     }
  465: }
  466: 
  467: =pod
  468: 
  469: =head2 Tick
  470: 
  471:    Tick is called every time unit by the event framework.  It
  472: 
  473: =item 1 decrements the remaining timeout.
  474: 
  475: =item 2 If the timeout is zero, calls TimedOut indicating that the current operation timed out.
  476: 
  477: =cut
  478:     
  479: sub Tick {
  480:     my $self = shift;
  481:     $self->{TimeoutRemaining}--;
  482:     if ($self->{TimeoutRemaining} < 0) {
  483: 	$self->TimedOut();
  484:     }
  485: }
  486: 
  487: =pod
  488: 
  489: =head2 TimedOut
  490: 
  491: called on a timeout.  If the timeout callback is defined, it is called
  492: with $self as its parameters.
  493: 
  494: =cut
  495: 
  496: sub TimedOut  {
  497: 
  498:     my $self = shift;
  499:     if($self->{TimeoutCallback}) {
  500: 	my $callback = $self->{TimeoutCallback};
  501: 	my @args = ( $self);
  502: 	&$callback(@args);
  503:     }
  504: }
  505: 
  506: =pod
  507: 
  508: =head2 InitiateTransaction
  509: 
  510: Called to initiate a transaction.  A transaction can only be initiated
  511: when the object is idle... otherwise an error is returned.  A
  512: transaction consists of a request to the server that will have a
  513: reply.  This member sets the request data in the TransactionRequest
  514: member, makes the state SendingRequest and sets the data to allow a
  515: timout, and to request writability notification.
  516: 
  517: =cut
  518: 
  519: sub InitiateTransaction {
  520:     my $self   = shift;
  521:     my $data   = shift;
  522: 
  523:     Debug(1, "initiating transaction: ".$data);
  524:     if($self->{State} ne "Idle") {
  525: 	Debug(0," .. but not idle here\n");
  526: 	return -1;		# Error indicator.
  527:     }
  528:     # if the transaction is to be encrypted encrypt the data:
  529: 
  530:     if($data =~ /^encrypt\:/) {
  531: 	$data = $self->Encrypt($data);
  532:     }
  533: 
  534:     # Setup the trasaction
  535: 
  536:     $self->{TransactionRequest} = $data;
  537:     $self->{TransactionReply}   = "";
  538:     $self->{InformWritable}     = 1;
  539:     $self->{InformReadable}     = 0;
  540:     $self->{Timeoutable}        = 1;
  541:     $self->{TimeoutRemaining}   = $self->{TimeoutValue};
  542:     $self->Transition("SendingRequest");
  543: }
  544: 
  545: 
  546: =pod
  547: 
  548: =head2 SetStateTransitionCallback
  549: 
  550: Sets a callback for state transitions.  Returns a reference to any
  551: prior established callback, or undef if there was none:
  552: 
  553: =cut
  554: 
  555: sub SetStateTransitionCallback {
  556:     my $self        = shift;
  557:     my $oldCallback = $self->{TransitionCallback};
  558:     $self->{TransitionCallback} = shift;
  559:     return $oldCallback;
  560: }
  561: 
  562: =pod
  563: 
  564: =head2 SetTimeoutCallback
  565: 
  566: Sets the timeout callback.  Returns a reference to any prior
  567: established callback or undef if there was none.
  568: 
  569: =cut
  570: 
  571: sub SetTimeoutCallback {
  572:     my $self                 = shift;
  573:     my $callback             = shift;
  574:     my $oldCallback          = $self->{TimeoutCallback};
  575:     $self->{TimeoutCallback} = $callback;
  576:     return $oldCallback;
  577: }
  578: 
  579: =pod
  580: 
  581: =head2 Shutdown:
  582: 
  583: Shuts down the socket.
  584: 
  585: =cut
  586: 
  587: sub Shutdown {
  588:     my $self = shift;
  589:     my $socket = $self->GetSocket();
  590:     Debug(5,"socket is -$socket-");
  591:     if ($socket) {
  592: 	# Ask lond to exit too.  Non blocking so
  593: 	# there is no cost for failure.
  594: 	eval {
  595: 	    $socket->send("exit\n", 0);
  596: 	    $socket->shutdown(2);
  597: 	}
  598:     }
  599: }
  600: 
  601: =pod
  602: 
  603: =head2 GetState
  604: 
  605: selector for the object state.
  606: 
  607: =cut
  608: 
  609: sub GetState {
  610:     my $self = shift;
  611:     return $self->{State};
  612: }
  613: 
  614: =pod
  615: 
  616: =head2 GetSocket
  617: 
  618: selector for the object socket.
  619: 
  620: =cut
  621: 
  622: sub GetSocket {
  623:     my $self  = shift;
  624:     return $self->{Socket};
  625: }
  626: 
  627: 
  628: =pod
  629: 
  630: =head2 WantReadable
  631: 
  632: Return the state of the flag that indicates the object wants to be
  633: called when readable.
  634: 
  635: =cut
  636: 
  637: sub WantReadable {
  638:     my   $self = shift;
  639: 
  640:     return $self->{InformReadable};
  641: }
  642: 
  643: =pod
  644: 
  645: =head2 WantWritable
  646: 
  647: Return the state of the flag that indicates the object wants write
  648: notification.
  649: 
  650: =cut
  651: 
  652: sub WantWritable {
  653:     my $self = shift;
  654:     return $self->{InformWritable};
  655: }
  656: 
  657: =pod
  658: 
  659: =head2 WantTimeout
  660: 
  661: return the state of the flag that indicates the object wants to be
  662: informed of timeouts.
  663: 
  664: =cut
  665: 
  666: sub WantTimeout {
  667:     my $self = shift;
  668:     return $self->{Timeoutable};
  669: }
  670: 
  671: =pod
  672: 
  673: =head2 GetReply
  674: 
  675: Returns the reply from the last transaction.
  676: 
  677: =cut
  678: 
  679: sub GetReply {
  680:     my $self = shift;
  681:     return $self->{TransactionReply};
  682: }
  683: 
  684: =pod
  685: 
  686: =head2 Encrypt
  687: 
  688: Returns the encrypted version of the command string.
  689: 
  690: The command input string is of the form:
  691: 
  692:   encrypt:command
  693: 
  694: The output string can be directly sent to lond as it is of the form:
  695: 
  696:   enc:length:<encodedrequest>
  697: 
  698: =cut
  699: 
  700: sub Encrypt {
  701:     my $self    = shift;		# Reference to the object.
  702:     my $request = shift;	        # Text to send.
  703: 
  704:    
  705:     # Split the encrypt: off the request and figure out it's length.
  706:     # the cipher works in blocks of 8 bytes.
  707: 
  708:     my $cmd = $request;
  709:     $cmd    =~ s/^encrypt\://;	# strip off encrypt:
  710:     chomp($cmd);		# strip off trailing \n
  711:     my     $length=length($cmd);	# Get the string length.
  712:     $cmd .= "         ";	# Pad with blanks so we can fill out a block.
  713: 
  714:     # encrypt the request in 8 byte chunks to create the encrypted
  715:     # output request.
  716: 
  717:     my $Encoded = '';
  718:     for(my $index = 0; $index <= $length; $index += 8) {
  719: 	$Encoded .= 
  720: 	    unpack("H16", 
  721: 		   $self->{Cipher}->encrypt(substr($cmd, 
  722: 						   $index, 8)));
  723:     }
  724: 
  725:     # Build up the answer as enc:length:$encrequest.
  726: 
  727:     $request = "enc:$length:$Encoded\n";
  728:     return $request;
  729:     
  730:     
  731: }
  732: 
  733: =pod
  734: 
  735: =head2 Decrypt
  736: 
  737: Decrypt a response from the server.  The response is in the form:
  738: 
  739:  enc:<length>:<encrypted data>
  740: 
  741: =cut
  742: 
  743: sub Decrypt {
  744:     my $self      = shift;	# Recover reference to object
  745:     my $encrypted = shift;	# This is the encrypted data.
  746: 
  747:     #  Bust up the response into length, and encryptedstring:
  748: 
  749:     my ($enc, $length, $EncryptedString) = split(/:/,$encrypted);
  750:     chomp($EncryptedString);
  751: 
  752:     # Decode the data in 8 byte blocks.  The string is encoded
  753:     # as hex digits so there are two characters per byte:
  754: 
  755:     my $decrypted = "";
  756:     for(my $index = 0; $index < length($EncryptedString);
  757: 	$index += 16) {
  758: 	$decrypted .= $self->{Cipher}->decrypt(
  759: 				    pack("H16",
  760: 					 substr($EncryptedString,
  761: 						$index, 
  762: 						16)));
  763:     }
  764:     #  the answer may have trailing pads to fill out a block.
  765:     #  $length tells us the actual length of the decrypted string:
  766: 
  767:     $decrypted = substr($decrypted, 0, $length);
  768: 
  769:     return $decrypted;
  770: 
  771: }
  772: 
  773: =pod
  774: 
  775: =head2 GetHostIterator
  776: 
  777: Returns a hash iterator to the host information.  Each get from 
  778: this iterator returns a reference to an array that contains 
  779: information read from the hosts configuration file.  Array elements
  780: are used as follows:
  781: 
  782:  [0]   - LonCapa host name.
  783:  [1]   - LonCapa domain name.
  784:  [2]   - Loncapa role (e.g. library or access).
  785:  [3]   - DNS name server hostname.
  786:  [4]   - IP address (result of e.g. nslookup [3]).
  787:  [5]   - Maximum connection count.
  788:  [6]   - Idle timeout for reducing connection count.
  789:  [7]   - Minimum connection count.
  790: 
  791: =cut
  792: 
  793: sub GetHostIterator {
  794: 
  795:     return HashIterator->new(\%hostshash);    
  796: }
  797: 
  798: ###########################################################
  799: #
  800: #  The following is an unashamed kludge that is here to
  801: # allow LondConnection to be used outside of the
  802: # loncapa environment (e.g. by lonManage).
  803: # 
  804: #   This is a textual inclusion of pieces of the
  805: #   Configuration.pm module.
  806: #
  807: 
  808: 
  809: my $confdir='/etc/httpd/conf/';
  810: 
  811: # ------------------- Subroutine read_conf: read LON-CAPA server configuration.
  812: # This subroutine reads PerlSetVar values out of specified web server
  813: # configuration files.
  814: sub read_conf
  815:   {
  816:     my (@conf_files)=@_;
  817:     my %perlvar;
  818:     foreach my $filename (@conf_files,'loncapa_apache.conf')
  819:       {
  820: 	  if($DebugLevel > 3) {
  821: 	      print("Going to read $confdir.$filename\n");
  822: 	  }
  823: 	open(CONFIG,'<'.$confdir.$filename) or
  824: 	    die("Can't read $confdir$filename");
  825: 	while (my $configline=<CONFIG>)
  826: 	  {
  827: 	    if ($configline =~ /^[^\#]*PerlSetVar/)
  828: 	      {
  829: 		my ($unused,$varname,$varvalue)=split(/\s+/,$configline);
  830: 		chomp($varvalue);
  831: 		$perlvar{$varname}=$varvalue;
  832: 	      }
  833: 	  }
  834: 	close(CONFIG);
  835:       }
  836:     if($DebugLevel > 3) {
  837: 	print "Dumping perlvar:\n";
  838: 	foreach my $var (keys %perlvar) {
  839: 	    print "$var = $perlvar{$var}\n";
  840: 	}
  841:     }
  842:     my $perlvarref=\%perlvar;
  843:     return $perlvarref;
  844: }
  845: 
  846: #---------------------- Subroutine read_hosts: Read a LON-CAPA hosts.tab
  847: # formatted configuration file.
  848: #
  849: my $RequiredCount = 5;		# Required item count in hosts.tab.
  850: my $DefaultMaxCon = 5;		# Default value for maximum connections.
  851: my $DefaultIdle   = 1000;       # Default connection idle time in seconds.
  852: my $DefaultMinCon = 0;          # Default value for minimum connections.
  853: 
  854: sub read_hosts {
  855:     my $Filename = shift;
  856:     my %HostsTab;
  857:     
  858:    open(CONFIG,'<'.$Filename) or die("Can't read $Filename");
  859:     while (my $line = <CONFIG>) {
  860: 	if (!($line =~ /^\s*\#/)) {
  861: 	    my @items = split(/:/, $line);
  862: 	    if(scalar @items >= $RequiredCount) {
  863: 		if (scalar @items == $RequiredCount) { # Only required items:
  864: 		    $items[$RequiredCount] = $DefaultMaxCon;
  865: 		}
  866: 		if(scalar @items == $RequiredCount + 1) { # up through maxcon.
  867: 		    $items[$RequiredCount+1] = $DefaultIdle;
  868: 		}
  869: 		if(scalar @items == $RequiredCount + 2) { # up through idle.
  870: 		    $items[$RequiredCount+2] = $DefaultMinCon;
  871: 		}
  872: 		{
  873: 		    my @list = @items; # probably not needed but I'm unsure of 
  874: 		    # about the scope of item so...
  875: 		    $HostsTab{$list[0]} = \@list; 
  876: 		}
  877: 	    }
  878: 	}
  879:     }
  880:     close(CONFIG);
  881:     my $hostref = \%HostsTab;
  882:     return ($hostref);
  883: }
  884: #
  885: #   Get the version of our peer.  Note that this is only well
  886: #   defined if the state machine has hit the idle state at least
  887: #   once (well actually if it has transitioned out of 
  888: #   ReadingVersionString   The member data LondVersion is returned.
  889: #
  890: sub PeerVersion {
  891:    my $self = shift;
  892:    
  893:    return $self->{LondVersion};
  894: }
  895: 
  896: 1;
  897: 
  898: =pod
  899: 
  900: =head1 Theory
  901: 
  902: The lond object is a state machine.  It lives through the following states:
  903: 
  904: =item Connected:
  905: 
  906: a TCP connection has been formed, but the passkey has not yet been
  907: negotiated.
  908: 
  909: =item Initialized:
  910: 
  911: "init" sent.
  912: 
  913: =item ChallengeReceived:
  914: 
  915: lond sent its challenge to us.
  916: 
  917: =item ChallengeReplied:
  918: 
  919: We replied to lond's challenge waiting for lond's ok.
  920: 
  921: =item RequestingKey:
  922: 
  923: We are requesting an encryption key.
  924: 
  925: =item ReceivingKey:
  926: 
  927: We are receiving an encryption key.
  928: 
  929: =item Idle:
  930: 
  931: Connection was negotiated but no requests are active.
  932: 
  933: =item SendingRequest:
  934: 
  935: A request is being sent to the peer.
  936: 
  937: =item ReceivingReply:
  938: 
  939: Waiting for an entire reply from the peer.
  940: 
  941: =item Disconnected:
  942: 
  943: For whatever reason, the connection was dropped.
  944: 
  945: When we need to be writing data, we have a writable event. When we
  946: need to be reading data, a readable event established.  Events
  947: dispatch through the class functions Readable and Writable, and the
  948: watcher contains a reference to the associated object to allow object
  949: context to be reached.
  950: 
  951: =head2 Member data.
  952: 
  953: =item Host
  954: 
  955: Host socket is connected to.
  956: 
  957: =item Port
  958: 
  959: The port the remote lond is listening on.
  960: 
  961: =item Socket
  962: 
  963: Socket open on the connection.
  964: 
  965: =item State
  966: 
  967: The current state.
  968: 
  969: =item TransactionRequest
  970: 
  971: The request being transmitted.
  972: 
  973: =item TransactionReply
  974: 
  975: The reply being received from the transaction.
  976: 
  977: =item InformReadable
  978: 
  979: True if we want to be called when socket is readable.
  980: 
  981: =item InformWritable
  982: 
  983: True if we want to be informed if the socket is writable.
  984: 
  985: =item Timeoutable
  986: 
  987: True if the current operation is allowed to timeout.
  988: 
  989: =item TimeoutValue
  990: 
  991: Number of seconds in the timeout.
  992: 
  993: =item TimeoutRemaining
  994: 
  995: Number of seconds left in the timeout.
  996: 
  997: =item CipherKey
  998: 
  999: The key that was negotiated with the peer.
 1000: 
 1001: =item Cipher
 1002: 
 1003: The cipher obtained via the key.
 1004: 
 1005: 
 1006: =head2 The following are callback like members:
 1007: 
 1008: =item Tick:
 1009: 
 1010: Called in response to a timer tick. Used to managed timeouts etc.
 1011: 
 1012: =item Readable:
 1013: 
 1014: Called when the socket becomes readable.
 1015: 
 1016: =item Writable:
 1017: 
 1018: Called when the socket becomes writable.
 1019: 
 1020: =item TimedOut:
 1021: 
 1022: Called when a timed operation timed out.
 1023: 
 1024: 
 1025: =head2 The following are operational member functions.
 1026: 
 1027: =item InitiateTransaction:
 1028: 
 1029: Called to initiate a new transaction
 1030: 
 1031: =item SetStateTransitionCallback:
 1032: 
 1033: Called to establish a function that is called whenever the object goes
 1034: through a state transition.  This is used by The client to manage the
 1035: work flow for the object.
 1036: 
 1037: =item SetTimeoutCallback:
 1038: 
 1039: Set a function to be called when a transaction times out.  The
 1040: function will be called with the object as its sole parameter.
 1041: 
 1042: =item Encrypt:
 1043: 
 1044: Encrypts a block of text according to the cipher negotiated with the
 1045: peer (assumes the text is a command).
 1046: 
 1047: =item Decrypt:
 1048: 
 1049: Decrypts a block of text according to the cipher negotiated with the
 1050: peer (assumes the block was a reply.
 1051: 
 1052: =item Shutdown:
 1053: 
 1054: Shuts off the socket.
 1055: 
 1056: =head2 The following are selector member functions:
 1057: 
 1058: =item GetState:
 1059: 
 1060: Returns the current state
 1061: 
 1062: =item GetSocket:
 1063: 
 1064: Gets the socekt open on the connection to lond.
 1065: 
 1066: =item WantReadable:
 1067: 
 1068: true if the current state requires a readable event.
 1069: 
 1070: =item WantWritable:
 1071: 
 1072: true if the current state requires a writable event.
 1073: 
 1074: =item WantTimeout:
 1075: 
 1076: true if the current state requires timeout support.
 1077: 
 1078: =item GetHostIterator:
 1079: 
 1080: Returns an iterator into the host file hash.
 1081: 
 1082: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>