Net::EasyTCP(3) Easily create secure, bandwidth-friendly TCP/IP clients and servers

FEATURES

  • One easy module to create both clients and servers
  • Object Oriented interface
  • Event-based callbacks in server mode
  • Internal protocol to take care of all the common transport problems
  • Transparent encryption
  • Transparent compression

SYNOPSIS

SERVER EXAMPLE:


use Net::EasyTCP;
#
# Create the server object
#
$server = new Net::EasyTCP(
mode => "server",
port => 2345,
)
|| die "ERROR CREATING SERVER: $@\n";
#
# Tell it about the callbacks to call
# on known events
#
$server->setcallback(
data => \&gotdata,
connect => \&connected,
disconnect => \&disconnected,
)
|| die "ERROR SETTING CALLBACKS: $@\n";
#
# Start the server
#
$server->start() || die "ERROR STARTING SERVER: $@\n";
#
# This sub gets called when a client sends us data
#
sub gotdata {
my $client = shift;
my $serial = $client->serial();
my $data = $client->data();
print "Client $serial sent me some data, sending it right back to them again\n";
$client->send($data) || die "ERROR SENDING TO CLIENT: $@\n";
if ($data eq "QUIT") {
$client->close() || die "ERROR CLOSING CLIENT: $@\n";
}
elsif ($data eq "DIE") {
$server->stop() || die "ERROR STOPPING SERVER: $@\n";
}
}
#
# This sub gets called when a new client connects
#
sub connected {
my $client = shift;
my $serial = $client->serial();
print "Client $serial just connected\n";
}
#
# This sub gets called when an existing client disconnects
#
sub disconnected {
my $client = shift;
my $serial = $client->serial();
print "Client $serial just disconnected\n";
}

CLIENT EXAMPLE:
        use Net::EasyTCP;
        #
        # Create a new client and connect to a server
        #
        $client = new Net::EasyTCP(
                mode            =>      "client",
                host            =>      'localhost',
                port            =>      2345,
        )
        || die "ERROR CREATING CLIENT: $@\n";
        #
        # Send and receive a simple string
        #
        $client->send("HELLO THERE") || die "ERROR SENDING: $@\n";
        $reply = $client->receive() || die "ERROR RECEIVING: $@\n";
        #
        # Send and receive complex objects/strings/arrays/hashes by reference
        #
        %hash = ("to be or" => "not to be" , "just another" => "perl hacker");
        $client->send(\%hash) || die "ERROR SENDING: $@\n";
        $reply = $client->receive() || die "ERROR RECEIVING: $@\n";
        foreach (keys %{$reply}) {
                print "Received key: $_ = $reply->{$_}\n";
        }
        #
        # Send and receive large binary data
        #
        for (1..8192) {
                for (0..255) {
                        $largedata .= chr($_);
                }
        }
        $client->send($largedata) || die "ERROR SENDING: $@\n";
        $reply = $client->receive() || die "ERROR RECEIVING: $@\n";
        #
        # Cleanly disconnect from the server
        #
        $client->close();

DESCRIPTION

This class allows you to easily create TCP/IP clients and servers and provides an OO interface to manage the connection(s). This allows you to concentrate on the application rather than on the transport.

You still have to engineer your high-level protocol. For example, if you're writing an SMTP client-server pair, you will have to teach your client to send ``HELO'' when it connects, and you will have to teach your server what to do once it receives the ``HELO'' command, and so forth.

What you won't have to do is worry about how the command will get there, about line termination, about binary data, complex-structure serialization, encryption, compression, or about fragmented packets on the received end. All of these will be taken care of by this class.

CONSTRUCTOR

new(%hash)
Constructs and returns a new Net::EasyTCP object. Such an object behaves in one of two modes (that needs to be supplied to new() on creation time). You can create either a server object (which accepts connections from several clients) or a client object (which initiates a connection to a server).

new() expects to be passed a hash. The following keys are accepted:

