Annotation of loncom/LondConnection.pm, revision 1.25

1.2       albertel    1: #   This module defines and implements a class that represents
                      2: #   a connection to a lond daemon.
                      3: #
1.25    ! albertel    4: # $Id: LondConnection.pm,v 1.24 2004/02/09 10:57:37 foxr Exp $
1.2       albertel    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/
1.1       foxr       27: #
1.14      foxr       28: 
1.1       foxr       29: package LondConnection;
                     30: 
1.10      foxr       31: use strict;
1.1       foxr       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;
1.14      foxr       39: 
1.1       foxr       40: 
1.12      foxr       41: 
                     42: 
                     43: 
1.6       foxr       44: my $DebugLevel=0;
1.12      foxr       45: my %hostshash;
                     46: my %perlvar;
1.1       foxr       47: 
1.14      foxr       48: #
1.16      foxr       49: #  Set debugging level
                     50: #
                     51: sub SetDebug {
                     52:     $DebugLevel = shift;
                     53: }
                     54: 
                     55: #
1.14      foxr       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: 
1.1       foxr       63: #   Read the configuration file for apache to get the perl
                     64: #   variable set.
                     65: 
1.12      foxr       66: sub ReadConfig {
1.14      foxr       67:     my $perlvarref = read_conf('loncapa.conf');
1.12      foxr       68:     %perlvar    = %{$perlvarref};
1.14      foxr       69:     my $hoststab   = read_hosts(
1.21      foxr       70: 				"$perlvar{lonTabDir}/hosts.tab") || 
1.14      foxr       71: 				die "Can't read host table!!";
1.12      foxr       72:     %hostshash  = %{$hoststab};
1.17      foxr       73:     $ConfigRead = 1;
1.12      foxr       74:     
                     75: }
                     76: 
1.15      foxr       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: 
1.17      foxr       95:     &Debug(4, "ReadForeignConfig $MyHost $Filename\n");
                     96: 
1.15      foxr       97:     $perlvar{lonHostID} = $MyHost; # Rmember my host.
                     98:     my $hosttab = read_hosts($Filename) ||
                     99: 	die "Can't read hosts table!!";
1.17      foxr      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;
1.1       foxr      107: 
1.15      foxr      108: }
1.1       foxr      109: 
                    110: sub Debug {
                    111:     my $level   = shift;
                    112:     my $message = shift;
                    113:     if ($level < $DebugLevel) {
                    114: 	print($message."\n");
                    115:     }
                    116: }
1.3       albertel  117: 
                    118: =pod
                    119: 
                    120: =head2 Dump
                    121: 
1.12      foxr      122: Dump the internal state of the object: For debugging purposes, to stderr.
1.3       albertel  123: 
1.1       foxr      124: =cut
                    125: 
                    126: sub Dump {
                    127:     my $self   = shift;
1.10      foxr      128:     my $key;
                    129:     my $value;
1.22      foxr      130:     print STDERR "Dumping LondConnectionObject:\n";
1.1       foxr      131:     while(($key, $value) = each %$self) {
1.22      foxr      132: 	print STDERR "$key -> $value\n";
1.1       foxr      133:     }
1.23      foxr      134:     print STDERR "-------------------------------\n";
1.1       foxr      135: }
                    136: 
                    137: =pod
1.3       albertel  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: 
1.1       foxr      143: =cut
1.3       albertel  144: 
1.1       foxr      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: 
1.3       albertel  156: 
1.14      foxr      157: 
1.1       foxr      158: =pod
1.3       albertel  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: 
1.1       foxr      174: =cut
1.3       albertel  175: 
1.1       foxr      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 
1.14      foxr      180: 
                    181:     if (!$ConfigRead) {
                    182: 	ReadConfig();
                    183: 	$ConfigRead = 1;
                    184:     }
1.1       foxr      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}) {
1.16      foxr      194: 	&Debug(8, "No Such host $Hostname");
1.1       foxr      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,
1.24      foxr      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};
1.1       foxr      217:     bless($self, $class);
                    218:     unless ($self->{Socket} = IO::Socket::INET->new(PeerHost => $self->{Host},
1.25    ! albertel  219: 						    PeerPort => $self->{Port},
        !           220: 						    Type     => SOCK_STREAM,
        !           221: 						    Proto    => "tcp",
        !           222: 						    Timeout  => 3)) {
1.1       foxr      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
1.9       foxr      230:     $self->{Timeoutable}        = 1;    # Timeout allowed during startup negotiation. 
1.1       foxr      231:     $self->{TransactionRequest} = "init\n";
                    232:     
                    233:     #
                    234:     # Set socket to nonblocking I/O.
                    235:     #
                    236:     my $socket = $self->{Socket};
1.10      foxr      237:     my $flags    = fcntl($socket->fileno, F_GETFL,0);
1.1       foxr      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: }
1.3       albertel  251: 
1.1       foxr      252: =pod
1.3       albertel  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.
1.1       foxr      275: 
                    276: =cut
