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("Connection created ($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("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("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 $self->{peerhost};
202 #-----------------------------------------------------------------
205 my ($pkg, $to_host, $to_port, $rproc) = @_;
207 # Create a connection end-point object
210 $conn = $pkg->new($rproc);
212 $conn->{peerhost} = $to_host;
213 $conn->{peerport} = $to_port;
214 $conn->{sort} = 'Outgoing';
216 # Create a new internet socket
217 my $sock = $io_socket->new();
218 return undef unless $sock;
220 my $proto = getprotobyname('tcp');
221 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
224 $conn->{blocking} = 0;
226 # does the host resolve?
227 my $ip = gethostbyname($to_host);
228 return undef unless $ip;
230 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
231 return undef unless $r || _err_will_block($!);
233 $conn->{sock} = $sock;
234 $conn->{peerhost} = $sock->peerhost; # for consistency
236 if ($conn->{rproc}) {
237 my $callback = sub {$conn->_rcv};
238 set_event_handler ($sock, read => $callback);
245 my ($conn, $line, $sort) = @_;
248 local $^F = 10000; # make sure it ain't closed on exec
249 my ($a, $b) = $io_socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
258 $conn->{csort} = $sort;
259 $conn->{lineend} = "\cM" if $sort eq 'ax25';
261 if ($conn->{rproc}) {
262 my $callback = sub {$conn->_rcv};
263 Msg::set_event_handler ($a, read => $callback);
265 dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
272 *STDIN = IO::File->new_from_fd($b, 'r') or die;
273 *STDOUT = IO::File->new_from_fd($b, 'w') or die;
274 *STDERR = IO::File->new_from_fd($b, 'w') or die;
276 unless ($main::is_win) {
277 # $SIG{HUP} = 'IGNORE';
278 $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
281 exec "$line" or dbg("exec '$line' failed $!");
284 dbg("cannot fork for $line");
287 dbg("no socket pair $! for $line");
295 return if exists $conn->{disconnecting};
297 $conn->{disconnecting} = 1;
298 my $sock = delete $conn->{sock};
299 $conn->{state} = 'E';
300 $conn->{timeout}->del if $conn->{timeout};
302 # be careful to delete the correct one
304 if ($call = $conn->{call}) {
305 my $ref = $conns{$call};
306 delete $conns{$call} if $ref && $ref == $conn;
308 $call ||= 'unallocated';
309 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
311 # get rid of any references
313 if (ref($conn->{$_})) {
318 if (defined($sock)) {
319 set_event_handler ($sock, read => undef, write => undef, error => undef);
324 unless ($main::is_win) {
325 kill 'TERM', $conn->{pid} if exists $conn->{pid};
330 my ($conn, $msg) = @_;
331 $conn->enqueue($msg);
332 $conn->_send (1); # 1 ==> flush
336 my ($conn, $msg) = @_;
337 $conn->enqueue($msg);
338 my $sock = $conn->{sock};
339 return unless defined($sock);
340 set_event_handler ($sock, write => sub {$conn->_send(0)});
345 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
349 my ($conn, $flush) = @_;
350 my $sock = $conn->{sock};
351 return unless defined($sock);
352 my $rq = $conn->{outqueue};
354 # If $flush is set, set the socket to blocking, and send all
355 # messages in the queue - return only if there's an error
356 # If $flush is 0 (deferred mode) make the socket non-blocking, and
357 # return to the event loop only after every message, or if it
358 # is likely to block in the middle of a message.
360 # if ($conn->{blocking} != $flush) {
361 # blocking($sock, $flush);
362 # $conn->{blocking} = $flush;
364 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
368 my $mlth = length($msg);
369 my $bytes_to_write = $mlth - $offset;
370 my $bytes_written = 0;
371 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
372 while ($bytes_to_write > 0) {
373 $bytes_written = syswrite ($sock, $msg,
374 $bytes_to_write, $offset);
375 if (!defined($bytes_written)) {
376 if (_err_will_block($!)) {
377 # Should happen only in deferred mode. Record how
378 # much we have already sent.
379 $conn->{send_offset} = $offset;
380 # Event handler should already be set, so we will
381 # be called back eventually, and will resume sending
384 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
386 return 0; # fail. Message remains in queue ..
388 } elsif (isdbg('raw')) {
389 my $call = $conn->{call} || 'none';
390 dbgdump('raw', "$call send $bytes_written: ", $msg);
392 $total_out += $bytes_written;
393 $offset += $bytes_written;
394 $bytes_to_write -= $bytes_written;
396 delete $conn->{send_offset};
399 #last unless $flush; # Go back to select and wait
400 # for it to fire again.
402 # Call me back if queue has not been drained.
404 set_event_handler ($sock, write => undef);
405 if (exists $conn->{close_on_empty}) {
406 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
416 my $oldsock = $conn->{sock};
417 my $rc = $rd_callbacks{$oldsock};
418 my $wc = $wt_callbacks{$oldsock};
419 my $ec = $er_callbacks{$oldsock};
420 my $sock = $oldsock->new_from_fd($oldsock, "w+");
422 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
423 $conn->{sock} = $sock;
424 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
429 sub _err_will_block {
430 return 0 unless $blocking_supported;
431 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
437 $conn->{close_on_empty} = 1;
440 #-----------------------------------------------------------------
441 # Receive side routines
444 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
445 my ($pkg, $my_host, $my_port, $login_proc) = @_;
446 my $self = $pkg->new($login_proc);
448 $self->{sock} = $io_socket->new (
449 LocalAddr => "$my_host:$my_port",
450 # LocalPort => $my_port,
454 die "Could not create socket: $! \n" unless $self->{sock};
455 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
464 unless ($main::is_win) {
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");
472 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
473 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
474 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
475 $conn->{sock}->autoflush(0);
478 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
479 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
480 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
481 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
490 if ($conn->{msg} =~ /\n/) {
491 my @lines = split /\r?\n/, $conn->{msg};
492 if ($conn->{msg} =~ /\n$/) {
495 $conn->{msg} = pop @lines;
498 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
503 sub _rcv { # Complement to _send
504 my $conn = shift; # $rcv_now complement of $flush
505 # Find out how much has already been received, if at all
506 my ($msg, $offset, $bytes_to_read, $bytes_read);
507 my $sock = $conn->{sock};
508 return unless defined($sock);
511 # if ($conn->{blocking}) {
512 # blocking($sock, 0);
513 # $conn->{blocking} = 0;
515 $bytes_read = sysread ($sock, $msg, 1024, 0);
516 if (defined ($bytes_read)) {
517 if ($bytes_read > 0) {
518 $total_in += $bytes_read;
520 my $call = $conn->{call} || 'none';
521 dbgdump('raw', "$call read $bytes_read: ", $msg);
524 my @ch = split //, $msg;
529 $conn->{msg} =~ s/.$//;
536 set_event_handler ($sock, write => sub{$conn->_send(0)});
537 push @{$conn->{outqueue}}, $out;
540 $conn->{msg} .= $msg;
544 if (_err_will_block($!)) {
552 if (defined $bytes_read && $bytes_read == 0) {
553 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
556 unless ($conn->{disable_read}) {
557 $conn->dequeue if exists $conn->{msg};
563 my $server_conn = shift;
564 my $sock = $server_conn->{sock}->accept();
566 my $conn = $server_conn->new($server_conn->{rproc});
567 $conn->{sock} = $sock;
570 $conn->{blocking} = 0;
571 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
572 $conn->{sort} = 'Incoming';
574 $conn->{eproc} = $eproc;
575 set_event_handler ($sock, error => $eproc);
578 $conn->{rproc} = $rproc;
579 my $callback = sub {$conn->_rcv};
580 set_event_handler ($sock, read => $callback);
581 } else { # Login failed
582 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
586 dbg("Msg: error on accept ($!)") if isdbg('err');
593 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
594 $conn->{sock}->close;
597 # close all clients (this is for forking really)
598 sub close_all_clients
600 foreach my $conn (values %conns) {
608 set_event_handler ($conn->{sock}, read => undef);
609 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
613 #----------------------------------------------------
614 # Event loop routines used by both client and server
616 sub set_event_handler {
617 shift unless ref($_[0]); # shift if first arg is package name
618 my ($handle, %args) = @_;
620 if (exists $args{'write'}) {
621 $callback = $args{'write'};
623 $wt_callbacks{$handle} = $callback;
624 $wt_handles->add($handle);
626 delete $wt_callbacks{$handle};
627 $wt_handles->remove($handle);
630 if (exists $args{'read'}) {
631 $callback = $args{'read'};
633 $rd_callbacks{$handle} = $callback;
634 $rd_handles->add($handle);
636 delete $rd_callbacks{$handle};
637 $rd_handles->remove($handle);
640 if (exists $args{'error'}) {
641 $callback = $args{'error'};
643 $er_callbacks{$handle} = $callback;
644 $er_handles->add($handle);
646 delete $er_callbacks{$handle};
647 $er_handles->remove($handle);
653 my ($pkg, $loop_count, $timeout, $wronly) = @_; # event_loop(1) to process events once
654 my ($conn, $r, $w, $e, $rset, $wset, $eset);
657 # Quit the loop if no handles left to process
659 last unless $wt_handles->count();
661 ($rset, $wset, $eset) = IO::Select->select(undef, $wt_handles, undef, $timeout);
663 foreach $w (@$wset) {
664 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
668 last unless ($rd_handles->count() || $wt_handles->count());
670 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
672 foreach $e (@$eset) {
673 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
675 foreach $r (@$rset) {
676 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
678 foreach $w (@$wset) {
679 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
685 if (defined($loop_count)) {
686 last unless --$loop_count;
693 my ($pkg, $interval) = @_;
695 while (time - $now < $interval) {
696 $pkg->event_loop(10, 0.01);
703 my $call = $conn->{call} || 'unallocated';
704 my $host = $conn->{peerhost} || '';
705 my $port = $conn->{peerport} || '';
706 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');