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)
21 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 $io_socket);
26 $rd_handles = IO::Select->new();
27 $wt_handles = IO::Select->new();
28 $er_handles = IO::Select->new();
29 $total_in = $total_out = 0;
34 # Checks if blocking is supported
37 require POSIX; POSIX->import(qw(O_NONBLOCK F_SETFL F_GETFL))
42 require IO::Socket::INET6;
48 $io_socket = 'IO::Socket::INET';
50 $io_socket = 'IO::Socket::INET6';
54 if ($@ || $main::is_win) {
55 $blocking_supported = $io_socket->can('blocking') ? 2 : 0;
57 $blocking_supported = $io_socket->can('blocking') ? 2 : 1;
61 # import as many of these errno values as are available
64 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
67 unless ($^O eq 'MSWin32') {
71 require Socket; Socket->import(qw(IPPROTO_TCP TCP_NODELAY));
74 dbg("IPPROTO_TCP and TCP_NODELAY manually defined");
75 eval 'sub IPPROTO_TCP { 6 };';
76 eval 'sub TCP_NODELAY { 1 };';
79 # http://support.microsoft.com/support/kb/articles/Q150/5/37.asp
80 # defines EINPROGRESS as 10035. We provide it here because some
81 # Win32 users report POSIX::EINPROGRESS is not vendor-supported.
82 if ($^O eq 'MSWin32') {
83 eval '*EINPROGRESS = sub { 10036 };' unless defined *EINPROGRESS;
84 eval '*EWOULDBLOCK = *EAGAIN = sub { 10035 };' unless defined *EWOULDBLOCK;
85 eval '*F_GETFL = sub { 0 };' unless defined *F_GETFL;
86 eval '*F_SETFL = sub { 0 };' unless defined *F_SETFL;
87 eval 'sub IPPROTO_TCP { 6 };';
88 eval 'sub TCP_NODELAY { 1 };';
89 $blocking_supported = 0; # it appears that this DOESN'T work :-(
95 my $eagain = eval {EAGAIN()};
96 my $einprogress = eval {EINPROGRESS()};
97 my $ewouldblock = eval {EWOULDBLOCK()};
103 #-----------------------------------------------------------------
104 # Generalised initializer
108 my ($pkg, $rproc) = @_;
110 my $class = $obj || $pkg;
121 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
126 dbg("$class Connection $conn->{cnum} created (total $noconns)") if isdbg('connll');
127 return bless $conn, $class;
133 my $callback = shift;
134 $conn->{eproc} = $callback;
135 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
141 my $callback = shift;
142 $conn->{rproc} = $callback;
147 return unless $blocking_supported;
149 # Make the handle stop blocking, the Windows way.
150 if ($blocking_supported) {
151 $_[0]->blocking($_[1]);
153 my $flags = fcntl ($_[0], F_GETFL, 0);
155 $flags &= ~O_NONBLOCK;
157 $flags |= O_NONBLOCK;
159 fcntl ($_[0], F_SETFL, $flags);
171 $call = $pkg->{call} unless $call;
172 return undef unless $call;
173 dbg((ref $pkg) . " changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
174 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
175 $pkg->{call} = $call;
176 $ref = $conns{$call} = $pkg;
177 dbg((ref $pkg) . " Connection $pkg->{cnum} $call stored") if isdbg('connll');
179 $ref = $conns{$call};
184 # this is only called by any dependent processes going away unexpectedly
187 my ($pkg, $pid) = @_;
189 my @pid = grep {$_->{pid} == $pid} values %conns;
190 foreach my $p (@pid) {
191 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
199 return $conn->{csort} eq 'ax25';
205 $conn->{peerhost} ||= 'ax25' if $conn->ax25;
206 $conn->{peerhost} ||= $conn->{sock}->peerhost if $conn->{sock} && $conn->{sock}->isa('IO::Socket::INET');
207 $conn->{peerhost} ||= 'UNKNOWN';
208 $conn->{peerhost} =~ s/^::ffff://;
209 return $conn->{peerhost};
212 #-----------------------------------------------------------------
215 my ($pkg, $to_host, $to_port, $rproc) = @_;
217 # Create a connection end-point object
220 $conn = $pkg->new($rproc);
222 $conn->{peerhost} = $to_host;
223 $conn->{peerport} = $to_port;
224 $conn->{sort} = 'Outgoing';
226 dbg((ref $conn) . " connecting $conn->{cnum} to $to_host:$to_port") if isdbg('connll');
229 if ($blocking_supported) {
230 $sock = $io_socket->new(PeerAddr => $to_host, PeerPort => $to_port, Proto => 'tcp', Blocking =>0) or return undef;
232 # Create a new internet socket
233 $sock = $io_socket->new();
234 return undef unless $sock;
236 my $proto = getprotobyname('tcp');
237 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
240 $conn->{blocking} = 0;
242 # does the host resolve?
243 my $ip = gethostbyname($to_host);
244 return undef unless $ip;
246 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
247 return undef unless $r || _err_will_block($!);
250 $conn->{sock} = $sock;
251 # $conn->{peerhost} = $sock->peerhost; # for consistency
253 dbg((ref $conn) . " connected $conn->{cnum} to $to_host:$to_port") if isdbg('connll');
255 if ($conn->{rproc}) {
256 my $callback = sub {$conn->_rcv};
257 set_event_handler ($sock, read => $callback);
264 my ($conn, $line, $sort) = @_;
267 local $^F = 10000; # make sure it ain't closed on exec
268 my ($a, $b) = $io_socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
277 $conn->{csort} = $sort;
278 $conn->{lineend} = "\cM" if $sort eq 'ax25';
280 if ($conn->{rproc}) {
281 my $callback = sub {$conn->_rcv};
282 Msg::set_event_handler ($a, read => $callback);
284 dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
291 *STDIN = IO::File->new_from_fd($b, 'r') or die;
292 *STDOUT = IO::File->new_from_fd($b, 'w') or die;
293 *STDERR = IO::File->new_from_fd($b, 'w') or die;
295 unless ($main::is_win) {
296 # $SIG{HUP} = 'IGNORE';
297 $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
300 exec "$line" or dbg("exec '$line' failed $!");
303 dbg("cannot fork for $line");
306 dbg("no socket pair $! for $line");
314 return if exists $conn->{disconnecting};
316 $conn->{disconnecting} = 1;
317 my $sock = delete $conn->{sock};
318 $conn->{state} = 'E';
319 $conn->{timeout}->del if $conn->{timeout};
321 # be careful to delete the correct one
323 if ($call = $conn->{call}) {
324 my $ref = $conns{$call};
325 delete $conns{$call} if $ref && $ref == $conn;
327 $call ||= 'unallocated';
328 dbg((ref $conn) . " Connection $conn->{cnum} $call disconnected") if isdbg('connll');
330 # get rid of any references
332 if (ref($conn->{$_})) {
337 if (defined($sock)) {
338 set_event_handler ($sock, read => undef, write => undef, error => undef);
343 unless ($main::is_win) {
344 kill 'TERM', $conn->{pid} if exists $conn->{pid};
349 my ($conn, $msg) = @_;
350 $conn->enqueue($msg);
351 $conn->_send (1); # 1 ==> flush
355 my ($conn, $msg) = @_;
356 $conn->enqueue($msg);
357 my $sock = $conn->{sock};
358 return unless defined($sock);
359 set_event_handler ($sock, write => sub {$conn->_send(0)});
364 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
368 my ($conn, $flush) = @_;
369 my $sock = $conn->{sock};
370 return unless defined($sock);
371 my $rq = $conn->{outqueue};
373 # If $flush is set, set the socket to blocking, and send all
374 # messages in the queue - return only if there's an error
375 # If $flush is 0 (deferred mode) make the socket non-blocking, and
376 # return to the event loop only after every message, or if it
377 # is likely to block in the middle of a message.
379 # if ($conn->{blocking} != $flush) {
380 # blocking($sock, $flush);
381 # $conn->{blocking} = $flush;
383 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
387 my $mlth = length($msg);
388 my $bytes_to_write = $mlth - $offset;
389 my $bytes_written = 0;
390 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
391 while ($bytes_to_write > 0) {
392 $bytes_written = syswrite ($sock, $msg,
393 $bytes_to_write, $offset);
394 if (!defined($bytes_written)) {
395 if (_err_will_block($!)) {
396 # Should happen only in deferred mode. Record how
397 # much we have already sent.
398 $conn->{send_offset} = $offset;
399 # Event handler should already be set, so we will
400 # be called back eventually, and will resume sending
403 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
405 return 0; # fail. Message remains in queue ..
407 } elsif (isdbg('raw')) {
408 my $call = $conn->{call} || 'none';
409 dbgdump('raw', "$call send $bytes_written: ", $msg);
411 $total_out += $bytes_written;
412 $offset += $bytes_written;
413 $bytes_to_write -= $bytes_written;
415 delete $conn->{send_offset};
418 #last unless $flush; # Go back to select and wait
419 # for it to fire again.
421 # Call me back if queue has not been drained.
423 set_event_handler ($sock, write => undef);
424 if (exists $conn->{close_on_empty}) {
425 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
435 my $oldsock = $conn->{sock};
436 my $rc = $rd_callbacks{$oldsock};
437 my $wc = $wt_callbacks{$oldsock};
438 my $ec = $er_callbacks{$oldsock};
439 my $sock = $oldsock->new_from_fd($oldsock, "w+");
441 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
442 $conn->{sock} = $sock;
443 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
448 sub _err_will_block {
449 return 0 unless $blocking_supported;
450 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
456 $conn->{close_on_empty} = 1;
459 #-----------------------------------------------------------------
460 # Receive side routines
463 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
464 my ($pkg, $my_host, $my_port, $login_proc) = @_;
465 my $self = $pkg->new($login_proc);
467 $self->{sock} = $io_socket->new (
468 LocalAddr => $my_host,
469 LocalPort => $my_port,
473 die "Could not create socket: $! \n" unless $self->{sock};
474 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
483 unless ($main::is_win) {
485 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
486 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
487 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
488 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
491 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
492 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
493 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
494 $conn->{sock}->autoflush(0);
497 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
498 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
499 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
500 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
508 return if $conn->{disconnecting};
510 if ($conn->{msg} =~ /\cJ/) {
511 my @lines = split /\cM?\cJ/, $conn->{msg};
512 if ($conn->{msg} =~ /\cM?\cJ$/) {
515 $conn->{msg} = pop @lines;
518 last if $conn->{disconnecting};
519 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
524 sub _rcv { # Complement to _send
525 my $conn = shift; # $rcv_now complement of $flush
526 # Find out how much has already been received, if at all
527 my ($msg, $offset, $bytes_to_read, $bytes_read);
528 my $sock = $conn->{sock};
529 return unless defined($sock);
532 # if ($conn->{blocking}) {
533 # blocking($sock, 0);
534 # $conn->{blocking} = 0;
536 $bytes_read = sysread ($sock, $msg, 1024, 0);
537 if (defined ($bytes_read)) {
538 if ($bytes_read > 0) {
539 $total_in += $bytes_read;
541 my $call = $conn->{call} || 'none';
542 dbgdump('raw', "$call read $bytes_read: ", $msg);
545 my @ch = split //, $msg;
550 $conn->{msg} =~ s/.$//;
557 set_event_handler ($sock, write => sub{$conn->_send(0)});
558 push @{$conn->{outqueue}}, $out;
561 $conn->{msg} .= $msg;
565 if (_err_will_block($!)) {
573 if (defined $bytes_read && $bytes_read == 0) {
574 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
577 unless ($conn->{disable_read}) {
578 $conn->dequeue if exists $conn->{msg};
584 my $server_conn = shift;
585 my $sock = $server_conn->{sock}->accept();
587 my $conn = $server_conn->new($server_conn->{rproc});
588 $conn->{sock} = $sock;
591 $conn->{blocking} = 0;
592 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
593 $conn->{sort} = 'Incoming';
595 $conn->{eproc} = $eproc;
596 set_event_handler ($sock, error => $eproc);
599 $conn->{rproc} = $rproc;
600 my $callback = sub {$conn->_rcv};
601 set_event_handler ($sock, read => $callback);
602 } else { # Login failed
603 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
607 dbg("Msg: error on accept ($!)") if isdbg('err');
614 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
615 $conn->{sock}->close;
618 # close all clients (this is for forking really)
619 sub close_all_clients
621 foreach my $conn (values %conns) {
629 set_event_handler ($conn->{sock}, read => undef);
630 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
634 #----------------------------------------------------
635 # Event loop routines used by both client and server
637 sub set_event_handler {
638 shift unless ref($_[0]); # shift if first arg is package name
639 my ($handle, %args) = @_;
641 if (exists $args{'write'}) {
642 $callback = $args{'write'};
644 $wt_callbacks{$handle} = $callback;
645 $wt_handles->add($handle);
647 delete $wt_callbacks{$handle};
648 $wt_handles->remove($handle);
651 if (exists $args{'read'}) {
652 $callback = $args{'read'};
654 $rd_callbacks{$handle} = $callback;
655 $rd_handles->add($handle);
657 delete $rd_callbacks{$handle};
658 $rd_handles->remove($handle);
661 if (exists $args{'error'}) {
662 $callback = $args{'error'};
664 $er_callbacks{$handle} = $callback;
665 $er_handles->add($handle);
667 delete $er_callbacks{$handle};
668 $er_handles->remove($handle);
674 my ($pkg, $loop_count, $timeout, $wronly) = @_; # event_loop(1) to process events once
675 my ($conn, $r, $w, $e, $rset, $wset, $eset);
678 # Quit the loop if no handles left to process
680 last unless $wt_handles->count();
682 ($rset, $wset, $eset) = IO::Select->select(undef, $wt_handles, undef, $timeout);
684 foreach $w (@$wset) {
685 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
689 last unless ($rd_handles->count() || $wt_handles->count());
691 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
693 foreach $e (@$eset) {
694 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
696 foreach $r (@$rset) {
697 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
699 foreach $w (@$wset) {
700 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
706 if (defined($loop_count)) {
707 last unless --$loop_count;
714 my ($pkg, $interval) = @_;
716 while (time - $now < $interval) {
717 $pkg->event_loop(10, 0.01);
724 my $call = $conn->{call} || 'unallocated';
725 my $host = $conn->{peerhost} || '';
726 my $port = $conn->{peerport} || '';
728 dbg((ref $conn) . " Connection $conn->{cnum} $call [$host $port] being destroyed (total $noconns)") if isdbg('connll');