1.3       albertel  277: 
1.1       foxr      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: 
1.8       foxr      285:     unless (defined($rv) && length $data) {# Read failed,
1.1       foxr      286: 	if(($errno == POSIX::EWOULDBLOCK)   ||
                    287: 	   ($errno == POSIX::EAGAIN)        ||
1.8       foxr      288: 	   ($errno == POSIX::EINTR)) {
1.1       foxr      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:
1.10      foxr      306: 	    if($self->{TransactionReply} eq "refused\n") {	# Remote doesn't have
1.1       foxr      307: 		
                    308: 		$self->Transition("Disconnected"); # in host tables.
                    309: 		$socket->close();
                    310: 		return -1;
                    311: 	    }
1.25    ! albertel  312: 	    
1.1       foxr      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;
1.25    ! albertel  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;
1.24      foxr      339: 	} elsif ($self->{State} eq "HostSet") { # should be ok.
1.25    ! albertel  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;
1.1       foxr      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;
1.13      foxr      360: 	    if($self->{Cipher} eq undef) {
1.1       foxr      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;
1.25    ! albertel  398: 
1.1       foxr      399: }
                    400: 
                    401: 
                    402: =pod
1.3       albertel  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.
1.1       foxr      409: 
                    410: Returns  0 if successful, or -1 if not.
1.3       albertel  411: 
1.1       foxr      412: =cut
1.25    ! albertel  413: 
1.1       foxr      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:     }
1.10      foxr      426:     if (($nwritten >= 0)                        ||
1.1       foxr      427:         ($errno == POSIX::EWOULDBLOCK)    ||
                    428: 	($errno == POSIX::EAGAIN)         ||
                    429: 	($errno == POSIX::EINTR)          ||
                    430: 	($errno ==  0)) {
                    431: 	substr($self->{TransactionRequest}, 0, $nwritten) = ""; # rmv written part
1.25    ! albertel  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");
1.24      foxr      449: #            $self->{InformWritable} = 0;
                    450: #            $self->{InformReadable} = 1;
                    451: #            $self->{TransactionReply} = '';
1.25    ! albertel  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:     }
1.1       foxr      465: }
1.25    ! albertel  466: 
1.1       foxr      467: =pod
1.3       albertel  468: 
                    469: =head2 Tick
                    470: 
1.1       foxr      471:    Tick is called every time unit by the event framework.  It
1.3       albertel  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.
1.1       foxr      476: 
                    477: =cut
                    478:     
                    479: sub Tick {
                    480:     my $self = shift;
                    481:     $self->{TimeoutRemaining}--;
                    482:     if ($self->{TimeoutRemaining} < 0) {
                    483: 	$self->TimedOut();
                    484:     }
                    485: }
1.3       albertel  486: 
1.1       foxr      487: =pod
                    488: 
1.3       albertel  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: 
1.1       foxr      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: }
1.3       albertel  505: 
1.1       foxr      506: =pod
1.3       albertel  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: 
1.1       foxr      517: =cut
1.3       albertel  518: 
1.1       foxr      519: sub InitiateTransaction {
                    520:     my $self   = shift;
                    521:     my $data   = shift;
                    522: 
1.4       foxr      523:     Debug(1, "initiating transaction: ".$data);
1.1       foxr      524:     if($self->{State} ne "Idle") {
1.4       foxr      525: 	Debug(0," .. but not idle here\n");
1.1       foxr      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
1.3       albertel  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: 
1.1       foxr      553: =cut
1.3       albertel  554: 
1.1       foxr      555: sub SetStateTransitionCallback {
                    556:     my $self        = shift;
                    557:     my $oldCallback = $self->{TransitionCallback};
                    558:     $self->{TransitionCallback} = shift;
                    559:     return $oldCallback;
                    560: }
1.3       albertel  561: 
1.1       foxr      562: =pod
1.3       albertel  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: 
1.1       foxr      569: =cut
1.3       albertel  570: 
1.1       foxr      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
1.3       albertel  580: 
1.5       foxr      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();
1.20      albertel  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:     }
1.5       foxr      599: }
                    600: 
                    601: =pod
                    602: 
1.3       albertel  603: =head2 GetState
                    604: 
                    605: selector for the object state.
                    606: 
1.1       foxr      607: =cut
1.3       albertel  608: 
1.1       foxr      609: sub GetState {
                    610:     my $self = shift;
                    611:     return $self->{State};
                    612: }
1.3       albertel  613: 
1.1       foxr      614: =pod
1.3       albertel  615: 
                    616: =head2 GetSocket
                    617: 
                    618: selector for the object socket.
                    619: 