donotcheckversion
Set to 1 to force a client to continue connecting even if an encryption/compression/Storable module version mismatch is detected. (Using this is highly unrecommended, you should upgrade the module in question to the same version on both ends) Note that as of Net::EasyTCP version 0.20, this parameter is fairly useless since that version (and higher) do not require external modules to have the same version anymore, but instead determine compatability between different versions dynamically. See the accompanying Changes file for more details. (Optional and acceptable when mode is ``client'')
donotcompress
Set to 1 to forcefully disable compression even if the appropriate module(s) are found. (Optional)
donotcompresswith
Set to a scalar or an arrayref of compression module(s) you'd like to avoid compressing with. For example, if you do not want to use Compress::LZF, you can do so by utilizing this option. (Optional)
donotencrypt
Set to 1 to forcefully disable encryption even if the appropriate module(s) are found. (Optional)
donotencryptwith
Set to a scalar or an arrayref of encryption module(s) you'd like to avoid encrypting with. For example, Crypt::RSA takes a long time to initialize keys and encrypt/decrypt, so you can avoid using it by utilizing this option. (Optional)
host
Must be set to the hostname/IP address to connect to. (Mandatory when mode is ``client'')
mode
Must be set to either ``client'' or ``server'' according to the type of object you want returned. (Mandatory)
password
Defines a password to use for the connection. When mode is ``server'' this password will be required from clients before the full connection is accepted . When mode is ``client'' this is the password that the server connecting to requires.

Also, when encryption using a symmetric encryption module is used, this password is included as part of the secret ``key'' for encrypting the data. (Optional)

port
Must be set to the port the client connects to (if mode is ``client'') or to the port to listen to (if mode is ``server''). If you're writing a client+server pair, they must both use the same port number. (Mandatory)
timeout
Set to an integer (seconds) that a client attempting to establish a TCP/IP connection to a server will timeout after. If not supplied, the default is 30 seconds. (Optional and acceptable only when mode is ``client'')
welcome
If someone uses an interactive telnet program to telnet to the server, they will see this welcome message. (Optional and acceptable only when mode is ``server'')

METHODS

[C] = Available to objects created as mode ``client''

[H] = Available to ``hybrid'' client objects, as in ``the server-side client objects created when a new client connects''. These are the objects passed to your server's callbacks. Such hybrid clients behave almost exactly like a normal ``client'' object you create yourself, except for a slight difference in the available methods to retrieve data.

[S] = Available to objects created as mode ``server''

addclientip(@array)
[S] Adds an IP address (or IP addresses) to the list of allowed clients to a server. If this is done, the server will not accept connections from clients not in it's list.

The compliment of this function is deleteclientip() .

callback(%hash)
See setcallback()
clients()
[S] Returns all the clients currently connected to the server. If called in array context will return an array of client objects. If called in scalar context will return the number of clients connected.
close()
[C][H] Instructs a client object to close it's connection with a server.
compression()
[C][H] Returns the name of the module used as the compression module for this connection, undef if no compression occurs.
data()
[H] Retrieves the previously-retrieved data associated with a hybrid client object. This method is typically used from inside the callback sub associated with the ``data'' event, since the callback sub is passed nothing more than a client object.
deleteclientip(@array)
[S] Deletes an IP address (or IP addresses) from the list of allowed clients to a server. The IP address (or IP addresses) supplied will no longer be able to connect to the server.

The compliment of this function is addclientip() .

disconnect()
See close()
do_one_loop()
[S] Instructs a server object to ``do one loop'' and return ASAP. This method needs to be called VERY frequently for a server object to function as expected (either through some sort of loop inside your program if you need to do other things beside serve clients, or via the start() method if your entire program is dedicated to serving clients). Each one loop will help the server do it's job, including accepting new clients, receiving data from them, firing off the appropriate callbacks etc.
encryption()
[C][H] Returns the name of the module used as the encryption module for this connection, undef if no encryption occurs.
mode()
[C][H][S] Identifies the mode of the object. Returns either ``client'' or ``server''
receive($timeout)
[C] Receives data sent to the client by a server and returns it. It will block until data is received or until a certain timeout of inactivity (no data transferring) has occurred.

