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);
31 $rd_handles = IO::Select->new();
32 $wt_handles = IO::Select->new();
33 $er_handles = IO::Select->new();
38 # Checks if blocking is supported
41 require POSIX; POSIX->import(qw(O_NONBLOCK F_SETFL F_GETFL))
43 if ($@ || $main::is_win) {
44 # print STDERR "POSIX Blocking *** NOT *** supported $@\n";
45 $blocking_supported = 0;
47 $blocking_supported = 1;
48 # print STDERR "POSIX Blocking enabled\n";
52 # import as many of these errno values as are available
55 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
58 unless ($^O eq 'MSWin32') {
62 require Socket; Socket->import(qw(IPPROTO_TCP TCP_NODELAY));
65 dbg("IPPROTO_TCP and TCP_NODELAY manually defined");
66 eval 'sub IPPROTO_TCP { 6 };';
67 eval 'sub TCP_NODELAY { 1 };';
70 # http://support.microsoft.com/support/kb/articles/Q150/5/37.asp
71 # defines EINPROGRESS as 10035. We provide it here because some
72 # Win32 users report POSIX::EINPROGRESS is not vendor-supported.
73 if ($^O eq 'MSWin32') {
74 eval '*EINPROGRESS = sub { 10036 };';
75 eval '*EWOULDBLOCK = *EAGAIN = sub { 10035 };';
76 eval '*F_GETFL = sub { 0 };';
77 eval '*F_SETFL = sub { 0 };';
78 eval '*IPPROTO_TCP = sub { 6 };';
79 eval '*TCP_NODELAY = sub { 1 };';
80 $blocking_supported = 0; # it appears that this DOESN'T work :-(
86 my $eagain = eval {EAGAIN()};
87 my $einprogress = eval {EINPROGRESS()};
88 my $ewouldblock = eval {EWOULDBLOCK()};
94 #-----------------------------------------------------------------
95 # Generalised initializer
99 my ($pkg, $rproc) = @_;
101 my $class = $obj || $pkg;
112 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
117 dbg("Connection created ($noconns)") if isdbg('connll');
118 return bless $conn, $class;
124 my $callback = shift;
125 $conn->{eproc} = $callback;
126 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
132 my $callback = shift;
133 $conn->{rproc} = $callback;
138 return unless $blocking_supported;
140 # Make the handle stop blocking, the Windows way.
142 # 126 is FIONBIO (some docs say 0x7F << 16)
144 0x80000000 | (4 << 16) | (ord('f') << 8) | 126,
148 my $flags = fcntl ($_[0], F_GETFL, 0);
150 $flags &= ~O_NONBLOCK;
152 $flags |= O_NONBLOCK;
154 fcntl ($_[0], F_SETFL, $flags);
166 $call = $pkg->{call} unless $call;
167 return undef unless $call;
168 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
169 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
170 $pkg->{call} = $call;
171 $ref = $conns{$call} = $pkg;
172 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
174 $ref = $conns{$call};
179 # this is only called by any dependent processes going away unexpectedly
182 my ($pkg, $pid) = @_;
184 my @pid = grep {$_->{pid} == $pid} values %conns;
185 foreach my $p (@pid) {
186 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
191 #-----------------------------------------------------------------
194 my ($pkg, $to_host, $to_port, $rproc) = @_;
196 # Create a connection end-point object
199 $conn = $pkg->new($rproc);
201 $conn->{peerhost} = $to_host;
202 $conn->{peerport} = $to_port;
203 $conn->{sort} = 'Outgoing';
205 # Create a new internet socket
206 my $sock = IO::Socket::INET->new();
207 return undef unless $sock;
209 my $proto = getprotobyname('tcp');
210 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
213 $conn->{blocking} = 0;
215 # does the host resolve?
216 my $ip = gethostbyname($to_host);
217 return undef unless $ip;
219 # my $r = $sock->connect($to_port, $ip);
220 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
221 return undef unless $r || _err_will_block($!);
223 $conn->{sock} = $sock;
225 if ($conn->{rproc}) {
226 my $callback = sub {$conn->_rcv};
227 set_event_handler ($sock, read => $callback);
234 my ($conn, $line, $sort) = @_;
237 local $^F = 10000; # make sure it ain't closed on exec
238 my ($a, $b) = IO::Socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
247 $conn->{csort} = $sort;
248 $conn->{lineend} = "\cM" if $sort eq 'ax25';
250 if ($conn->{rproc}) {
251 my $callback = sub {$conn->_rcv};
252 Msg::set_event_handler ($a, read => $callback);
254 dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
261 *STDIN = IO::File->new_from_fd($b, 'r') or die;
262 *STDOUT = IO::File->new_from_fd($b, 'w') or die;
263 *STDERR = IO::File->new_from_fd($b, 'w') or die;
265 unless ($main::is_win) {
266 # $SIG{HUP} = 'IGNORE';
267 $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
270 exec "$line" or dbg("exec '$line' failed $!");
273 dbg("cannot fork for $line");
276 dbg("no socket pair $! for $line");
284 return if exists $conn->{disconnecting};
286 $conn->{disconnecting} = 1;
287 my $sock = delete $conn->{sock};
288 $conn->{state} = 'E';
289 $conn->{timeout}->del if $conn->{timeout};
291 # be careful to delete the correct one
293 if ($call = $conn->{call}) {
294 my $ref = $conns{$call};
295 delete $conns{$call} if $ref && $ref == $conn;
297 $call ||= 'unallocated';
298 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
300 # get rid of any references
302 if (ref($conn->{$_})) {
307 if (defined($sock)) {
308 set_event_handler ($sock, read => undef, write => undef, error => undef);
313 unless ($main::is_win) {
314 kill 'TERM', $conn->{pid} if exists $conn->{pid};
319 my ($conn, $msg) = @_;
320 $conn->enqueue($msg);
321 $conn->_send (1); # 1 ==> flush
325 my ($conn, $msg) = @_;
326 $conn->enqueue($msg);
327 my $sock = $conn->{sock};
328 return unless defined($sock);
329 set_event_handler ($sock, write => sub {$conn->_send(0)});
334 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
338 my ($conn, $flush) = @_;
339 my $sock = $conn->{sock};
340 return unless defined($sock);
341 my $rq = $conn->{outqueue};
343 # If $flush is set, set the socket to blocking, and send all
344 # messages in the queue - return only if there's an error
345 # If $flush is 0 (deferred mode) make the socket non-blocking, and
346 # return to the event loop only after every message, or if it
347 # is likely to block in the middle of a message.
349 if ($conn->{blocking} != $flush) {
350 blocking($sock, $flush);
351 $conn->{blocking} = $flush;
353 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
357 my $mlth = length($msg);
358 my $bytes_to_write = $mlth - $offset;
359 my $bytes_written = 0;
360 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
361 while ($bytes_to_write > 0) {
362 $bytes_written = syswrite ($sock, $msg,
363 $bytes_to_write, $offset);
364 if (!defined($bytes_written)) {
365 if (_err_will_block($!)) {
366 # Should happen only in deferred mode. Record how
367 # much we have already sent.
368 $conn->{send_offset} = $offset;
369 # Event handler should already be set, so we will
370 # be called back eventually, and will resume sending
373 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
375 return 0; # fail. Message remains in queue ..
377 } elsif (isdbg('raw')) {
378 my $call = $conn->{call} || 'none';
379 dbgdump('raw', "$call send $bytes_written: ", $msg);
381 $offset += $bytes_written;
382 $bytes_to_write -= $bytes_written;
384 delete $conn->{send_offset};
387 #last unless $flush; # Go back to select and wait
388 # for it to fire again.
390 # Call me back if queue has not been drained.
392 set_event_handler ($sock, write => undef);
393 if (exists $conn->{close_on_empty}) {
394 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
404 my $oldsock = $conn->{sock};
405 my $rc = $rd_callbacks{$oldsock};
406 my $wc = $wt_callbacks{$oldsock};
407 my $ec = $er_callbacks{$oldsock};
408 my $sock = $oldsock->new_from_fd($oldsock, "w+");
410 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
411 $conn->{sock} = $sock;
412 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
417 sub _err_will_block {
418 return 0 unless $blocking_supported;
419 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
425 $conn->{close_on_empty} = 1;
428 #-----------------------------------------------------------------
429 # Receive side routines
432 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
433 my ($pkg, $my_host, $my_port, $login_proc) = @_;
434 my $self = $pkg->new($login_proc);
436 $self->{sock} = IO::Socket::INET->new (
437 LocalAddr => "$my_host:$my_port",
438 # LocalPort => $my_port,
442 die "Could not create socket: $! \n" unless $self->{sock};
443 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
452 unless ($main::is_win) {
454 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
455 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
456 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
457 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
460 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
461 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
462 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
463 $conn->{sock}->autoflush(0);
466 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
467 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
468 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
469 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
478 if ($conn->{msg} =~ /\n/) {
479 my @lines = split /\r?\n/, $conn->{msg};
480 if ($conn->{msg} =~ /\n$/) {
483 $conn->{msg} = pop @lines;
486 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
491 sub _rcv { # Complement to _send
492 my $conn = shift; # $rcv_now complement of $flush
493 # Find out how much has already been received, if at all
494 my ($msg, $offset, $bytes_to_read, $bytes_read);
495 my $sock = $conn->{sock};
496 return unless defined($sock);
499 if ($conn->{blocking}) {
501 $conn->{blocking} = 0;
503 $bytes_read = sysread ($sock, $msg, 1024, 0);
504 if (defined ($bytes_read)) {
505 if ($bytes_read > 0) {
507 my $call = $conn->{call} || 'none';
508 dbgdump('raw', "$call read $bytes_read: ", $msg);
511 my @ch = split //, $msg;
516 $conn->{msg} =~ s/.$//;
523 set_event_handler ($sock, write => sub{$conn->_send(0)});
524 push @{$conn->{outqueue}}, $out;
527 $conn->{msg} .= $msg;
531 if (_err_will_block($!)) {
539 if (defined $bytes_read && $bytes_read == 0) {
540 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
543 unless ($conn->{disable_read}) {
544 $conn->dequeue if exists $conn->{msg};
550 my $server_conn = shift;
551 my $sock = $server_conn->{sock}->accept();
553 my $conn = $server_conn->new($server_conn->{rproc});
554 $conn->{sock} = $sock;
557 $conn->{blocking} = 0;
558 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
559 $conn->{sort} = 'Incoming';
561 $conn->{eproc} = $eproc;
562 set_event_handler ($sock, error => $eproc);
565 $conn->{rproc} = $rproc;
566 my $callback = sub {$conn->_rcv};
567 set_event_handler ($sock, read => $callback);
568 } else { # Login failed
569 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
573 dbg("Msg: error on accept ($!)") if isdbg('err');
580 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
581 $conn->{sock}->close;
584 # close all clients (this is for forking really)
585 sub close_all_clients
587 foreach my $conn (values %conns) {
595 set_event_handler ($conn->{sock}, read => undef);
596 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
600 #----------------------------------------------------
601 # Event loop routines used by both client and server
603 sub set_event_handler {
604 shift unless ref($_[0]); # shift if first arg is package name
605 my ($handle, %args) = @_;
607 if (exists $args{'write'}) {
608 $callback = $args{'write'};
610 $wt_callbacks{$handle} = $callback;
611 $wt_handles->add($handle);
613 delete $wt_callbacks{$handle};
614 $wt_handles->remove($handle);
617 if (exists $args{'read'}) {
618 $callback = $args{'read'};
620 $rd_callbacks{$handle} = $callback;
621 $rd_handles->add($handle);
623 delete $rd_callbacks{$handle};
624 $rd_handles->remove($handle);
627 if (exists $args{'error'}) {
628 $callback = $args{'error'};
630 $er_callbacks{$handle} = $callback;
631 $er_handles->add($handle);
633 delete $er_callbacks{$handle};
634 $er_handles->remove($handle);
640 my ($pkg, $loop_count, $timeout, $wronly) = @_; # event_loop(1) to process events once
641 my ($conn, $r, $w, $e, $rset, $wset, $eset);
644 # Quit the loop if no handles left to process
646 last unless $wt_handles->count();
648 ($rset, $wset, $eset) = IO::Select->select(undef, $wt_handles, undef, $timeout);
650 foreach $w (@$wset) {
651 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
655 last unless ($rd_handles->count() || $wt_handles->count());
657 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
659 foreach $e (@$eset) {
660 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
662 foreach $r (@$rset) {
663 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
665 foreach $w (@$wset) {
666 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
672 if (defined($loop_count)) {
673 last unless --$loop_count;
680 my ($pkg, $interval) = @_;
682 while (time - $now < $interval) {
683 $pkg->event_loop(10, 0.01);
690 my $call = $conn->{call} || 'unallocated';
691 my $host = $conn->{peerhost} || '';
692 my $port = $conn->{peerport} || '';
693 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');