EasyTCP

 view release on metacpan or  search on metacpan

EasyTCP.pm  view on Meta::CPAN

package Net::EasyTCP;

#
# $Header: /cvsroot/Net::EasyTCP/EasyTCP.pm,v 1.144 2004/03/17 14:14:31 mina Exp $
#

use strict;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK $_SERIAL %_COMPRESS_AVAILABLE %_ENCRYPT_AVAILABLE %_MISC_AVAILABLE $PACKETSIZE);

use IO::Socket;
use IO::Select;
use Storable qw(nfreeze thaw);

#
# This block's purpose is to:
# Put the list of available modules in %_COMPRESS_AVAILABLE and %_ENCRYPT_AVAILABLE and %_MISC_AVAILABLE
#
BEGIN {
	my $version;
	my $hasCBC;
	my @_compress_modules = (

		#
		# MAKE SURE WE DO NOT EVER ASSIGN THE SAME KEY TO MORE THAN ONE MODULE, EVEN OLD ONES NO LONGER IN THE LIST
		#
		# HIGHEST EVER USED: 2
		#
		[ '1', 'Compress::Zlib' ],
		[ '2', 'Compress::LZF' ],
	);
	my @_encrypt_modules = (

		#
		# MAKE SURE WE DO NOT EVER ASSIGN THE SAME KEY TO MORE THAN ONE MODULE, EVEN OLD ONES NO LONGER IN THE LIST
		#
		# HIGHEST EVER USED: E
		#
		[ 'B', 'Crypt::RSA',         0, 0 ],
		[ '3', 'Crypt::CBC',         0, 0 ],
		[ 'A', 'Crypt::Rijndael',    1, 1 ],
		[ '9', 'Crypt::RC6',         1, 1 ],
		[ '4', 'Crypt::Blowfish',    1, 1 ],
		[ '6', 'Crypt::DES_EDE3',    1, 1 ],
		[ '5', 'Crypt::DES',         1, 1 ],
		[ 'C', 'Crypt::Twofish2',    1, 1 ],
		[ 'D', 'Crypt::Twofish',     1, 1 ],
		[ 'E', 'Crypt::TEA',         1, 1 ],
		[ '2', 'Crypt::CipherSaber', 0, 1 ],
	);
	my @_misc_modules = (

		#
		# MAKE SURE WE DO NOT EVER ASSIGN THE SAME KEY TO MORE THAN ONE MODULE, EVEN OLD ONES NO LONGER IN THE LIST
		# (this is not as necessary as compress and encrypt since it's not transmitted to peers, but just in case...)
		#
		# HIGHEST EVER USED: 1
		#
		[ '1', 'Crypt::Random' ],
	);

	#
	# Let's reset some variables:
	#
	$hasCBC                      = 0;
	$_COMPRESS_AVAILABLE{_order} = [];
	$_ENCRYPT_AVAILABLE{_order}  = [];
	$_MISC_AVAILABLE{_order}     = [];

	#
	# Now we check the compress array for existing modules
	#
	foreach (@_compress_modules) {
		$@ = undef;
		eval {
			eval("require $_->[1];") || die "$_->[1] not found\n";
			$version = eval("\$$_->[1]::VERSION;") || die "Failed to determine version for $_->[1]\n";
		};
		if (!$@) {
			push(@{ $_COMPRESS_AVAILABLE{_order} }, $_->[0]);
			$_COMPRESS_AVAILABLE{ $_->[0] }{name}    = $_->[1];
			$_COMPRESS_AVAILABLE{ $_->[0] }{version} = $version;
		}
	}

	#
	# Now we check the encrypt array for existing modules
	#
	foreach (@_encrypt_modules) {
		$@ = undef;
		eval {
			eval("require $_->[1];") || die "$_->[1] not found\n";
			$version = eval("\$$_->[1]::VERSION;") || die "Failed to determine version for $_->[1]\n";
		};
		if (!$@) {
			if ($_->[1] eq 'Crypt::CBC') {
				$hasCBC = 1;
			}
			elsif (($hasCBC && $_->[2]) || !$_->[2]) {
				push(@{ $_ENCRYPT_AVAILABLE{_order} }, $_->[0]);
				$_ENCRYPT_AVAILABLE{ $_->[0] }{name}              = $_->[1];
				$_ENCRYPT_AVAILABLE{ $_->[0] }{cbc}               = $_->[2];
				$_ENCRYPT_AVAILABLE{ $_->[0] }{mergewithpassword} = $_->[3];
				$_ENCRYPT_AVAILABLE{ $_->[0] }{version}           = $version;
			}

EasyTCP.pm  view on Meta::CPAN


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.

=item serial()

B<[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.

=item setcallback(%hash)

B<[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:

=over 4

=item connect

Called when a new client connects to the server

=item data

Called when an existing client sends data to the server

=item disconnect

Called when an existing client disconnects

=back

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, clo...


=item socket()

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

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 connecti...

=item start(subref)

B<[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 ...

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 s...

=item stop()

B<[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.

=back

=head1 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: L<Compress::Zlib|Compress::Zlib> or L<Compress::LZF|Compress::LZF> are installed on both the client and the server.

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

Symmetric encryption will be automatically enabled if one (or more) of: L<Crypt::Rijndael|Crypt::Rijndael>* or L<Crypt::RC6|Crypt::RC6>* or L<Crypt::Blowfish|Crypt::Blowfish>* or L<Crypt::DES_EDE3|Crypt::DES_EDE3>* or L<Crypt::DES|Crypt::DES>* or L<C...

Strong randomization will be automatically enabled if L<Crypt::Random|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 c...

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, L<Crypt::CBC|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,...

* 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 fi...

* 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 d...

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, su...

=head1 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:

=over 4

=item *

clients()

=item *

data()

=back

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.

=head1 NOTES

=over 4

=item 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 ...

=item 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 ...

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

=item 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 ...

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

=item 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,...

=back

=head1 AUTHOR

Mina Naguib
http://www.topfx.com
mnaguib@cpan.org

=head1 SEE ALSO

Perl(1), L<IO::Socket>, L<IO::Select>, L<Compress::Zlib>, L<Compress::LZF>, L<Crypt::RSA>, L<Crypt::CBC>, L<Crypt::Rijndael>, L<Crypt::RC6>, L<Crypt::Blowfish>, L<Crypt::DES_EDE3>, L<Crypt::DES>, L<Crypt::Twofish2>, L<Crypt::Twofish>, L<Crypt::TEA>, ...

=head1 COPYRIGHT

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

=cut

#
# The main constructor. This calls either _new_client or _new_server depending on the supplied mode
#
sub new {
	my $class = shift;
	my %para  = @_;

	# Let's lowercase all keys in %para
	foreach (keys %para) {
		if ($_ ne lc($_)) {
			$para{ lc($_) } = $para{$_};
			delete $para{$_};
		}
	}
	if ($para{mode} =~ /^c/i) {
		return _new_client($class, %para);
	}
	elsif ($para{mode} =~ /^s/i) {
		return _new_server($class, %para);
	}
	else {
		$@ = "Supplied mode '$para{mode}' unacceptable. Must be either 'client' or 'server'";
		return undef;
	}
}

#
# Make callback() a synonim to setcallback()
#

sub callback {
	return setcallback(@_);
}

#
# This method adds an ip address(es) to the list of valid IPs a server can accept connections
# from.
#
sub addclientip {
	my $self = shift;
	my @ips  = @_;
	if ($self->{_mode} ne "server") {
		$@ = "$self->{_mode} cannot use method addclientip()";
		return undef;
	}
	foreach (@ips) {
		$self->{_clientip}{$_} = 1;
	}
	return 1;
}

#
# This method does the opposite of addclient(), it removes an ip address(es) from the list

EasyTCP.pm  view on Meta::CPAN

# This takes in an encryption key id and an optional "forcompat" boolean flag
# Generates a keypair (public, private) and returns them according to the type of encryption specified
# Returns undef on error
# The 2 returned keys are guaranteed to be: 1. Scalars and 2. Null-character-free. weather by their nature, or serialization or asci-fi-cation
# If "forcompat" is not specified and there are already a keypair for the specified module stored globally,
# it will return that instead of generating new ones.
# If "forcompat" is supplied, you're guaranteed to receive a new key that wasn't given out in the past to
# non-compat requests. It may be a repeat of a previous "forcompat" pair. However, the strength of that key
# could be possibly reduced.  Such keys are safe to reveal the private portion of publicly, as during the
# compatability negotiation phase, however such keys must NEVER be used to encrypt any real data, as they
# are no longer secret.
#
sub _genkey {
	my $modulekey = shift;
	my $forcompat = shift;
	my $module    = $_ENCRYPT_AVAILABLE{$modulekey}{name};
	my $key1      = undef;
	my $key2      = undef;
	my $temp;
	$@ = undef;
	if (!$forcompat && $_ENCRYPT_AVAILABLE{$modulekey}{localpublickey} && $_ENCRYPT_AVAILABLE{$modulekey}{localprivatekey}) {
		$key1 = $_ENCRYPT_AVAILABLE{$modulekey}{localpublickey};
		$key2 = $_ENCRYPT_AVAILABLE{$modulekey}{localprivatekey};
	}
	elsif ($forcompat && $_ENCRYPT_AVAILABLE{$modulekey}{localcompatpublickey} && $_ENCRYPT_AVAILABLE{$modulekey}{localcompatprivatekey}) {
		$key1 = $_ENCRYPT_AVAILABLE{$modulekey}{localcompatpublickey};
		$key2 = $_ENCRYPT_AVAILABLE{$modulekey}{localcompatprivatekey};
	}
	elsif ($module eq 'Crypt::RSA') {
		eval {
			$temp = Crypt::RSA->new() || die "Failed to create new Crypt::RSA object for key generation: $! $@\n";
			($key1, $key2) = $temp->keygen(
				Size      => 512,
				Verbosity => 0,
			  )
			  or die "Failed to create RSA keypair: " . $temp->errstr() . "\n";
		};
		if ($key1 && $key2) {
			$key1 = _bin2asc(nfreeze($key1));

			# RSA private keys are NOT serializable with the Serialize module - we MUST use Crypt::RSA::Key::Private's undocumented serialize() method:
			$key2 = $key2->serialize();
			if ($forcompat) {
				$_ENCRYPT_AVAILABLE{$modulekey}{localcompatpublickey}  = $key1;
				$_ENCRYPT_AVAILABLE{$modulekey}{localcompatprivatekey} = $key2;
			}
		}
	}
	elsif ($module eq 'Crypt::Rijndael') {
		$key1 = _genrandstring(32);
		$key2 = $key1;
	}
	elsif ($module eq 'Crypt::RC6') {
		$key1 = _genrandstring(32);
		$key2 = $key1;
	}
	elsif ($module eq 'Crypt::Blowfish') {
		$key1 = _genrandstring(56);
		$key2 = $key1;
	}
	elsif ($module eq 'Crypt::DES_EDE3') {
		$key1 = _genrandstring(24);
		$key2 = $key1;
	}
	elsif ($module eq 'Crypt::DES') {
		$key1 = _genrandstring(8);
		$key2 = $key1;
	}
	elsif ($module eq 'Crypt::Twofish2') {
		$key1 = _genrandstring(32);
		$key2 = $key1;
	}
	elsif ($module eq 'Crypt::Twofish') {
		$key1 = _genrandstring(32);
		$key2 = $key1;
	}
	elsif ($module eq 'Crypt::TEA') {
		$key1 = _genrandstring(16);
		$key2 = $key1;
	}
	elsif ($module eq 'Crypt::CipherSaber') {
		$key1 = _genrandstring(32);
		$key2 = $key1;
	}
	else {
		$@ = "Unknown encryption module [$module] modulekey [$modulekey]";
	}

	if (!$key1 || !$key2) {
		$@ = "Could not generate encryption keys. $@";
		return undef;
	}
	else {
		return ($key1, $key2);
	}

}

#
# This takes client object, and a reference to a scalar
# And if it can, compresses scalar, modifying the original, via the specified module in the client object
# Returns true if successful, false if not
#
sub _compress {
	my $client    = shift;
	my $rdata     = shift;
	my $modulekey = $client->{_compress} || return undef;
	my $module    = $_COMPRESS_AVAILABLE{$modulekey}{name};
	my $newdata;

	#
	# Compress the data
	#
	if ($module eq 'Compress::Zlib') {
		$newdata = Compress::Zlib::compress($$rdata);
	}
	elsif ($module eq 'Compress::LZF') {
		$newdata = Compress::LZF::compress($$rdata);
	}
	else {
		$@ = "Unknown compression module [$module] modulekey [$modulekey]";
	}

	#
	# Finally, override reference if compression succeeded



( run in 1.482 second using v1.01-cache-2.11-cpan-39bf76dae61 )