It accepts an optional parameter, a timeout value in seconds. If none is supplied it will default to 300.

remoteip()
[C][H] Returns the IP address of the host on the other end of the connection.
remoteport()
[C][H] Returns the port of the host on the other end of the connection.
running()
[S] Returns true if the server is running (started), false if it is not.
send($data)
[C][H] Sends data to a server. It can be used on client objects you create with the new() constructor, clients objects returned by the clients() method, or with client objects passed to your callback subs by a running server.

It accepts one parameter, and that is the data to send. The data can be a simple scalar or a reference to something more complex.

serial()
[H] Retrieves the serial number of a client object, This is a simple integer that allows your callback subs to easily differentiate between different clients.
setcallback(%hash)
[S] Tells the server which subroutines to call when specific events happen. For example when a client sends the server data, the server calls the ``data'' callback sub.

setcallback() expects to be passed a hash. Each key in the hash is the callback type identifier, and the value is a reference to a sub to call once that callback type event occurs.

Valid keys in that hash are:

connect
Called when a new client connects to the server
data
Called when an existing client sends data to the server
disconnect
Called when an existing client disconnects

Whenever a callback sub is called, it is passed a single parameter, a CLIENT OBJECT. The callback code may then use any of the methods available to client objects to do whatever it wants to do (Read data sent from the client, reply to the client, close the client connection etc...)

socket()
[C][H] Returns the handle of the socket (actually an IO::Socket object) associated with the supplied object. This is useful if you're interested in using IO::Select or select() and want to add a client object's socket handle to the select list.

Note that eventhough there's nothing stopping you from reading and writing directly to the socket handle you retrieve via this method, you should never do this since doing so would definately corrupt the internal protocol and may render your connection useless. Instead you should use the send() and receive() methods.

start(subref)
[S] Starts a server and does NOT return until the server is stopped via the stop() method. This method is a simple while() wrapper around the do_one_loop() method and should be used if your entire program is dedicated to being a server, and does not need to do anything else concurrently.

If you need to concurrently do other things when the server is running, then you can supply to start() the optional reference to a subroutine (very similar to the callback() method). If that is supplied, it will be called every loop. This is very similar to the callback subs, except that the called sub will be passed the server object that the start() method was called on (unlike normal client callbacks which are passed a client object). The other alternative to performing other tasks concurrently is to not use the start() method at all and directly call do_one_loop() repeatedly in your own program.

stop()
[S] Instructs a running server to stop and returns immediately (does not wait for the server to actually stop, which may be a few seconds later). To check if the server is still running or not use the running() method.

COMPRESSION AND ENCRYPTION

Clients and servers written using this class will automatically compress and/or encrypt the transferred data if the appropriate modules are found.

Compression will be automatically enabled if one (or more) of: Compress::Zlib or Compress::LZF are installed on both the client and the server.

As-symmetric encryption will be automatically enabled if Crypt::RSA is installed on both the client and the server.

Symmetric encryption will be automatically enabled if one (or more) of: Crypt::Rijndael* or Crypt::RC6* or Crypt::Blowfish* or Crypt::DES_EDE3* or Crypt::DES* or Crypt::Twofish2* or Crypt::Twofish* or Crypt::TEA* or Crypt::CipherSaber are installed on both the client and the server.

Strong randomization will be automatically enabled if Crypt::Random is installed; otherwise perl's internal rand() is used to generate random keys.

Preference to the compression/encryption method used is determind by availablity checking following the order in which they are presented in the above lists.

