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)
17 use vars qw($VERSION $BRANCH);
18 ($VERSION, $BRANCH) = dxver(q$Revision$);
25 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);
30 $rd_handles = IO::Select->new();
31 $wt_handles = IO::Select->new();
32 $er_handles = IO::Select->new();
33 $total_in = $total_out = 0;
38 # Checks if blocking is supported
41 require POSIX; POSIX->import(qw(O_NONBLOCK F_SETFL F_GETFL))
43 if ($@ || $main::is_win) {
44 $blocking_supported = IO::Socket->can('blocking') ? 2 : 0;
46 $blocking_supported = IO::Socket->can('blocking') ? 2 : 1;
50 # import as many of these errno values as are available
53 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
56 unless ($^O eq 'MSWin32') {
60 require Socket; Socket->import(qw(IPPROTO_TCP TCP_NODELAY));
63 dbg("IPPROTO_TCP and TCP_NODELAY manually defined");
64 eval 'sub IPPROTO_TCP { 6 };';
65 eval 'sub TCP_NODELAY { 1 };';
68 # http://support.microsoft.com/support/kb/articles/Q150/5/37.asp
69 # defines EINPROGRESS as 10035. We provide it here because some
70 # Win32 users report POSIX::EINPROGRESS is not vendor-supported.
71 if ($^O eq 'MSWin32') {
72 eval '*EINPROGRESS = sub { 10036 };';
73 eval '*EWOULDBLOCK = *EAGAIN = sub { 10035 };';
74 eval '*F_GETFL = sub { 0 };';
75 eval '*F_SETFL = sub { 0 };';
76 eval '*IPPROTO_TCP = sub { 6 };';
77 eval '*TCP_NODELAY = sub { 1 };';
78 $blocking_supported = 0; # it appears that this DOESN'T work :-(
84 my $eagain = eval {EAGAIN()};
85 my $einprogress = eval {EINPROGRESS()};
86 my $ewouldblock = eval {EWOULDBLOCK()};
92 #-----------------------------------------------------------------
93 # Generalised initializer
97 my ($pkg, $rproc) = @_;
99 my $class = $obj || $pkg;
110 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
115 dbg("Connection created ($noconns)") if isdbg('connll');
116 return bless $conn, $class;
122 my $callback = shift;
123 $conn->{eproc} = $callback;
124 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
130 my $callback = shift;
131 $conn->{rproc} = $callback;
136 return unless $blocking_supported;
138 # Make the handle stop blocking, the Windows way.
139 if ($blocking_supported) {
140 $_[0]->blocking($_[1]);
142 my $flags = fcntl ($_[0], F_GETFL, 0);
144 $flags &= ~O_NONBLOCK;
146 $flags |= O_NONBLOCK;
148 fcntl ($_[0], F_SETFL, $flags);
160 $call = $pkg->{call} unless $call;
161 return undef unless $call;
162 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
163 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
164 $pkg->{call} = $call;
165 $ref = $conns{$call} = $pkg;
166 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
168 $ref = $conns{$call};
173 # this is only called by any dependent processes going away unexpectedly
176 my ($pkg, $pid) = @_;
178 my @pid = grep {$_->{pid} == $pid} values %conns;
179 foreach my $p (@pid) {
180 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
185 #-----------------------------------------------------------------
188 my ($pkg, $to_host, $to_port, $rproc) = @_;
190 # Create a connection end-point object
193 $conn = $pkg->new($rproc);
195 $conn->{peerhost} = $to_host;
196 $conn->{peerport} = $to_port;
197 $conn->{sort} = 'Outgoing';
199 # Create a new internet socket
200 my $sock = IO::Socket::INET->new();
201 return undef unless $sock;
203 my $proto = getprotobyname('tcp');
204 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
207 $conn->{blocking} = 0;
209 # does the host resolve?
210 my $ip = gethostbyname($to_host);
211 return undef unless $ip;
213 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
214 return undef unless $r || _err_will_block($!);
216 $conn->{sock} = $sock;
218 if ($conn->{rproc}) {
219 my $callback = sub {$conn->_rcv};
220 set_event_handler ($sock, read => $callback);
227 my ($conn, $line, $sort) = @_;
230 local $^F = 10000; # make sure it ain't closed on exec
231 my ($a, $b) = IO::Socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
240 $conn->{csort} = $sort;
241 $conn->{lineend} = "\cM" if $sort eq 'ax25';
243 if ($conn->{rproc}) {
244 my $callback = sub {$conn->_rcv};
245 Msg::set_event_handler ($a, read => $callback);
247 dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
254 *STDIN = IO::File->new_from_fd($b, 'r') or die;
255 *STDOUT = IO::File->new_from_fd($b, 'w') or die;
256 *STDERR = IO::File->new_from_fd($b, 'w') or die;
258 unless ($main::is_win) {
259 # $SIG{HUP} = 'IGNORE';
260 $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
263 exec "$line" or dbg("exec '$line' failed $!");
266 dbg("cannot fork for $line");
269 dbg("no socket pair $! for $line");
277 return if exists $conn->{disconnecting};
279 $conn->{disconnecting} = 1;
280 my $sock = delete $conn->{sock};
281 $conn->{state} = 'E';
282 $conn->{timeout}->del if $conn->{timeout};
284 # be careful to delete the correct one
286 if ($call = $conn->{call}) {
287 my $ref = $conns{$call};
288 delete $conns{$call} if $ref && $ref == $conn;
290 $call ||= 'unallocated';
291 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
293 # get rid of any references
295 if (ref($conn->{$_})) {
300 if (defined($sock)) {
301 set_event_handler ($sock, read => undef, write => undef, error => undef);
306 unless ($main::is_win) {
307 kill 'TERM', $conn->{pid} if exists $conn->{pid};
312 my ($conn, $msg) = @_;
313 $conn->enqueue($msg);
314 $conn->_send (1); # 1 ==> flush
318 my ($conn, $msg) = @_;
319 $conn->enqueue($msg);
320 my $sock = $conn->{sock};
321 return unless defined($sock);
322 set_event_handler ($sock, write => sub {$conn->_send(0)});
327 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
331 my ($conn, $flush) = @_;
332 my $sock = $conn->{sock};
333 return unless defined($sock);
334 my $rq = $conn->{outqueue};
336 # If $flush is set, set the socket to blocking, and send all
337 # messages in the queue - return only if there's an error
338 # If $flush is 0 (deferred mode) make the socket non-blocking, and
339 # return to the event loop only after every message, or if it
340 # is likely to block in the middle of a message.
342 # if ($conn->{blocking} != $flush) {
343 # blocking($sock, $flush);
344 # $conn->{blocking} = $flush;
346 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
350 my $mlth = length($msg);
351 my $bytes_to_write = $mlth - $offset;
352 my $bytes_written = 0;
353 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
354 while ($bytes_to_write > 0) {
355 $bytes_written = syswrite ($sock, $msg,
356 $bytes_to_write, $offset);
357 if (!defined($bytes_written)) {
358 if (_err_will_block($!)) {
359 # Should happen only in deferred mode. Record how
360 # much we have already sent.
361 $conn->{send_offset} = $offset;
362 # Event handler should already be set, so we will
363 # be called back eventually, and will resume sending
366 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
368 return 0; # fail. Message remains in queue ..
370 } elsif (isdbg('raw')) {
371 my $call = $conn->{call} || 'none';
372 dbgdump('raw', "$call send $bytes_written: ", $msg);
374 $total_out += $bytes_written;
375 $offset += $bytes_written;
376 $bytes_to_write -= $bytes_written;
378 delete $conn->{send_offset};
381 #last unless $flush; # Go back to select and wait
382 # for it to fire again.
384 # Call me back if queue has not been drained.
386 set_event_handler ($sock, write => undef);
387 if (exists $conn->{close_on_empty}) {
388 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
398 my $oldsock = $conn->{sock};
399 my $rc = $rd_callbacks{$oldsock};
400 my $wc = $wt_callbacks{$oldsock};
401 my $ec = $er_callbacks{$oldsock};
402 my $sock = $oldsock->new_from_fd($oldsock, "w+");
404 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
405 $conn->{sock} = $sock;
406 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
411 sub _err_will_block {
412 return 0 unless $blocking_supported;
413 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
419 $conn->{close_on_empty} = 1;
422 #-----------------------------------------------------------------
423 # Receive side routines
426 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
427 my ($pkg, $my_host, $my_port, $login_proc) = @_;
428 my $self = $pkg->new($login_proc);
430 $self->{sock} = IO::Socket::INET->new (
431 LocalAddr => "$my_host:$my_port",
432 # LocalPort => $my_port,
436 die "Could not create socket: $! \n" unless $self->{sock};
437 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
446 unless ($main::is_win) {
448 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
449 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
450 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
451 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
454 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
455 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
456 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
457 $conn->{sock}->autoflush(0);
460 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
461 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
462 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
463 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
472 if ($conn->{msg} =~ /\n/) {
473 my @lines = split /\r?\n/, $conn->{msg};
474 if ($conn->{msg} =~ /\n$/) {
477 $conn->{msg} = pop @lines;
480 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
485 sub _rcv { # Complement to _send
486 my $conn = shift; # $rcv_now complement of $flush
487 # Find out how much has already been received, if at all
488 my ($msg, $offset, $bytes_to_read, $bytes_read);
489 my $sock = $conn->{sock};
490 return unless defined($sock);
493 if ($conn->{blocking}) {
495 $conn->{blocking} = 0;
497 $bytes_read = sysread ($sock, $msg, 1024, 0);
498 if (defined ($bytes_read)) {
499 if ($bytes_read > 0) {
500 $total_in += $bytes_read;
502 my $call = $conn->{call} || 'none';
503 dbgdump('raw', "$call read $bytes_read: ", $msg);
506 my @ch = split //, $msg;
511 $conn->{msg} =~ s/.$//;
518 set_event_handler ($sock, write => sub{$conn->_send(0)});
519 push @{$conn->{outqueue}}, $out;
522 $conn->{msg} .= $msg;
526 if (_err_will_block($!)) {
534 if (defined $bytes_read && $bytes_read == 0) {
535 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
538 unless ($conn->{disable_read}) {
539 $conn->dequeue if exists $conn->{msg};
545 my $server_conn = shift;
546 my $sock = $server_conn->{sock}->accept();
548 my $conn = $server_conn->new($server_conn->{rproc});
549 $conn->{sock} = $sock;
552 $conn->{blocking} = 0;
553 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
554 $conn->{sort} = 'Incoming';
556 $conn->{eproc} = $eproc;
557 set_event_handler ($sock, error => $eproc);
560 $conn->{rproc} = $rproc;
561 my $callback = sub {$conn->_rcv};
562 set_event_handler ($sock, read => $callback);
563 } else { # Login failed
564 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
568 dbg("Msg: error on accept ($!)") if isdbg('err');
575 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
576 $conn->{sock}->close;
579 # close all clients (this is for forking really)
580 sub close_all_clients
582 foreach my $conn (values %conns) {
590 set_event_handler ($conn->{sock}, read => undef);
591 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
595 #----------------------------------------------------
596 # Event loop routines used by both client and server
598 sub set_event_handler {
599 shift unless ref($_[0]); # shift if first arg is package name
600 my ($handle, %args) = @_;
602 if (exists $args{'write'}) {
603 $callback = $args{'write'};
605 $wt_callbacks{$handle} = $callback;
606 $wt_handles->add($handle);
608 delete $wt_callbacks{$handle};
609 $wt_handles->remove($handle);
612 if (exists $args{'read'}) {
613 $callback = $args{'read'};
615 $rd_callbacks{$handle} = $callback;
616 $rd_handles->add($handle);
618 delete $rd_callbacks{$handle};
619 $rd_handles->remove($handle);
622 if (exists $args{'error'}) {
623 $callback = $args{'error'};
625 $er_callbacks{$handle} = $callback;
626 $er_handles->add($handle);
628 delete $er_callbacks{$handle};
629 $er_handles->remove($handle);
635 my ($pkg, $loop_count, $timeout, $wronly) = @_; # event_loop(1) to process events once
636 my ($conn, $r, $w, $e, $rset, $wset, $eset);
639 # Quit the loop if no handles left to process
641 last unless $wt_handles->count();
643 ($rset, $wset, $eset) = IO::Select->select(undef, $wt_handles, undef, $timeout);
645 foreach $w (@$wset) {
646 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
650 last unless ($rd_handles->count() || $wt_handles->count());
652 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
654 foreach $e (@$eset) {
655 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
657 foreach $r (@$rset) {
658 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
660 foreach $w (@$wset) {
661 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
667 if (defined($loop_count)) {
668 last unless --$loop_count;
675 my ($pkg, $interval) = @_;
677 while (time - $now < $interval) {
678 $pkg->event_loop(10, 0.01);
685 my $call = $conn->{call} || 'unallocated';
686 my $host = $conn->{peerhost} || '';
687 my $port = $conn->{peerport} || '';
688 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');