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;
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 my $ip = gethostbyname($to_host);
216 # my $r = $sock->connect($to_port, $ip);
217 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
218 return undef unless $r || _err_will_block($!);
220 $conn->{sock} = $sock;
222 if ($conn->{rproc}) {
223 my $callback = sub {$conn->_rcv};
224 set_event_handler ($sock, read => $callback);
231 return if exists $conn->{disconnecting};
233 $conn->{disconnecting} = 1;
234 my $sock = delete $conn->{sock};
235 $conn->{state} = 'E';
236 $conn->{timeout}->del if $conn->{timeout};
238 # be careful to delete the correct one
240 if ($call = $conn->{call}) {
241 my $ref = $conns{$call};
242 delete $conns{$call} if $ref && $ref == $conn;
244 $call ||= 'unallocated';
245 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
247 # get rid of any references
249 if (ref($conn->{$_})) {
254 if (defined($sock)) {
255 set_event_handler ($sock, read => undef, write => undef, error => undef);
260 unless ($main::is_win) {
261 kill 'TERM', $conn->{pid} if exists $conn->{pid};
267 my ($conn, $msg) = @_;
268 $conn->enqueue($msg);
269 $conn->_send (1); # 1 ==> flush
273 my ($conn, $msg) = @_;
274 $conn->enqueue($msg);
275 my $sock = $conn->{sock};
276 return unless defined($sock);
277 set_event_handler ($sock, write => sub {$conn->_send(0)});
282 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
286 my ($conn, $flush) = @_;
287 my $sock = $conn->{sock};
288 return unless defined($sock);
289 my $rq = $conn->{outqueue};
291 # If $flush is set, set the socket to blocking, and send all
292 # messages in the queue - return only if there's an error
293 # If $flush is 0 (deferred mode) make the socket non-blocking, and
294 # return to the event loop only after every message, or if it
295 # is likely to block in the middle of a message.
297 if ($conn->{blocking} != $flush) {
298 blocking($sock, $flush);
299 $conn->{blocking} = $flush;
301 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
305 my $mlth = length($msg);
306 my $bytes_to_write = $mlth - $offset;
307 my $bytes_written = 0;
308 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
309 while ($bytes_to_write > 0) {
310 $bytes_written = syswrite ($sock, $msg,
311 $bytes_to_write, $offset);
312 if (!defined($bytes_written)) {
313 if (_err_will_block($!)) {
314 # Should happen only in deferred mode. Record how
315 # much we have already sent.
316 $conn->{send_offset} = $offset;
317 # Event handler should already be set, so we will
318 # be called back eventually, and will resume sending
321 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
323 return 0; # fail. Message remains in queue ..
325 } elsif (isdbg('raw')) {
326 my $call = $conn->{call} || 'none';
327 dbgdump('raw', "$call send $bytes_written: ", $msg);
329 $offset += $bytes_written;
330 $bytes_to_write -= $bytes_written;
332 delete $conn->{send_offset};
335 #last unless $flush; # Go back to select and wait
336 # for it to fire again.
338 # Call me back if queue has not been drained.
340 set_event_handler ($sock, write => undef);
341 if (exists $conn->{close_on_empty}) {
342 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
352 my $oldsock = $conn->{sock};
353 my $rc = $rd_callbacks{$oldsock};
354 my $wc = $wt_callbacks{$oldsock};
355 my $ec = $er_callbacks{$oldsock};
356 my $sock = $oldsock->new_from_fd($oldsock, "w+");
358 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
359 $conn->{sock} = $sock;
360 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
365 sub _err_will_block {
366 return 0 unless $blocking_supported;
367 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
373 $conn->{close_on_empty} = 1;
376 #-----------------------------------------------------------------
377 # Receive side routines
380 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
381 my ($pkg, $my_host, $my_port, $login_proc) = @_;
382 my $self = $pkg->new($login_proc);
384 $self->{sock} = IO::Socket::INET->new (
385 LocalAddr => "$my_host:$my_port",
386 # LocalPort => $my_port,
390 die "Could not create socket: $! \n" unless $self->{sock};
391 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
400 unless ($main::is_win) {
402 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
403 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
404 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
405 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
408 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
409 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
410 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
411 $conn->{sock}->autoflush(0);
414 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
415 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
416 my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
417 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
426 if ($conn->{msg} =~ /\n/) {
427 my @lines = split /\r?\n/, $conn->{msg};
428 if ($conn->{msg} =~ /\n$/) {
431 $conn->{msg} = pop @lines;
434 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
439 sub _rcv { # Complement to _send
440 my $conn = shift; # $rcv_now complement of $flush
441 # Find out how much has already been received, if at all
442 my ($msg, $offset, $bytes_to_read, $bytes_read);
443 my $sock = $conn->{sock};
444 return unless defined($sock);
447 if ($conn->{blocking}) {
449 $conn->{blocking} = 0;
451 $bytes_read = sysread ($sock, $msg, 1024, 0);
452 if (defined ($bytes_read)) {
453 if ($bytes_read > 0) {
455 my $call = $conn->{call} || 'none';
456 dbgdump('raw', "$call read $bytes_read: ", $msg);
459 my @ch = split //, $msg;
464 $conn->{msg} =~ s/.$//;
471 set_event_handler ($sock, write => sub{$conn->_send(0)});
472 push @{$conn->{outqueue}}, $out;
475 $conn->{msg} .= $msg;
479 if (_err_will_block($!)) {
487 if (defined $bytes_read && $bytes_read == 0) {
488 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
491 unless ($conn->{disable_read}) {
492 $conn->dequeue if exists $conn->{msg};
498 my $server_conn = shift;
499 my $sock = $server_conn->{sock}->accept();
501 my $conn = $server_conn->new($server_conn->{rproc});
502 $conn->{sock} = $sock;
505 $conn->{blocking} = 0;
506 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
507 $conn->{sort} = 'Incoming';
509 $conn->{eproc} = $eproc;
510 set_event_handler ($sock, error => $eproc);
513 $conn->{rproc} = $rproc;
514 my $callback = sub {$conn->_rcv};
515 set_event_handler ($sock, read => $callback);
516 } else { # Login failed
517 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
521 dbg("Msg: error on accept ($!)") if isdbg('err');
528 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
529 $conn->{sock}->close;
532 # close all clients (this is for forking really)
533 sub close_all_clients
535 foreach my $conn (values %conns) {
543 set_event_handler ($conn->{sock}, read => undef);
544 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
548 #----------------------------------------------------
549 # Event loop routines used by both client and server
551 sub set_event_handler {
552 shift unless ref($_[0]); # shift if first arg is package name
553 my ($handle, %args) = @_;
555 if (exists $args{'write'}) {
556 $callback = $args{'write'};
558 $wt_callbacks{$handle} = $callback;
559 $wt_handles->add($handle);
561 delete $wt_callbacks{$handle};
562 $wt_handles->remove($handle);
565 if (exists $args{'read'}) {
566 $callback = $args{'read'};
568 $rd_callbacks{$handle} = $callback;
569 $rd_handles->add($handle);
571 delete $rd_callbacks{$handle};
572 $rd_handles->remove($handle);
575 if (exists $args{'error'}) {
576 $callback = $args{'error'};
578 $er_callbacks{$handle} = $callback;
579 $er_handles->add($handle);
581 delete $er_callbacks{$handle};
582 $er_handles->remove($handle);
588 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
589 my ($conn, $r, $w, $e, $rset, $wset, $eset);
592 # Quit the loop if no handles left to process
593 last unless ($rd_handles->count() || $wt_handles->count());
595 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
597 foreach $e (@$eset) {
598 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
600 foreach $r (@$rset) {
601 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
603 foreach $w (@$wset) {
604 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
609 if (defined($loop_count)) {
610 last unless --$loop_count;
617 my ($pkg, $interval) = @_;
619 while (time - $now < $interval) {
620 $pkg->event_loop(10, 0.01);
627 my $call = $conn->{call} || 'unallocated';
628 my $host = $conn->{peerhost} || '';
629 my $port = $conn->{peerport} || '';
630 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');