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 return if exists $conn->{disconnecting};
236 $conn->{disconnecting} = 1;
237 my $sock = delete $conn->{sock};
238 $conn->{state} = 'E';
239 $conn->{timeout}->del if $conn->{timeout};
241 # be careful to delete the correct one
243 if ($call = $conn->{call}) {
244 my $ref = $conns{$call};
245 delete $conns{$call} if $ref && $ref == $conn;
247 $call ||= 'unallocated';
248 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
250 # get rid of any references
252 if (ref($conn->{$_})) {
257 if (defined($sock)) {
258 set_event_handler ($sock, read => undef, write => undef, error => undef);
263 unless ($main::is_win) {
264 kill 'TERM', $conn->{pid} if exists $conn->{pid};
270 my ($conn, $msg) = @_;
271 $conn->enqueue($msg);
272 $conn->_send (1); # 1 ==> flush
276 my ($conn, $msg) = @_;
277 $conn->enqueue($msg);
278 my $sock = $conn->{sock};
279 return unless defined($sock);
280 set_event_handler ($sock, write => sub {$conn->_send(0)});
285 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
289 my ($conn, $flush) = @_;
290 my $sock = $conn->{sock};
291 return unless defined($sock);
292 my $rq = $conn->{outqueue};
294 # If $flush is set, set the socket to blocking, and send all
295 # messages in the queue - return only if there's an error
296 # If $flush is 0 (deferred mode) make the socket non-blocking, and
297 # return to the event loop only after every message, or if it
298 # is likely to block in the middle of a message.
300 if ($conn->{blocking} != $flush) {
301 blocking($sock, $flush);
302 $conn->{blocking} = $flush;
304 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
308 my $mlth = length($msg);
309 my $bytes_to_write = $mlth - $offset;
310 my $bytes_written = 0;
311 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
312 while ($bytes_to_write > 0) {
313 $bytes_written = syswrite ($sock, $msg,
314 $bytes_to_write, $offset);
315 if (!defined($bytes_written)) {
316 if (_err_will_block($!)) {
317 # Should happen only in deferred mode. Record how
318 # much we have already sent.
319 $conn->{send_offset} = $offset;
320 # Event handler should already be set, so we will
321 # be called back eventually, and will resume sending
324 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
326 return 0; # fail. Message remains in queue ..
328 } elsif (isdbg('raw')) {
329 my $call = $conn->{call} || 'none';
330 dbgdump('raw', "$call send $bytes_written: ", $msg);
332 $offset += $bytes_written;
333 $bytes_to_write -= $bytes_written;
335 delete $conn->{send_offset};
338 #last unless $flush; # Go back to select and wait
339 # for it to fire again.
341 # Call me back if queue has not been drained.
343 set_event_handler ($sock, write => undef);
344 if (exists $conn->{close_on_empty}) {
345 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
355 my $oldsock = $conn->{sock};
356 my $rc = $rd_callbacks{$oldsock};
357 my $wc = $wt_callbacks{$oldsock};
358 my $ec = $er_callbacks{$oldsock};
359 my $sock = $oldsock->new_from_fd($oldsock, "w+");
361 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
362 $conn->{sock} = $sock;
363 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
368 sub _err_will_block {
369 return 0 unless $blocking_supported;
370 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
376 $conn->{close_on_empty} = 1;
379 #-----------------------------------------------------------------
380 # Receive side routines
383 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
384 my ($pkg, $my_host, $my_port, $login_proc) = @_;
385 my $self = $pkg->new($login_proc);
387 $self->{sock} = IO::Socket::INET->new (
388 LocalAddr => "$my_host:$my_port",
389 # LocalPort => $my_port,
393 die "Could not create socket: $! \n" unless $self->{sock};
394 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
403 unless ($main::is_win) {
405 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
406 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
407 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
408 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
411 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
412 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
413 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
414 $conn->{sock}->autoflush(0);
417 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
418 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
419 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
420 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
429 if ($conn->{msg} =~ /\n/) {
430 my @lines = split /\r?\n/, $conn->{msg};
431 if ($conn->{msg} =~ /\n$/) {
434 $conn->{msg} = pop @lines;
437 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
442 sub _rcv { # Complement to _send
443 my $conn = shift; # $rcv_now complement of $flush
444 # Find out how much has already been received, if at all
445 my ($msg, $offset, $bytes_to_read, $bytes_read);
446 my $sock = $conn->{sock};
447 return unless defined($sock);
450 if ($conn->{blocking}) {
452 $conn->{blocking} = 0;
454 $bytes_read = sysread ($sock, $msg, 1024, 0);
455 if (defined ($bytes_read)) {
456 if ($bytes_read > 0) {
458 my $call = $conn->{call} || 'none';
459 dbgdump('raw', "$call read $bytes_read: ", $msg);
462 my @ch = split //, $msg;
467 $conn->{msg} =~ s/.$//;
474 set_event_handler ($sock, write => sub{$conn->_send(0)});
475 push @{$conn->{outqueue}}, $out;
478 $conn->{msg} .= $msg;
482 if (_err_will_block($!)) {
490 if (defined $bytes_read && $bytes_read == 0) {
491 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
494 unless ($conn->{disable_read}) {
495 $conn->dequeue if exists $conn->{msg};
501 my $server_conn = shift;
502 my $sock = $server_conn->{sock}->accept();
504 my $conn = $server_conn->new($server_conn->{rproc});
505 $conn->{sock} = $sock;
508 $conn->{blocking} = 0;
509 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
510 $conn->{sort} = 'Incoming';
512 $conn->{eproc} = $eproc;
513 set_event_handler ($sock, error => $eproc);
516 $conn->{rproc} = $rproc;
517 my $callback = sub {$conn->_rcv};
518 set_event_handler ($sock, read => $callback);
519 } else { # Login failed
520 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
524 dbg("Msg: error on accept ($!)") if isdbg('err');
531 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
532 $conn->{sock}->close;
535 # close all clients (this is for forking really)
536 sub close_all_clients
538 foreach my $conn (values %conns) {
546 set_event_handler ($conn->{sock}, read => undef);
547 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
551 #----------------------------------------------------
552 # Event loop routines used by both client and server
554 sub set_event_handler {
555 shift unless ref($_[0]); # shift if first arg is package name
556 my ($handle, %args) = @_;
558 if (exists $args{'write'}) {
559 $callback = $args{'write'};
561 $wt_callbacks{$handle} = $callback;
562 $wt_handles->add($handle);
564 delete $wt_callbacks{$handle};
565 $wt_handles->remove($handle);
568 if (exists $args{'read'}) {
569 $callback = $args{'read'};
571 $rd_callbacks{$handle} = $callback;
572 $rd_handles->add($handle);
574 delete $rd_callbacks{$handle};
575 $rd_handles->remove($handle);
578 if (exists $args{'error'}) {
579 $callback = $args{'error'};
581 $er_callbacks{$handle} = $callback;
582 $er_handles->add($handle);
584 delete $er_callbacks{$handle};
585 $er_handles->remove($handle);
591 my ($pkg, $loop_count, $timeout, $wronly) = @_; # event_loop(1) to process events once
592 my ($conn, $r, $w, $e, $rset, $wset, $eset);
595 # Quit the loop if no handles left to process
597 last unless $wt_handles->count();
599 ($rset, $wset, $eset) = IO::Select->select(undef, $wt_handles, undef, $timeout);
601 foreach $w (@$wset) {
602 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
606 last unless ($rd_handles->count() || $wt_handles->count());
608 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
610 foreach $e (@$eset) {
611 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
613 foreach $r (@$rset) {
614 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
616 foreach $w (@$wset) {
617 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
623 if (defined($loop_count)) {
624 last unless --$loop_count;
631 my ($pkg, $interval) = @_;
633 while (time - $now < $interval) {
634 $pkg->event_loop(10, 0.01);
641 my $call = $conn->{call} || 'unallocated';
642 my $host = $conn->{peerhost} || '';
643 my $port = $conn->{peerport} || '';
644 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');