2 # This has been taken from the 'Advanced Perl Programming' book by Sriram Srinivasan
4 # I am presuming that the code is distributed on the same basis as perl itself.
6 # I have modified it to suit my devious purposes (Dirk Koopman G1TLH)
15 use vars qw($VERSION $BRANCH);
16 $VERSION = sprintf( "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/ );
17 $BRANCH = sprintf( "%d.%03d", q$Revision$ =~ /\d+\.\d+\.(\d+)\.(\d+)/ ) || 0;
18 $main::build += $VERSION;
19 $main::branch += $BRANCH;
26 use vars qw(%rd_callbacks %wt_callbacks %er_callbacks $rd_handles $wt_handles $er_handles $now %conns $noconns $blocking_supported $cnum);
31 $rd_handles = IO::Select->new();
32 $wt_handles = IO::Select->new();
33 $er_handles = IO::Select->new();
38 # Checks if blocking is supported
40 require POSIX; POSIX->import(qw(O_NONBLOCK F_SETFL F_GETFL))
42 if ($@ || $main::is_win) {
43 # print STDERR "POSIX Blocking *** NOT *** supported $@\n";
44 $blocking_supported = 0;
46 $blocking_supported = 1;
47 # print STDERR "POSIX Blocking enabled\n";
51 # import as many of these errno values as are available
53 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
55 # http://support.microsoft.com/support/kb/articles/Q150/5/37.asp
56 # defines EINPROGRESS as 10035. We provide it here because some
57 # Win32 users report POSIX::EINPROGRESS is not vendor-supported.
58 if ($^O eq 'MSWin32') {
59 eval '*EINPROGRESS = sub { 10036 };';
60 eval '*EWOULDBLOCK = *EAGAIN = sub { 10035 };';
61 $blocking_supported = 1;
67 my $eagain = eval {EAGAIN()};
68 my $einprogress = eval {EINPROGRESS()};
69 my $ewouldblock = eval {EWOULDBLOCK()};
75 #-----------------------------------------------------------------
76 # Generalised initializer
80 my ($pkg, $rproc) = @_;
82 my $class = $obj || $pkg;
93 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
98 dbg("Connection created ($noconns)") if isdbg('connll');
99 return bless $conn, $class;
105 my $callback = shift;
106 $conn->{eproc} = $callback;
107 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
113 my $callback = shift;
114 $conn->{rproc} = $callback;
119 return unless $blocking_supported;
121 # Make the handle stop blocking, the Windows way.
122 if ($^O eq 'MSWin32') {
125 # 126 is FIONBIO (some docs say 0x7F << 16)
127 0x80000000 | (4 << 16) | (ord('f') << 8) | 126,
129 ) or confess "Can't set the handle non-blocking: $!";
132 my $flags = fcntl ($_[0], F_GETFL, 0);
134 $flags &= ~O_NONBLOCK;
136 $flags |= O_NONBLOCK;
138 fcntl ($_[0], F_SETFL, $flags);
149 $call = $pkg->{call} unless $call;
150 return undef unless $call;
151 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
152 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
153 $pkg->{call} = $call;
154 $ref = $conns{$call} = $pkg;
155 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
157 $ref = $conns{$call};
162 # this is only called by any dependent processes going away unexpectedly
165 my ($pkg, $pid) = @_;
167 my @pid = grep {$_->{pid} == $pid} values %conns;
168 foreach my $p (@pid) {
169 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
174 #-----------------------------------------------------------------
177 my ($pkg, $to_host, $to_port, $rproc) = @_;
179 # Create a connection end-point object
182 $conn = $pkg->new($rproc);
184 $conn->{peerhost} = $to_host;
185 $conn->{peerport} = $to_port;
186 $conn->{sort} = 'Outgoing';
188 # Create a new internet socket
189 my $sock = IO::Socket::INET->new();
190 return undef unless $sock;
192 my $proto = getprotobyname('tcp');
193 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
196 $conn->{blocking} = 0;
198 my $ip = gethostbyname($to_host);
199 # my $r = $sock->connect($to_port, $ip);
200 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
201 return undef unless $r || _err_will_block($!);
203 $conn->{sock} = $sock;
205 if ($conn->{rproc}) {
206 my $callback = sub {$conn->_rcv};
207 set_event_handler ($sock, read => $callback);
214 return if exists $conn->{disconnecting};
216 $conn->{disconnecting} = 1;
217 my $sock = delete $conn->{sock};
218 $conn->{state} = 'E';
219 $conn->{timeout}->del if $conn->{timeout};
221 # be careful to delete the correct one
223 if ($call = $conn->{call}) {
224 my $ref = $conns{$call};
225 delete $conns{$call} if $ref && $ref == $conn;
227 $call ||= 'unallocated';
228 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
230 # get rid of any references
232 if (ref($conn->{$_})) {
237 if (defined($sock)) {
238 set_event_handler ($sock, read => undef, write => undef, error => undef);
243 unless ($main::is_win) {
244 kill 'TERM', $conn->{pid} if exists $conn->{pid};
250 my ($conn, $msg) = @_;
251 $conn->enqueue($msg);
252 $conn->_send (1); # 1 ==> flush
256 my ($conn, $msg) = @_;
257 $conn->enqueue($msg);
258 my $sock = $conn->{sock};
259 return unless defined($sock);
260 set_event_handler ($sock, write => sub {$conn->_send(0)});
265 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
269 my ($conn, $flush) = @_;
270 my $sock = $conn->{sock};
271 return unless defined($sock);
272 my $rq = $conn->{outqueue};
274 # If $flush is set, set the socket to blocking, and send all
275 # messages in the queue - return only if there's an error
276 # If $flush is 0 (deferred mode) make the socket non-blocking, and
277 # return to the event loop only after every message, or if it
278 # is likely to block in the middle of a message.
280 if ($conn->{blocking} != $flush) {
281 blocking($sock, $flush);
282 $conn->{blocking} = $flush;
284 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
288 my $mlth = length($msg);
289 my $bytes_to_write = $mlth - $offset;
290 my $bytes_written = 0;
291 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
292 while ($bytes_to_write > 0) {
293 $bytes_written = syswrite ($sock, $msg,
294 $bytes_to_write, $offset);
295 if (!defined($bytes_written)) {
296 if (_err_will_block($!)) {
297 # Should happen only in deferred mode. Record how
298 # much we have already sent.
299 $conn->{send_offset} = $offset;
300 # Event handler should already be set, so we will
301 # be called back eventually, and will resume sending
304 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
306 return 0; # fail. Message remains in queue ..
308 } elsif (isdbg('raw')) {
309 my $call = $conn->{call} || 'none';
310 dbgdump('raw', "$call send $bytes_written: ", $msg);
312 $offset += $bytes_written;
313 $bytes_to_write -= $bytes_written;
315 delete $conn->{send_offset};
318 #last unless $flush; # Go back to select and wait
319 # for it to fire again.
321 # Call me back if queue has not been drained.
323 set_event_handler ($sock, write => undef);
324 if (exists $conn->{close_on_empty}) {
325 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
335 my $oldsock = $conn->{sock};
336 my $rc = $rd_callbacks{$oldsock};
337 my $wc = $wt_callbacks{$oldsock};
338 my $ec = $er_callbacks{$oldsock};
339 my $sock = $oldsock->new_from_fd($oldsock, "w+");
341 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
342 $conn->{sock} = $sock;
343 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
348 sub _err_will_block {
349 return 0 unless $blocking_supported;
350 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
356 $conn->{close_on_empty} = 1;
359 #-----------------------------------------------------------------
360 # Receive side routines
363 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
364 my ($pkg, $my_host, $my_port, $login_proc) = @_;
365 my $self = $pkg->new($login_proc);
367 $self->{sock} = IO::Socket::INET->new (
368 LocalAddr => "$my_host:$my_port",
369 # LocalPort => $my_port,
373 die "Could not create socket: $! \n" unless $self->{sock};
374 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
378 eval "use Socket qw(IPPROTO_TCP TCP_NODELAY)";
381 sub TCP_NODELAY {1;};
389 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
390 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
391 my $n = unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
392 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
395 setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0)) or confess "setsockopt linger: $!";
396 setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1) or confess "setsockopt keepalive: $!";
397 setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1) or confess "setsockopt: $!" unless $main::iswin;
398 $conn->{sock}->autoflush(0);
401 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
402 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
403 my $n = unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
404 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
412 if ($conn->{msg} =~ /\n/) {
413 my @lines = split /\r?\n/, $conn->{msg};
414 if ($conn->{msg} =~ /\n$/) {
417 $conn->{msg} = pop @lines;
420 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
425 sub _rcv { # Complement to _send
426 my $conn = shift; # $rcv_now complement of $flush
427 # Find out how much has already been received, if at all
428 my ($msg, $offset, $bytes_to_read, $bytes_read);
429 my $sock = $conn->{sock};
430 return unless defined($sock);
433 if ($conn->{blocking}) {
435 $conn->{blocking} = 0;
437 $bytes_read = sysread ($sock, $msg, 1024, 0);
438 if (defined ($bytes_read)) {
439 if ($bytes_read > 0) {
441 my $call = $conn->{call} || 'none';
442 dbgdump('raw', "$call read $bytes_read: ", $msg);
445 my @ch = split //, $msg;
450 $conn->{msg} =~ s/.$//;
457 set_event_handler ($sock, write => sub{$conn->_send(0)});
458 push @{$conn->{outqueue}}, $out;
461 $conn->{msg} .= $msg;
465 if (_err_will_block($!)) {
473 if (defined $bytes_read && $bytes_read == 0) {
474 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
477 unless ($conn->{disable_read}) {
478 $conn->dequeue if exists $conn->{msg};
484 my $server_conn = shift;
485 my $sock = $server_conn->{sock}->accept();
487 my $conn = $server_conn->new($server_conn->{rproc});
488 $conn->{sock} = $sock;
491 $conn->{blocking} = 0;
492 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
493 $conn->{sort} = 'Incoming';
495 $conn->{eproc} = $eproc;
496 set_event_handler ($sock, error => $eproc);
499 $conn->{rproc} = $rproc;
500 my $callback = sub {$conn->_rcv};
501 set_event_handler ($sock, read => $callback);
502 } else { # Login failed
503 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
507 dbg("Msg: error on accept ($!)") if isdbg('err');
514 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
515 $conn->{sock}->close;
518 # close all clients (this is for forking really)
519 sub close_all_clients
521 foreach my $conn (values %conns) {
529 set_event_handler ($conn->{sock}, read => undef);
530 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
534 #----------------------------------------------------
535 # Event loop routines used by both client and server
537 sub set_event_handler {
538 shift unless ref($_[0]); # shift if first arg is package name
539 my ($handle, %args) = @_;
541 if (exists $args{'write'}) {
542 $callback = $args{'write'};
544 $wt_callbacks{$handle} = $callback;
545 $wt_handles->add($handle);
547 delete $wt_callbacks{$handle};
548 $wt_handles->remove($handle);
551 if (exists $args{'read'}) {
552 $callback = $args{'read'};
554 $rd_callbacks{$handle} = $callback;
555 $rd_handles->add($handle);
557 delete $rd_callbacks{$handle};
558 $rd_handles->remove($handle);
561 if (exists $args{'error'}) {
562 $callback = $args{'error'};
564 $er_callbacks{$handle} = $callback;
565 $er_handles->add($handle);
567 delete $er_callbacks{$handle};
568 $er_handles->remove($handle);
574 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
575 my ($conn, $r, $w, $e, $rset, $wset, $eset);
578 # Quit the loop if no handles left to process
579 last unless ($rd_handles->count() || $wt_handles->count());
581 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
583 foreach $e (@$eset) {
584 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
586 foreach $r (@$rset) {
587 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
589 foreach $w (@$wset) {
590 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
595 if (defined($loop_count)) {
596 last unless --$loop_count;
603 my ($pkg, $interval) = @_;
605 while (time - $now < $interval) {
606 $pkg->event_loop(10, 0.01);
613 my $call = $conn->{call} || 'unallocated';
614 my $host = $conn->{peerhost} || '';
615 my $port = $conn->{peerport} || '';
616 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');