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,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 $total_in $total_out);
31 $rd_handles = IO::Select->new();
32 $wt_handles = IO::Select->new();
33 $er_handles = IO::Select->new();
34 $total_in = $total_out = 0;
39 # Checks if blocking is supported
42 require POSIX; POSIX->import(qw(O_NONBLOCK F_SETFL F_GETFL))
44 if ($@ || $main::is_win) {
45 # print STDERR "POSIX Blocking *** NOT *** supported $@\n";
46 $blocking_supported = 0;
48 $blocking_supported = 1;
49 # print STDERR "POSIX Blocking enabled\n";
53 # import as many of these errno values as are available
56 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
59 unless ($^O eq 'MSWin32') {
63 require Socket; Socket->import(qw(IPPROTO_TCP TCP_NODELAY));
66 dbg("IPPROTO_TCP and TCP_NODELAY manually defined");
67 eval 'sub IPPROTO_TCP { 6 };';
68 eval 'sub TCP_NODELAY { 1 };';
71 # http://support.microsoft.com/support/kb/articles/Q150/5/37.asp
72 # defines EINPROGRESS as 10035. We provide it here because some
73 # Win32 users report POSIX::EINPROGRESS is not vendor-supported.
74 if ($^O eq 'MSWin32') {
75 eval '*EINPROGRESS = sub { 10036 };';
76 eval '*EWOULDBLOCK = *EAGAIN = sub { 10035 };';
77 eval '*F_GETFL = sub { 0 };';
78 eval '*F_SETFL = sub { 0 };';
79 eval '*IPPROTO_TCP = sub { 6 };';
80 eval '*TCP_NODELAY = sub { 1 };';
81 $blocking_supported = 0; # it appears that this DOESN'T work :-(
87 my $eagain = eval {EAGAIN()};
88 my $einprogress = eval {EINPROGRESS()};
89 my $ewouldblock = eval {EWOULDBLOCK()};
95 #-----------------------------------------------------------------
96 # Generalised initializer
100 my ($pkg, $rproc) = @_;
102 my $class = $obj || $pkg;
113 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
118 dbg("Connection created ($noconns)") if isdbg('connll');
119 return bless $conn, $class;
125 my $callback = shift;
126 $conn->{eproc} = $callback;
127 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
133 my $callback = shift;
134 $conn->{rproc} = $callback;
139 return unless $blocking_supported;
141 # Make the handle stop blocking, the Windows way.
143 # 126 is FIONBIO (some docs say 0x7F << 16)
145 0x80000000 | (4 << 16) | (ord('f') << 8) | 126,
149 my $flags = fcntl ($_[0], F_GETFL, 0);
151 $flags &= ~O_NONBLOCK;
153 $flags |= O_NONBLOCK;
155 fcntl ($_[0], F_SETFL, $flags);
167 $call = $pkg->{call} unless $call;
168 return undef unless $call;
169 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
170 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
171 $pkg->{call} = $call;
172 $ref = $conns{$call} = $pkg;
173 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
175 $ref = $conns{$call};
180 # this is only called by any dependent processes going away unexpectedly
183 my ($pkg, $pid) = @_;
185 my @pid = grep {$_->{pid} == $pid} values %conns;
186 foreach my $p (@pid) {
187 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
192 #-----------------------------------------------------------------
195 my ($pkg, $to_host, $to_port, $rproc) = @_;
197 # Create a connection end-point object
200 $conn = $pkg->new($rproc);
202 $conn->{peerhost} = $to_host;
203 $conn->{peerport} = $to_port;
204 $conn->{sort} = 'Outgoing';
206 # Create a new internet socket
207 my $sock = IO::Socket::INET->new();
208 return undef unless $sock;
210 my $proto = getprotobyname('tcp');
211 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
214 $conn->{blocking} = 0;
216 # does the host resolve?
217 my $ip = gethostbyname($to_host);
218 return undef unless $ip;
220 # my $r = $sock->connect($to_port, $ip);
221 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
222 return undef unless $r || _err_will_block($!);
224 $conn->{sock} = $sock;
226 if ($conn->{rproc}) {
227 my $callback = sub {$conn->_rcv};
228 set_event_handler ($sock, read => $callback);
235 my ($conn, $line, $sort) = @_;
238 local $^F = 10000; # make sure it ain't closed on exec
239 my ($a, $b) = IO::Socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
248 $conn->{csort} = $sort;
249 $conn->{lineend} = "\cM" if $sort eq 'ax25';
251 if ($conn->{rproc}) {
252 my $callback = sub {$conn->_rcv};
253 Msg::set_event_handler ($a, read => $callback);
255 dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
262 *STDIN = IO::File->new_from_fd($b, 'r') or die;
263 *STDOUT = IO::File->new_from_fd($b, 'w') or die;
264 *STDERR = IO::File->new_from_fd($b, 'w') or die;
266 unless ($main::is_win) {
267 # $SIG{HUP} = 'IGNORE';
268 $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
271 exec "$line" or dbg("exec '$line' failed $!");
274 dbg("cannot fork for $line");
277 dbg("no socket pair $! for $line");
285 return if exists $conn->{disconnecting};
287 $conn->{disconnecting} = 1;
288 my $sock = delete $conn->{sock};
289 $conn->{state} = 'E';
290 $conn->{timeout}->del if $conn->{timeout};
292 # be careful to delete the correct one
294 if ($call = $conn->{call}) {
295 my $ref = $conns{$call};
296 delete $conns{$call} if $ref && $ref == $conn;
298 $call ||= 'unallocated';
299 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
301 # get rid of any references
303 if (ref($conn->{$_})) {
308 if (defined($sock)) {
309 set_event_handler ($sock, read => undef, write => undef, error => undef);
314 unless ($main::is_win) {
315 kill 'TERM', $conn->{pid} if exists $conn->{pid};
320 my ($conn, $msg) = @_;
321 $conn->enqueue($msg);
322 $conn->_send (1); # 1 ==> flush
326 my ($conn, $msg) = @_;
327 $conn->enqueue($msg);
328 my $sock = $conn->{sock};
329 return unless defined($sock);
330 set_event_handler ($sock, write => sub {$conn->_send(0)});
335 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
339 my ($conn, $flush) = @_;
340 my $sock = $conn->{sock};
341 return unless defined($sock);
342 my $rq = $conn->{outqueue};
344 # If $flush is set, set the socket to blocking, and send all
345 # messages in the queue - return only if there's an error
346 # If $flush is 0 (deferred mode) make the socket non-blocking, and
347 # return to the event loop only after every message, or if it
348 # is likely to block in the middle of a message.
350 if ($conn->{blocking} != $flush) {
351 blocking($sock, $flush);
352 $conn->{blocking} = $flush;
354 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
358 my $mlth = length($msg);
359 my $bytes_to_write = $mlth - $offset;
360 my $bytes_written = 0;
361 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
362 while ($bytes_to_write > 0) {
363 $bytes_written = syswrite ($sock, $msg,
364 $bytes_to_write, $offset);
365 if (!defined($bytes_written)) {
366 if (_err_will_block($!)) {
367 # Should happen only in deferred mode. Record how
368 # much we have already sent.
369 $conn->{send_offset} = $offset;
370 # Event handler should already be set, so we will
371 # be called back eventually, and will resume sending
374 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
376 return 0; # fail. Message remains in queue ..
378 } elsif (isdbg('raw')) {
379 my $call = $conn->{call} || 'none';
380 dbgdump('raw', "$call send $bytes_written: ", $msg);
382 $total_out += $bytes_written;
383 $offset += $bytes_written;
384 $bytes_to_write -= $bytes_written;
386 delete $conn->{send_offset};
389 #last unless $flush; # Go back to select and wait
390 # for it to fire again.
392 # Call me back if queue has not been drained.
394 set_event_handler ($sock, write => undef);
395 if (exists $conn->{close_on_empty}) {
396 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
406 my $oldsock = $conn->{sock};
407 my $rc = $rd_callbacks{$oldsock};
408 my $wc = $wt_callbacks{$oldsock};
409 my $ec = $er_callbacks{$oldsock};
410 my $sock = $oldsock->new_from_fd($oldsock, "w+");
412 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
413 $conn->{sock} = $sock;
414 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
419 sub _err_will_block {
420 return 0 unless $blocking_supported;
421 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
427 $conn->{close_on_empty} = 1;
430 #-----------------------------------------------------------------
431 # Receive side routines
434 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
435 my ($pkg, $my_host, $my_port, $login_proc) = @_;
436 my $self = $pkg->new($login_proc);
438 $self->{sock} = IO::Socket::INET->new (
439 LocalAddr => "$my_host:$my_port",
440 # LocalPort => $my_port,
444 die "Could not create socket: $! \n" unless $self->{sock};
445 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
454 unless ($main::is_win) {
456 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
457 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
458 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
459 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
462 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
463 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
464 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
465 $conn->{sock}->autoflush(0);
468 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
469 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
470 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
471 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
480 if ($conn->{msg} =~ /\n/) {
481 my @lines = split /\r?\n/, $conn->{msg};
482 if ($conn->{msg} =~ /\n$/) {
485 $conn->{msg} = pop @lines;
488 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
493 sub _rcv { # Complement to _send
494 my $conn = shift; # $rcv_now complement of $flush
495 # Find out how much has already been received, if at all
496 my ($msg, $offset, $bytes_to_read, $bytes_read);
497 my $sock = $conn->{sock};
498 return unless defined($sock);
501 if ($conn->{blocking}) {
503 $conn->{blocking} = 0;
505 $bytes_read = sysread ($sock, $msg, 1024, 0);
506 if (defined ($bytes_read)) {
507 if ($bytes_read > 0) {
508 $total_in += $bytes_read;
510 my $call = $conn->{call} || 'none';
511 dbgdump('raw', "$call read $bytes_read: ", $msg);
514 my @ch = split //, $msg;
519 $conn->{msg} =~ s/.$//;
526 set_event_handler ($sock, write => sub{$conn->_send(0)});
527 push @{$conn->{outqueue}}, $out;
530 $conn->{msg} .= $msg;
534 if (_err_will_block($!)) {
542 if (defined $bytes_read && $bytes_read == 0) {
543 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
546 unless ($conn->{disable_read}) {
547 $conn->dequeue if exists $conn->{msg};
553 my $server_conn = shift;
554 my $sock = $server_conn->{sock}->accept();
556 my $conn = $server_conn->new($server_conn->{rproc});
557 $conn->{sock} = $sock;
560 $conn->{blocking} = 0;
561 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
562 $conn->{sort} = 'Incoming';
564 $conn->{eproc} = $eproc;
565 set_event_handler ($sock, error => $eproc);
568 $conn->{rproc} = $rproc;
569 my $callback = sub {$conn->_rcv};
570 set_event_handler ($sock, read => $callback);
571 } else { # Login failed
572 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
576 dbg("Msg: error on accept ($!)") if isdbg('err');
583 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
584 $conn->{sock}->close;
587 # close all clients (this is for forking really)
588 sub close_all_clients
590 foreach my $conn (values %conns) {
598 set_event_handler ($conn->{sock}, read => undef);
599 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
603 #----------------------------------------------------
604 # Event loop routines used by both client and server
606 sub set_event_handler {
607 shift unless ref($_[0]); # shift if first arg is package name
608 my ($handle, %args) = @_;
610 if (exists $args{'write'}) {
611 $callback = $args{'write'};
613 $wt_callbacks{$handle} = $callback;
614 $wt_handles->add($handle);
616 delete $wt_callbacks{$handle};
617 $wt_handles->remove($handle);
620 if (exists $args{'read'}) {
621 $callback = $args{'read'};
623 $rd_callbacks{$handle} = $callback;
624 $rd_handles->add($handle);
626 delete $rd_callbacks{$handle};
627 $rd_handles->remove($handle);
630 if (exists $args{'error'}) {
631 $callback = $args{'error'};
633 $er_callbacks{$handle} = $callback;
634 $er_handles->add($handle);
636 delete $er_callbacks{$handle};
637 $er_handles->remove($handle);
643 my ($pkg, $loop_count, $timeout, $wronly) = @_; # event_loop(1) to process events once
644 my ($conn, $r, $w, $e, $rset, $wset, $eset);
647 # Quit the loop if no handles left to process
649 last unless $wt_handles->count();
651 ($rset, $wset, $eset) = IO::Select->select(undef, $wt_handles, undef, $timeout);
653 foreach $w (@$wset) {
654 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
658 last unless ($rd_handles->count() || $wt_handles->count());
660 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
662 foreach $e (@$eset) {
663 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
665 foreach $r (@$rset) {
666 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
668 foreach $w (@$wset) {
669 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
675 if (defined($loop_count)) {
676 last unless --$loop_count;
683 my ($pkg, $interval) = @_;
685 while (time - $now < $interval) {
686 $pkg->event_loop(10, 0.01);
693 my $call = $conn->{call} || 'unallocated';
694 my $host = $conn->{peerhost} || '';
695 my $port = $conn->{peerport} || '';
696 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');