1.1       foxr      620: =cut
1.3       albertel  621: 
1.1       foxr      622: sub GetSocket {
                    623:     my $self  = shift;
                    624:     return $self->{Socket};
                    625: }
1.3       albertel  626: 
1.5       foxr      627: 
1.1       foxr      628: =pod
1.3       albertel  629: 
                    630: =head2 WantReadable
                    631: 
                    632: Return the state of the flag that indicates the object wants to be
                    633: called when readable.
                    634: 
1.1       foxr      635: =cut
1.3       albertel  636: 
1.1       foxr      637: sub WantReadable {
                    638:     my   $self = shift;
                    639: 
                    640:     return $self->{InformReadable};
                    641: }
1.3       albertel  642: 
1.1       foxr      643: =pod
1.3       albertel  644: 
                    645: =head2 WantWritable
                    646: 
                    647: Return the state of the flag that indicates the object wants write
                    648: notification.
                    649: 
1.1       foxr      650: =cut
1.3       albertel  651: 
1.1       foxr      652: sub WantWritable {
                    653:     my $self = shift;
                    654:     return $self->{InformWritable};
                    655: }
1.3       albertel  656: 
1.1       foxr      657: =pod
1.3       albertel  658: 
                    659: =head2 WantTimeout
                    660: 
                    661: return the state of the flag that indicates the object wants to be
                    662: informed of timeouts.
                    663: 
1.1       foxr      664: =cut
1.3       albertel  665: 
1.1       foxr      666: sub WantTimeout {
                    667:     my $self = shift;
                    668:     return $self->{Timeoutable};
                    669: }
                    670: 
                    671: =pod
1.3       albertel  672: 
                    673: =head2 GetReply
                    674: 
                    675: Returns the reply from the last transaction.
                    676: 
1.1       foxr      677: =cut
1.3       albertel  678: 
1.1       foxr      679: sub GetReply {
                    680:     my $self = shift;
                    681:     return $self->{TransactionReply};
                    682: }
                    683: 
                    684: =pod
1.3       albertel  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: 
1.1       foxr      692:   encrypt:command
1.3       albertel  693: 
                    694: The output string can be directly sent to lond as it is of the form:
                    695: 
1.1       foxr      696:   enc:length:<encodedrequest>
1.3       albertel  697: 
1.1       foxr      698: =cut
1.3       albertel  699: 
1.1       foxr      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: }
1.3       albertel  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: 
1.1       foxr      741: =cut
1.3       albertel  742: 
1.1       foxr      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: 
1.10      foxr      755:     my $decrypted = "";
1.1       foxr      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
1.3       albertel  774: 
                    775: =head2 GetHostIterator
1.1       foxr      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: 
1.3       albertel  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.
1.11      foxr      786:  [4]   - IP address (result of e.g. nslookup [3]).
1.3       albertel  787:  [5]   - Maximum connection count.
                    788:  [6]   - Idle timeout for reducing connection count.
                    789:  [7]   - Minimum connection count.
1.1       foxr      790: 
1.3       albertel  791: =cut
1.1       foxr      792: 
                    793: sub GetHostIterator {
                    794: 
                    795:     return HashIterator->new(\%hostshash);    
                    796: }
1.14      foxr      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:       {
1.21      foxr      820: 	  if($DebugLevel > 3) {
                    821: 	      print("Going to read $confdir.$filename\n");
                    822: 	  }
1.14      foxr      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:       }
1.21      foxr      836:     if($DebugLevel > 3) {
                    837: 	print "Dumping perlvar:\n";
                    838: 	foreach my $var (keys %perlvar) {
                    839: 	    print "$var = $perlvar{$var}\n";
                    840: 	}
                    841:     }
1.14      foxr      842:     my $perlvarref=\%perlvar;
1.21      foxr      843:     return $perlvarref;
                    844: }
1.14      foxr      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:     
1.16      foxr      858:    open(CONFIG,'<'.$Filename) or die("Can't read $Filename");
1.14      foxr      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: }
1.24      foxr      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: }
1.1       foxr      895: 
                    896: 1;
                    897: 
                    898: =pod
1.3       albertel  899: 
1.1       foxr      900: =head1 Theory
                    901: 
1.3       albertel  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.
1.1       foxr      950: 
                    951: =head2 Member data.
                    952: 
1.3       albertel  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.
1.1       foxr     1004: 
                   1005: 
                   1006: =head2 The following are callback like members:
1.3       albertel 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: 
1.1       foxr     1024: 
                   1025: =head2 The following are operational member functions.
1.3       albertel 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.
1.5       foxr     1051: 
                   1052: =item Shutdown:
                   1053: 
                   1054: Shuts off the socket.
1.1       foxr     1055: 
                   1056: =head2 The following are selector member functions:
                   1057: 
1.3       albertel 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: 
1.1       foxr     1082: =cut

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