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 $blocking_supported = IO::Socket->can('blocking') ? 2 : 0;
47 $blocking_supported = IO::Socket->can('blocking') ? 2 : 1;
51 # import as many of these errno values as are available
54 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
57 unless ($^O eq 'MSWin32') {
61 require Socket; Socket->import(qw(IPPROTO_TCP TCP_NODELAY));
64 dbg("IPPROTO_TCP and TCP_NODELAY manually defined");
65 eval 'sub IPPROTO_TCP { 6 };';
66 eval 'sub TCP_NODELAY { 1 };';
69 # http://support.microsoft.com/support/kb/articles/Q150/5/37.asp
70 # defines EINPROGRESS as 10035. We provide it here because some
71 # Win32 users report POSIX::EINPROGRESS is not vendor-supported.
72 if ($^O eq 'MSWin32') {
73 eval '*EINPROGRESS = sub { 10036 };';
74 eval '*EWOULDBLOCK = *EAGAIN = sub { 10035 };';
75 eval '*F_GETFL = sub { 0 };';
76 eval '*F_SETFL = sub { 0 };';
77 eval '*IPPROTO_TCP = sub { 6 };';
78 eval '*TCP_NODELAY = sub { 1 };';
79 $blocking_supported = 0; # it appears that this DOESN'T work :-(
85 my $eagain = eval {EAGAIN()};
86 my $einprogress = eval {EINPROGRESS()};
87 my $ewouldblock = eval {EWOULDBLOCK()};
93 #-----------------------------------------------------------------
94 # Generalised initializer
98 my ($pkg, $rproc) = @_;
100 my $class = $obj || $pkg;
111 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
116 dbg("Connection created ($noconns)") if isdbg('connll');
117 return bless $conn, $class;
123 my $callback = shift;
124 $conn->{eproc} = $callback;
125 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
131 my $callback = shift;
132 $conn->{rproc} = $callback;
137 return unless $blocking_supported;
139 # Make the handle stop blocking, the Windows way.
140 if ($blocking_supported) {
141 $_[0]->blocking($_[1]);
143 my $flags = fcntl ($_[0], F_GETFL, 0);
145 $flags &= ~O_NONBLOCK;
147 $flags |= O_NONBLOCK;
149 fcntl ($_[0], F_SETFL, $flags);
161 $call = $pkg->{call} unless $call;
162 return undef unless $call;
163 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
164 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
165 $pkg->{call} = $call;
166 $ref = $conns{$call} = $pkg;
167 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
169 $ref = $conns{$call};
174 # this is only called by any dependent processes going away unexpectedly
177 my ($pkg, $pid) = @_;
179 my @pid = grep {$_->{pid} == $pid} values %conns;
180 foreach my $p (@pid) {
181 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
186 #-----------------------------------------------------------------
189 my ($pkg, $to_host, $to_port, $rproc) = @_;
191 # Create a connection end-point object
194 $conn = $pkg->new($rproc);
196 $conn->{peerhost} = $to_host;
197 $conn->{peerport} = $to_port;
198 $conn->{sort} = 'Outgoing';
200 # Create a new internet socket
201 my $sock = IO::Socket::INET->new();
202 return undef unless $sock;
204 my $proto = getprotobyname('tcp');
205 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
208 $conn->{blocking} = 0;
210 # does the host resolve?
211 my $ip = gethostbyname($to_host);
212 return undef unless $ip;
214 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
215 return undef unless $r || _err_will_block($!);
217 $conn->{sock} = $sock;
219 if ($conn->{rproc}) {
220 my $callback = sub {$conn->_rcv};
221 set_event_handler ($sock, read => $callback);
228 my ($conn, $line, $sort) = @_;
231 local $^F = 10000; # make sure it ain't closed on exec
232 my ($a, $b) = IO::Socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
241 $conn->{csort} = $sort;
242 $conn->{lineend} = "\cM" if $sort eq 'ax25';
244 if ($conn->{rproc}) {
245 my $callback = sub {$conn->_rcv};
246 Msg::set_event_handler ($a, read => $callback);
248 dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
255 *STDIN = IO::File->new_from_fd($b, 'r') or die;
256 *STDOUT = IO::File->new_from_fd($b, 'w') or die;
257 *STDERR = IO::File->new_from_fd($b, 'w') or die;
259 unless ($main::is_win) {
260 # $SIG{HUP} = 'IGNORE';
261 $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
264 exec "$line" or dbg("exec '$line' failed $!");
267 dbg("cannot fork for $line");
270 dbg("no socket pair $! for $line");
278 return if exists $conn->{disconnecting};
280 $conn->{disconnecting} = 1;
281 my $sock = delete $conn->{sock};
282 $conn->{state} = 'E';
283 $conn->{timeout}->del if $conn->{timeout};
285 # be careful to delete the correct one
287 if ($call = $conn->{call}) {
288 my $ref = $conns{$call};
289 delete $conns{$call} if $ref && $ref == $conn;
291 $call ||= 'unallocated';
292 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
294 # get rid of any references
296 if (ref($conn->{$_})) {
301 if (defined($sock)) {
302 set_event_handler ($sock, read => undef, write => undef, error => undef);
307 unless ($main::is_win) {
308 kill 'TERM', $conn->{pid} if exists $conn->{pid};
313 my ($conn, $msg) = @_;
314 $conn->enqueue($msg);
315 $conn->_send (1); # 1 ==> flush
319 my ($conn, $msg) = @_;
320 $conn->enqueue($msg);
321 my $sock = $conn->{sock};
322 return unless defined($sock);
323 set_event_handler ($sock, write => sub {$conn->_send(0)});
328 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
332 my ($conn, $flush) = @_;
333 my $sock = $conn->{sock};
334 return unless defined($sock);
335 my $rq = $conn->{outqueue};
337 # If $flush is set, set the socket to blocking, and send all
338 # messages in the queue - return only if there's an error
339 # If $flush is 0 (deferred mode) make the socket non-blocking, and
340 # return to the event loop only after every message, or if it
341 # is likely to block in the middle of a message.
343 # if ($conn->{blocking} != $flush) {
344 # blocking($sock, $flush);
345 # $conn->{blocking} = $flush;
347 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
351 my $mlth = length($msg);
352 my $bytes_to_write = $mlth - $offset;
353 my $bytes_written = 0;
354 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
355 while ($bytes_to_write > 0) {
356 $bytes_written = syswrite ($sock, $msg,
357 $bytes_to_write, $offset);
358 if (!defined($bytes_written)) {
359 if (_err_will_block($!)) {
360 # Should happen only in deferred mode. Record how
361 # much we have already sent.
362 $conn->{send_offset} = $offset;
363 # Event handler should already be set, so we will
364 # be called back eventually, and will resume sending
367 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
369 return 0; # fail. Message remains in queue ..
371 } elsif (isdbg('raw')) {
372 my $call = $conn->{call} || 'none';
373 dbgdump('raw', "$call send $bytes_written: ", $msg);
375 $total_out += $bytes_written;
376 $offset += $bytes_written;
377 $bytes_to_write -= $bytes_written;
379 delete $conn->{send_offset};
382 #last unless $flush; # Go back to select and wait
383 # for it to fire again.
385 # Call me back if queue has not been drained.
387 set_event_handler ($sock, write => undef);
388 if (exists $conn->{close_on_empty}) {
389 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
399 my $oldsock = $conn->{sock};
400 my $rc = $rd_callbacks{$oldsock};
401 my $wc = $wt_callbacks{$oldsock};
402 my $ec = $er_callbacks{$oldsock};
403 my $sock = $oldsock->new_from_fd($oldsock, "w+");
405 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
406 $conn->{sock} = $sock;
407 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
412 sub _err_will_block {
413 return 0 unless $blocking_supported;
414 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
420 $conn->{close_on_empty} = 1;
423 #-----------------------------------------------------------------
424 # Receive side routines
427 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
428 my ($pkg, $my_host, $my_port, $login_proc) = @_;
429 my $self = $pkg->new($login_proc);
431 $self->{sock} = IO::Socket::INET->new (
432 LocalAddr => "$my_host:$my_port",
433 # LocalPort => $my_port,
437 die "Could not create socket: $! \n" unless $self->{sock};
438 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
447 unless ($main::is_win) {
449 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
450 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
451 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
452 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
455 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
456 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
457 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
458 $conn->{sock}->autoflush(0);
461 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
462 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
463 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
464 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
473 if ($conn->{msg} =~ /\n/) {
474 my @lines = split /\r?\n/, $conn->{msg};
475 if ($conn->{msg} =~ /\n$/) {
478 $conn->{msg} = pop @lines;
481 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
486 sub _rcv { # Complement to _send
487 my $conn = shift; # $rcv_now complement of $flush
488 # Find out how much has already been received, if at all
489 my ($msg, $offset, $bytes_to_read, $bytes_read);
490 my $sock = $conn->{sock};
491 return unless defined($sock);
494 if ($conn->{blocking}) {
496 $conn->{blocking} = 0;
498 $bytes_read = sysread ($sock, $msg, 1024, 0);
499 if (defined ($bytes_read)) {
500 if ($bytes_read > 0) {
501 $total_in += $bytes_read;
503 my $call = $conn->{call} || 'none';
504 dbgdump('raw', "$call read $bytes_read: ", $msg);
507 my @ch = split //, $msg;
512 $conn->{msg} =~ s/.$//;
519 set_event_handler ($sock, write => sub{$conn->_send(0)});
520 push @{$conn->{outqueue}}, $out;
523 $conn->{msg} .= $msg;
527 if (_err_will_block($!)) {
535 if (defined $bytes_read && $bytes_read == 0) {
536 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
539 unless ($conn->{disable_read}) {
540 $conn->dequeue if exists $conn->{msg};
546 my $server_conn = shift;
547 my $sock = $server_conn->{sock}->accept();
549 my $conn = $server_conn->new($server_conn->{rproc});
550 $conn->{sock} = $sock;
553 $conn->{blocking} = 0;
554 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
555 $conn->{sort} = 'Incoming';
557 $conn->{eproc} = $eproc;
558 set_event_handler ($sock, error => $eproc);
561 $conn->{rproc} = $rproc;
562 my $callback = sub {$conn->_rcv};
563 set_event_handler ($sock, read => $callback);
564 } else { # Login failed
565 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
569 dbg("Msg: error on accept ($!)") if isdbg('err');
576 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
577 $conn->{sock}->close;
580 # close all clients (this is for forking really)
581 sub close_all_clients
583 foreach my $conn (values %conns) {
591 set_event_handler ($conn->{sock}, read => undef);
592 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
596 #----------------------------------------------------
597 # Event loop routines used by both client and server
599 sub set_event_handler {
600 shift unless ref($_[0]); # shift if first arg is package name
601 my ($handle, %args) = @_;
603 if (exists $args{'write'}) {
604 $callback = $args{'write'};
606 $wt_callbacks{$handle} = $callback;
607 $wt_handles->add($handle);
609 delete $wt_callbacks{$handle};
610 $wt_handles->remove($handle);
613 if (exists $args{'read'}) {
614 $callback = $args{'read'};
616 $rd_callbacks{$handle} = $callback;
617 $rd_handles->add($handle);
619 delete $rd_callbacks{$handle};
620 $rd_handles->remove($handle);
623 if (exists $args{'error'}) {
624 $callback = $args{'error'};
626 $er_callbacks{$handle} = $callback;
627 $er_handles->add($handle);
629 delete $er_callbacks{$handle};
630 $er_handles->remove($handle);
636 my ($pkg, $loop_count, $timeout, $wronly) = @_; # event_loop(1) to process events once
637 my ($conn, $r, $w, $e, $rset, $wset, $eset);
640 # Quit the loop if no handles left to process
642 last unless $wt_handles->count();
644 ($rset, $wset, $eset) = IO::Select->select(undef, $wt_handles, undef, $timeout);
646 foreach $w (@$wset) {
647 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
651 last unless ($rd_handles->count() || $wt_handles->count());
653 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
655 foreach $e (@$eset) {
656 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
658 foreach $r (@$rset) {
659 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
661 foreach $w (@$wset) {
662 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
668 if (defined($loop_count)) {
669 last unless --$loop_count;
676 my ($pkg, $interval) = @_;
678 while (time - $now < $interval) {
679 $pkg->event_loop(10, 0.01);
686 my $call = $conn->{call} || 'unallocated';
687 my $host = $conn->{peerhost} || '';
688 my $port = $conn->{peerport} || '';
689 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');