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)
20 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);
25 $rd_handles = IO::Select->new();
26 $wt_handles = IO::Select->new();
27 $er_handles = IO::Select->new();
28 $total_in = $total_out = 0;
33 # Checks if blocking is supported
36 require POSIX; POSIX->import(qw(O_NONBLOCK F_SETFL F_GETFL))
41 require IO::Socket::INET6;
47 $io_socket = 'IO::Socket::INET';
49 $io_socket = 'IO::Socket::INET6';
53 if ($@ || $main::is_win) {
54 $blocking_supported = $io_socket->can('blocking') ? 2 : 0;
56 $blocking_supported = $io_socket->can('blocking') ? 2 : 1;
60 # import as many of these errno values as are available
63 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
66 unless ($^O eq 'MSWin32') {
70 require Socket; Socket->import(qw(IPPROTO_TCP TCP_NODELAY));
73 dbg("IPPROTO_TCP and TCP_NODELAY manually defined");
74 eval 'sub IPPROTO_TCP { 6 };';
75 eval 'sub TCP_NODELAY { 1 };';
78 # http://support.microsoft.com/support/kb/articles/Q150/5/37.asp
79 # defines EINPROGRESS as 10035. We provide it here because some
80 # Win32 users report POSIX::EINPROGRESS is not vendor-supported.
81 if ($^O eq 'MSWin32') {
82 eval '*EINPROGRESS = sub { 10036 };' unless defined *EINPROGRESS;
83 eval '*EWOULDBLOCK = *EAGAIN = sub { 10035 };' unless defined *EWOULDBLOCK;
84 eval '*F_GETFL = sub { 0 };' unless defined *F_GETFL;
85 eval '*F_SETFL = sub { 0 };' unless defined *F_SETFL;
86 eval 'sub IPPROTO_TCP { 6 };';
87 eval 'sub TCP_NODELAY { 1 };';
88 $blocking_supported = 0; # it appears that this DOESN'T work :-(
94 my $eagain = eval {EAGAIN()};
95 my $einprogress = eval {EINPROGRESS()};
96 my $ewouldblock = eval {EWOULDBLOCK()};
102 #-----------------------------------------------------------------
103 # Generalised initializer
107 my ($pkg, $rproc) = @_;
109 my $class = $obj || $pkg;
120 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
125 dbg("Connection created ($noconns)") if isdbg('connll');
126 return bless $conn, $class;
132 my $callback = shift;
133 $conn->{eproc} = $callback;
134 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
140 my $callback = shift;
141 $conn->{rproc} = $callback;
146 return unless $blocking_supported;
148 # Make the handle stop blocking, the Windows way.
149 if ($blocking_supported) {
150 $_[0]->blocking($_[1]);
152 my $flags = fcntl ($_[0], F_GETFL, 0);
154 $flags &= ~O_NONBLOCK;
156 $flags |= O_NONBLOCK;
158 fcntl ($_[0], F_SETFL, $flags);
170 $call = $pkg->{call} unless $call;
171 return undef unless $call;
172 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
173 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
174 $pkg->{call} = $call;
175 $ref = $conns{$call} = $pkg;
176 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
178 $ref = $conns{$call};
183 # this is only called by any dependent processes going away unexpectedly
186 my ($pkg, $pid) = @_;
188 my @pid = grep {$_->{pid} == $pid} values %conns;
189 foreach my $p (@pid) {
190 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
198 return $conn->{csort} eq 'ax25';
204 $conn->{peerhost} ||= 'ax25' if $conn->ax25;
205 $conn->{peerhost} ||= $conn->{sock}->peerhost if $conn->{sock} && $conn->{sock}->isa('IO::Socket::INET');
206 $conn->{peerhost} ||= 'UNKNOWN';
207 return $conn->{peerhost};
210 #-----------------------------------------------------------------
213 my ($pkg, $to_host, $to_port, $rproc) = @_;
215 # Create a connection end-point object
218 $conn = $pkg->new($rproc);
220 $conn->{peerhost} = $to_host;
221 $conn->{peerport} = $to_port;
222 $conn->{sort} = 'Outgoing';
225 if ($blocking_supported) {
226 $sock = $io_socket->new(PeerAddr => $to_host, PeerPort => $to_port, Proto => 'tcp', Blocking =>0) or return undef;
228 # Create a new internet socket
229 $sock = $io_socket->new();
230 return undef unless $sock;
232 my $proto = getprotobyname('tcp');
233 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
236 $conn->{blocking} = 0;
238 # does the host resolve?
239 my $ip = gethostbyname($to_host);
240 return undef unless $ip;
242 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
243 return undef unless $r || _err_will_block($!);
246 $conn->{sock} = $sock;
247 $conn->{peerhost} = $sock->peerhost; # for consistency
249 if ($conn->{rproc}) {
250 my $callback = sub {$conn->_rcv};
251 set_event_handler ($sock, read => $callback);
258 my ($conn, $line, $sort) = @_;
261 local $^F = 10000; # make sure it ain't closed on exec
262 my ($a, $b) = $io_socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
271 $conn->{csort} = $sort;
272 $conn->{lineend} = "\cM" if $sort eq 'ax25';
274 if ($conn->{rproc}) {
275 my $callback = sub {$conn->_rcv};
276 Msg::set_event_handler ($a, read => $callback);
278 dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
285 *STDIN = IO::File->new_from_fd($b, 'r') or die;
286 *STDOUT = IO::File->new_from_fd($b, 'w') or die;
287 *STDERR = IO::File->new_from_fd($b, 'w') or die;
289 unless ($main::is_win) {
290 # $SIG{HUP} = 'IGNORE';
291 $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
294 exec "$line" or dbg("exec '$line' failed $!");
297 dbg("cannot fork for $line");
300 dbg("no socket pair $! for $line");
308 return if exists $conn->{disconnecting};
310 $conn->{disconnecting} = 1;
311 my $sock = delete $conn->{sock};
312 $conn->{state} = 'E';
313 $conn->{timeout}->del if $conn->{timeout};
315 # be careful to delete the correct one
317 if ($call = $conn->{call}) {
318 my $ref = $conns{$call};
319 delete $conns{$call} if $ref && $ref == $conn;
321 $call ||= 'unallocated';
322 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
324 # get rid of any references
326 if (ref($conn->{$_})) {
331 if (defined($sock)) {
332 set_event_handler ($sock, read => undef, write => undef, error => undef);
337 unless ($main::is_win) {
338 kill 'TERM', $conn->{pid} if exists $conn->{pid};
343 my ($conn, $msg) = @_;
344 $conn->enqueue($msg);
345 $conn->_send (1); # 1 ==> flush
349 my ($conn, $msg) = @_;
350 $conn->enqueue($msg);
351 my $sock = $conn->{sock};
352 return unless defined($sock);
353 set_event_handler ($sock, write => sub {$conn->_send(0)});
358 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
362 my ($conn, $flush) = @_;
363 my $sock = $conn->{sock};
364 return unless defined($sock);
365 my $rq = $conn->{outqueue};
367 # If $flush is set, set the socket to blocking, and send all
368 # messages in the queue - return only if there's an error
369 # If $flush is 0 (deferred mode) make the socket non-blocking, and
370 # return to the event loop only after every message, or if it
371 # is likely to block in the middle of a message.
373 # if ($conn->{blocking} != $flush) {
374 # blocking($sock, $flush);
375 # $conn->{blocking} = $flush;
377 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
381 my $mlth = length($msg);
382 my $bytes_to_write = $mlth - $offset;
383 my $bytes_written = 0;
384 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
385 while ($bytes_to_write > 0) {
386 $bytes_written = syswrite ($sock, $msg,
387 $bytes_to_write, $offset);
388 if (!defined($bytes_written)) {
389 if (_err_will_block($!)) {
390 # Should happen only in deferred mode. Record how
391 # much we have already sent.
392 $conn->{send_offset} = $offset;
393 # Event handler should already be set, so we will
394 # be called back eventually, and will resume sending
397 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
399 return 0; # fail. Message remains in queue ..
401 } elsif (isdbg('raw')) {
402 my $call = $conn->{call} || 'none';
403 dbgdump('raw', "$call send $bytes_written: ", $msg);
405 $total_out += $bytes_written;
406 $offset += $bytes_written;
407 $bytes_to_write -= $bytes_written;
409 delete $conn->{send_offset};
412 #last unless $flush; # Go back to select and wait
413 # for it to fire again.
415 # Call me back if queue has not been drained.
417 set_event_handler ($sock, write => undef);
418 if (exists $conn->{close_on_empty}) {
419 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
429 my $oldsock = $conn->{sock};
430 my $rc = $rd_callbacks{$oldsock};
431 my $wc = $wt_callbacks{$oldsock};
432 my $ec = $er_callbacks{$oldsock};
433 my $sock = $oldsock->new_from_fd($oldsock, "w+");
435 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
436 $conn->{sock} = $sock;
437 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
442 sub _err_will_block {
443 return 0 unless $blocking_supported;
444 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
450 $conn->{close_on_empty} = 1;
453 #-----------------------------------------------------------------
454 # Receive side routines
457 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
458 my ($pkg, $my_host, $my_port, $login_proc) = @_;
459 my $self = $pkg->new($login_proc);
461 $self->{sock} = $io_socket->new (
462 LocalAddr => "$my_host:$my_port",
463 # LocalPort => $my_port,
467 die "Could not create socket: $! \n" unless $self->{sock};
468 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
477 unless ($main::is_win) {
479 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
480 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
481 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
482 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
485 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
486 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
487 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
488 $conn->{sock}->autoflush(0);
491 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
492 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
493 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
494 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
503 if ($conn->{msg} =~ /\n/) {
504 my @lines = split /\r?\n/, $conn->{msg};
505 if ($conn->{msg} =~ /\n$/) {
508 $conn->{msg} = pop @lines;
511 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
516 sub _rcv { # Complement to _send
517 my $conn = shift; # $rcv_now complement of $flush
518 # Find out how much has already been received, if at all
519 my ($msg, $offset, $bytes_to_read, $bytes_read);
520 my $sock = $conn->{sock};
521 return unless defined($sock);
524 # if ($conn->{blocking}) {
525 # blocking($sock, 0);
526 # $conn->{blocking} = 0;
528 $bytes_read = sysread ($sock, $msg, 1024, 0);
529 if (defined ($bytes_read)) {
530 if ($bytes_read > 0) {
531 $total_in += $bytes_read;
533 my $call = $conn->{call} || 'none';
534 dbgdump('raw', "$call read $bytes_read: ", $msg);
537 my @ch = split //, $msg;
542 $conn->{msg} =~ s/.$//;
549 set_event_handler ($sock, write => sub{$conn->_send(0)});
550 push @{$conn->{outqueue}}, $out;
553 $conn->{msg} .= $msg;
557 if (_err_will_block($!)) {
565 if (defined $bytes_read && $bytes_read == 0) {
566 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
569 unless ($conn->{disable_read}) {
570 $conn->dequeue if exists $conn->{msg};
576 my $server_conn = shift;
577 my $sock = $server_conn->{sock}->accept();
579 my $conn = $server_conn->new($server_conn->{rproc});
580 $conn->{sock} = $sock;
583 $conn->{blocking} = 0;
584 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
585 $conn->{sort} = 'Incoming';
587 $conn->{eproc} = $eproc;
588 set_event_handler ($sock, error => $eproc);
591 $conn->{rproc} = $rproc;
592 my $callback = sub {$conn->_rcv};
593 set_event_handler ($sock, read => $callback);
594 } else { # Login failed
595 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
599 dbg("Msg: error on accept ($!)") if isdbg('err');
606 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
607 $conn->{sock}->close;
610 # close all clients (this is for forking really)
611 sub close_all_clients
613 foreach my $conn (values %conns) {
621 set_event_handler ($conn->{sock}, read => undef);
622 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
626 #----------------------------------------------------
627 # Event loop routines used by both client and server
629 sub set_event_handler {
630 shift unless ref($_[0]); # shift if first arg is package name
631 my ($handle, %args) = @_;
633 if (exists $args{'write'}) {
634 $callback = $args{'write'};
636 $wt_callbacks{$handle} = $callback;
637 $wt_handles->add($handle);
639 delete $wt_callbacks{$handle};
640 $wt_handles->remove($handle);
643 if (exists $args{'read'}) {
644 $callback = $args{'read'};
646 $rd_callbacks{$handle} = $callback;
647 $rd_handles->add($handle);
649 delete $rd_callbacks{$handle};
650 $rd_handles->remove($handle);
653 if (exists $args{'error'}) {
654 $callback = $args{'error'};
656 $er_callbacks{$handle} = $callback;
657 $er_handles->add($handle);
659 delete $er_callbacks{$handle};
660 $er_handles->remove($handle);
666 my ($pkg, $loop_count, $timeout, $wronly) = @_; # event_loop(1) to process events once
667 my ($conn, $r, $w, $e, $rset, $wset, $eset);
670 # Quit the loop if no handles left to process
672 last unless $wt_handles->count();
674 ($rset, $wset, $eset) = IO::Select->select(undef, $wt_handles, undef, $timeout);
676 foreach $w (@$wset) {
677 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
681 last unless ($rd_handles->count() || $wt_handles->count());
683 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
685 foreach $e (@$eset) {
686 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
688 foreach $r (@$rset) {
689 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
691 foreach $w (@$wset) {
692 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
698 if (defined($loop_count)) {
699 last unless --$loop_count;
706 my ($pkg, $interval) = @_;
708 while (time - $now < $interval) {
709 $pkg->event_loop(10, 0.01);
716 my $call = $conn->{call} || 'unallocated';
717 my $host = $conn->{peerhost} || '';
718 my $port = $conn->{peerport} || '';
719 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');