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
40 require POSIX; POSIX->import(qw(O_NONBLOCK F_SETFL F_GETFL))
42 if ($@ || $main::is_win) {
43 # print STDERR "POSIX Blocking *** NOT *** supported $@\n";
44 $blocking_supported = 0;
46 $blocking_supported = 1;
47 # print STDERR "POSIX Blocking enabled\n";
51 # import as many of these errno values as are available
53 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
55 # http://support.microsoft.com/support/kb/articles/Q150/5/37.asp
56 # defines EINPROGRESS as 10035. We provide it here because some
57 # Win32 users report POSIX::EINPROGRESS is not vendor-supported.
58 if ($^O eq 'MSWin32') {
59 eval '*EINPROGRESS = sub { 10036 };';
60 eval '*EWOULDBLOCK = *EAGAIN = sub { 10035 };';
61 $blocking_supported = 1;
67 my $eagain = eval {EAGAIN()};
68 my $einprogress = eval {EINPROGRESS()};
69 my $ewouldblock = eval {EWOULDBLOCK()};
75 #-----------------------------------------------------------------
76 # Generalised initializer
80 my ($pkg, $rproc) = @_;
82 my $class = $obj || $pkg;
93 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
98 dbg("Connection created ($noconns)") if isdbg('connll');
99 return bless $conn, $class;
105 my $callback = shift;
106 $conn->{eproc} = $callback;
107 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
113 my $callback = shift;
114 $conn->{rproc} = $callback;
119 return unless $blocking_supported;
121 # Make the handle stop blocking, the Windows way.
123 # 126 is FIONBIO (some docs say 0x7F << 16)
125 0x80000000 | (4 << 16) | (ord('f') << 8) | 126,
130 my $flags = fcntl ($_[0], F_GETFL, 0);
132 $flags &= ~O_NONBLOCK;
134 $flags |= O_NONBLOCK;
136 fcntl ($_[0], F_SETFL, $flags);
147 $call = $pkg->{call} unless $call;
148 return undef unless $call;
149 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
150 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
151 $pkg->{call} = $call;
152 $ref = $conns{$call} = $pkg;
153 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
155 $ref = $conns{$call};
160 # this is only called by any dependent processes going away unexpectedly
163 my ($pkg, $pid) = @_;
165 my @pid = grep {$_->{pid} == $pid} values %conns;
166 foreach my $p (@pid) {
167 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
172 #-----------------------------------------------------------------
175 my ($pkg, $to_host, $to_port, $rproc) = @_;
177 # Create a connection end-point object
180 $conn = $pkg->new($rproc);
182 $conn->{peerhost} = $to_host;
183 $conn->{peerport} = $to_port;
184 $conn->{sort} = 'Outgoing';
186 # Create a new internet socket
187 my $sock = IO::Socket::INET->new();
188 return undef unless $sock;
190 my $proto = getprotobyname('tcp');
191 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
194 $conn->{blocking} = 0;
196 my $ip = gethostbyname($to_host);
197 # my $r = $sock->connect($to_port, $ip);
198 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
199 return undef unless $r || _err_will_block($!);
201 $conn->{sock} = $sock;
203 if ($conn->{rproc}) {
204 my $callback = sub {$conn->_rcv};
205 set_event_handler ($sock, read => $callback);
212 return if exists $conn->{disconnecting};
214 $conn->{disconnecting} = 1;
215 my $sock = delete $conn->{sock};
216 $conn->{state} = 'E';
217 $conn->{timeout}->del if $conn->{timeout};
219 # be careful to delete the correct one
221 if ($call = $conn->{call}) {
222 my $ref = $conns{$call};
223 delete $conns{$call} if $ref && $ref == $conn;
225 $call ||= 'unallocated';
226 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
228 # get rid of any references
230 if (ref($conn->{$_})) {
235 if (defined($sock)) {
236 set_event_handler ($sock, read => undef, write => undef, error => undef);
241 unless ($main::is_win) {
242 kill 'TERM', $conn->{pid} if exists $conn->{pid};
248 my ($conn, $msg) = @_;
249 $conn->enqueue($msg);
250 $conn->_send (1); # 1 ==> flush
254 my ($conn, $msg) = @_;
255 $conn->enqueue($msg);
256 my $sock = $conn->{sock};
257 return unless defined($sock);
258 set_event_handler ($sock, write => sub {$conn->_send(0)});
263 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
267 my ($conn, $flush) = @_;
268 my $sock = $conn->{sock};
269 return unless defined($sock);
270 my $rq = $conn->{outqueue};
272 # If $flush is set, set the socket to blocking, and send all
273 # messages in the queue - return only if there's an error
274 # If $flush is 0 (deferred mode) make the socket non-blocking, and
275 # return to the event loop only after every message, or if it
276 # is likely to block in the middle of a message.
278 if ($conn->{blocking} != $flush) {
279 blocking($sock, $flush);
280 $conn->{blocking} = $flush;
282 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
286 my $mlth = length($msg);
287 my $bytes_to_write = $mlth - $offset;
288 my $bytes_written = 0;
289 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
290 while ($bytes_to_write > 0) {
291 $bytes_written = syswrite ($sock, $msg,
292 $bytes_to_write, $offset);
293 if (!defined($bytes_written)) {
294 if (_err_will_block($!)) {
295 # Should happen only in deferred mode. Record how
296 # much we have already sent.
297 $conn->{send_offset} = $offset;
298 # Event handler should already be set, so we will
299 # be called back eventually, and will resume sending
302 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
304 return 0; # fail. Message remains in queue ..
306 } elsif (isdbg('raw')) {
307 my $call = $conn->{call} || 'none';
308 dbgdump('raw', "$call send $bytes_written: ", $msg);
310 $offset += $bytes_written;
311 $bytes_to_write -= $bytes_written;
313 delete $conn->{send_offset};
316 #last unless $flush; # Go back to select and wait
317 # for it to fire again.
319 # Call me back if queue has not been drained.
321 set_event_handler ($sock, write => undef);
322 if (exists $conn->{close_on_empty}) {
323 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
333 my $oldsock = $conn->{sock};
334 my $rc = $rd_callbacks{$oldsock};
335 my $wc = $wt_callbacks{$oldsock};
336 my $ec = $er_callbacks{$oldsock};
337 my $sock = $oldsock->new_from_fd($oldsock, "w+");
339 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
340 $conn->{sock} = $sock;
341 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
346 sub _err_will_block {
347 return 0 unless $blocking_supported;
348 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
354 $conn->{close_on_empty} = 1;
357 #-----------------------------------------------------------------
358 # Receive side routines
361 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
362 my ($pkg, $my_host, $my_port, $login_proc) = @_;
363 my $self = $pkg->new($login_proc);
365 $self->{sock} = IO::Socket::INET->new (
366 LocalAddr => "$my_host:$my_port",
367 # LocalPort => $my_port,
371 die "Could not create socket: $! \n" unless $self->{sock};
372 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
378 eval "use Socket qw(IPPROTO_TCP TCP_NODELAY)";
380 if ($@ && !$main::inwin) {
382 sub TCP_NODELAY {1;};
390 my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER);
391 my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
392 my $n = unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
393 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
396 setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0)) or confess "setsockopt linger: $!";
397 setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1) or confess "setsockopt keepalive: $!";
398 setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1) or confess "setsockopt: $!" unless $main::iswin;
399 $conn->{sock}->autoflush(0);
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 = unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
405 dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
413 if ($conn->{msg} =~ /\n/) {
414 my @lines = split /\r?\n/, $conn->{msg};
415 if ($conn->{msg} =~ /\n$/) {
418 $conn->{msg} = pop @lines;
421 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
426 sub _rcv { # Complement to _send
427 my $conn = shift; # $rcv_now complement of $flush
428 # Find out how much has already been received, if at all
429 my ($msg, $offset, $bytes_to_read, $bytes_read);
430 my $sock = $conn->{sock};
431 return unless defined($sock);
434 if ($conn->{blocking}) {
436 $conn->{blocking} = 0;
438 $bytes_read = sysread ($sock, $msg, 1024, 0);
439 if (defined ($bytes_read)) {
440 if ($bytes_read > 0) {
442 my $call = $conn->{call} || 'none';
443 dbgdump('raw', "$call read $bytes_read: ", $msg);
446 my @ch = split //, $msg;
451 $conn->{msg} =~ s/.$//;
458 set_event_handler ($sock, write => sub{$conn->_send(0)});
459 push @{$conn->{outqueue}}, $out;
462 $conn->{msg} .= $msg;
466 if (_err_will_block($!)) {
474 if (defined $bytes_read && $bytes_read == 0) {
475 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
478 unless ($conn->{disable_read}) {
479 $conn->dequeue if exists $conn->{msg};
485 my $server_conn = shift;
486 my $sock = $server_conn->{sock}->accept();
488 my $conn = $server_conn->new($server_conn->{rproc});
489 $conn->{sock} = $sock;
492 $conn->{blocking} = 0;
493 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
494 $conn->{sort} = 'Incoming';
496 $conn->{eproc} = $eproc;
497 set_event_handler ($sock, error => $eproc);
500 $conn->{rproc} = $rproc;
501 my $callback = sub {$conn->_rcv};
502 set_event_handler ($sock, read => $callback);
503 } else { # Login failed
504 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
508 dbg("Msg: error on accept ($!)") if isdbg('err');
515 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
516 $conn->{sock}->close;
519 # close all clients (this is for forking really)
520 sub close_all_clients
522 foreach my $conn (values %conns) {
530 set_event_handler ($conn->{sock}, read => undef);
531 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
535 #----------------------------------------------------
536 # Event loop routines used by both client and server
538 sub set_event_handler {
539 shift unless ref($_[0]); # shift if first arg is package name
540 my ($handle, %args) = @_;
542 if (exists $args{'write'}) {
543 $callback = $args{'write'};
545 $wt_callbacks{$handle} = $callback;
546 $wt_handles->add($handle);
548 delete $wt_callbacks{$handle};
549 $wt_handles->remove($handle);
552 if (exists $args{'read'}) {
553 $callback = $args{'read'};
555 $rd_callbacks{$handle} = $callback;
556 $rd_handles->add($handle);
558 delete $rd_callbacks{$handle};
559 $rd_handles->remove($handle);
562 if (exists $args{'error'}) {
563 $callback = $args{'error'};
565 $er_callbacks{$handle} = $callback;
566 $er_handles->add($handle);
568 delete $er_callbacks{$handle};
569 $er_handles->remove($handle);
575 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
576 my ($conn, $r, $w, $e, $rset, $wset, $eset);
579 # Quit the loop if no handles left to process
580 last unless ($rd_handles->count() || $wt_handles->count());
582 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
584 foreach $e (@$eset) {
585 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
587 foreach $r (@$rset) {
588 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
590 foreach $w (@$wset) {
591 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
596 if (defined($loop_count)) {
597 last unless --$loop_count;
604 my ($pkg, $interval) = @_;
606 while (time - $now < $interval) {
607 $pkg->event_loop(10, 0.01);
614 my $call = $conn->{call} || 'unallocated';
615 my $host = $conn->{peerhost} || '';
616 my $port = $conn->{peerport} || '';
617 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');