Note that during the negotiation upon connection, servers and clients written using Net::EasyTCP version lower than 0.20 communicated the version of the selected encryption/compression modules. If a version mismatch is found, the client reported a connection failure stating the reason (module version mismatch). This behavior was necessary since it was observed that different versions of the same module could produce incompatible output. If this is encountered, it is strongly recommended you upgrade the module in question to the same version on both ends, or more preferrably, Net::EasyTCP on both ends to the latest version, at a minimum 0.20. However, if you wish to forcefully connect overlooking a version mismatch (risking instability/random problems/data corruption) you may supply the ``donotcheckversion'' key to the new() constructor of the client object. This is no longer a requirement of Net::EasyTCP version 0.20 or higher since these newer versions have the ability to use different-version modules as long as their data was compatible, which was automatically determined at negotiation time.

To find out which module(s) have been negotiated for use you can use the compression() and encryption() methods.

* Note that for this class's purposes, Crypt::CBC is a requirement to use any of the encryption modules with a * next to it's name in the above list. So eventhough you may have these modules installed on both the client and the server, they will not be used unless Crypt::CBC is also installed on both ends.

* Note that the nature of symmetric cryptography dictates sharing the secret keys somehow. It is therefore highly recommend to use an As-symmetric cryptography module (such as Crypt::RSA) for serious encryption needs; as a determined hacker might find it trivial to decrypt your data with other symmetric modules.

* Note that if symmetric cryptography is used, then it is highly recommended to also use the ``password'' feature on your servers and clients; since then the ``password'' will, aside from authentication, be also used in the ``secret key'' to encrypt the data. Without a password, the secret key has to be transmitted to the other side during the handshake, significantly lowering the overall security of the data.

If the above modules are installed but you want to forcefully disable compression or encryption, supply the ``donotcompress'' and/or ``donotencrypt'' keys to the new() constructor. If you would like to forcefully disable the use of only some modules, supply the ``donotcompresswith'' and/or ``donotencryptwith'' keys to the new() constructor. This could be used for example to disable the use of Crypt::RSA if you cannot afford the time it takes to generate it's keypairs etc...

RETURN VALUES AND ERRORS

The constructor and all methods return something that evaluates to true when successful, and to false when not successful.

There are a couple of exceptions to the above rule and they are the following methods:

  • clients()
  • data()

The above methods may return something that evaluates to false (such as an empty string, an empty array, or the string ``0'') eventhough there was no error. In that case check if the returned value is defined or not, using the defined() Perl function.

If not successful, the variable $@ will contain a description of the error that occurred.

NOTES

Incompatability with Net::EasyTCP version 0.01
Version 0.02 and later have had their internal protocol modified to a fairly large degree. This has made compatability with version 0.01 impossible. If you're going to use version 0.02 or later (highly recommended), then you will need to make sure that none of the clients/servers are still using version 0.01. It is highly recommended to use the same version of this module on both sides.
Internal Protocol
This class implements a miniature protocol when it sends and receives data between it's clients and servers. This means that a server created using this class cannot properly communicate with a normal client of any protocol (pop3/smtp/etc..) unless that client was also written using this class. It also means that a client written with this class will not properly communicate with a different server (telnet/smtp/pop3 server for example, unless that server is implemented using this class also). This limitation will not change in future releases due to the plethora of advantages the internal protocol gives us.

In other words, if you write a server using this class, write the client using this class also, and vice versa.

Delays
This class does not use the fork() method whatsoever. This means that all it's input/output and multi-socket handling is done via select().

This leads to the following limitation: When a server calls one of your callback subs, it waits for it to return and therefore cannot do anything else. If your callback sub takes 5 minutes to return, then the server will not be able to do anything for 5 minutes, such as acknowledge new clients, or process input from other clients.

In other words, make the code in your callbacks' subs' minimal and strive to make it return as fast as possible.

Deadlocks
As with any client-server scenario, make sure you engineer how they're going to talk to each other, and the order they're going to talk to each other in, quite carefully. If both ends of the connection are waiting for the other end to say something, you've got a deadlock.

COPYRIGHT

Copyright (C) 2001-2003 Mina Naguib. All rights reserved. Use is subject to the Perl license.