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));
59 my $eagain = eval {EAGAIN()};
60 my $einprogress = eval {EINPROGRESS()};
61 my $ewouldblock = eval {EWOULDBLOCK()};
67 #-----------------------------------------------------------------
68 # Generalised initializer
72 my ($pkg, $rproc) = @_;
74 my $class = $obj || $pkg;
85 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
90 dbg("Connection created ($noconns)") if isdbg('connll');
91 return bless $conn, $class;
98 $conn->{eproc} = $callback;
99 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
105 my $callback = shift;
106 $conn->{rproc} = $callback;
111 return unless $blocking_supported;
113 my $flags = fcntl ($_[0], F_GETFL, 0);
115 $flags &= ~O_NONBLOCK;
117 $flags |= O_NONBLOCK;
119 fcntl ($_[0], F_SETFL, $flags);
130 $call = $pkg->{call} unless $call;
131 return undef unless $call;
132 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
133 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
134 $pkg->{call} = $call;
135 $ref = $conns{$call} = $pkg;
136 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
138 $ref = $conns{$call};
143 # this is only called by any dependent processes going away unexpectedly
146 my ($pkg, $pid) = @_;
148 my @pid = grep {$_->{pid} == $pid} values %conns;
149 foreach my $p (@pid) {
150 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
155 #-----------------------------------------------------------------
158 my ($pkg, $to_host, $to_port, $rproc) = @_;
160 # Create a connection end-point object
163 $conn = $pkg->new($rproc);
165 $conn->{peerhost} = $to_host;
166 $conn->{peerport} = $to_port;
167 $conn->{sort} = 'Outgoing';
169 # Create a new internet socket
170 my $sock = IO::Socket::INET->new();
171 return undef unless $sock;
173 my $proto = getprotobyname('tcp');
174 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
177 $conn->{blocking} = 0;
179 my $ip = gethostbyname($to_host);
180 # my $r = $sock->connect($to_port, $ip);
181 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
182 return undef unless $r || _err_will_block($!);
184 $conn->{sock} = $sock;
186 if ($conn->{rproc}) {
187 my $callback = sub {$conn->_rcv};
188 set_event_handler ($sock, read => $callback);
195 return if exists $conn->{disconnecting};
197 $conn->{disconnecting} = 1;
198 my $sock = delete $conn->{sock};
199 $conn->{state} = 'E';
200 $conn->{timeout}->del if $conn->{timeout};
202 # be careful to delete the correct one
204 if ($call = $conn->{call}) {
205 my $ref = $conns{$call};
206 delete $conns{$call} if $ref && $ref == $conn;
208 $call ||= 'unallocated';
209 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
211 unless ($main::is_win) {
212 kill 'TERM', $conn->{pid} if exists $conn->{pid};
215 # get rid of any references
217 if (ref($conn->{$_})) {
222 return unless defined($sock);
223 set_event_handler ($sock, read => undef, write => undef, error => undef);
229 my ($conn, $msg) = @_;
230 $conn->enqueue($msg);
231 $conn->_send (1); # 1 ==> flush
235 my ($conn, $msg) = @_;
236 $conn->enqueue($msg);
237 my $sock = $conn->{sock};
238 return unless defined($sock);
239 set_event_handler ($sock, write => sub {$conn->_send(0)});
244 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
248 my ($conn, $flush) = @_;
249 my $sock = $conn->{sock};
250 return unless defined($sock);
251 my $rq = $conn->{outqueue};
253 # If $flush is set, set the socket to blocking, and send all
254 # messages in the queue - return only if there's an error
255 # If $flush is 0 (deferred mode) make the socket non-blocking, and
256 # return to the event loop only after every message, or if it
257 # is likely to block in the middle of a message.
259 if ($conn->{blocking} != $flush) {
260 blocking($sock, $flush);
261 $conn->{blocking} = $flush;
263 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
267 my $mlth = length($msg);
268 my $bytes_to_write = $mlth - $offset;
269 my $bytes_written = 0;
270 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
271 while ($bytes_to_write > 0) {
272 $bytes_written = syswrite ($sock, $msg,
273 $bytes_to_write, $offset);
274 if (!defined($bytes_written)) {
275 if (_err_will_block($!)) {
276 # Should happen only in deferred mode. Record how
277 # much we have already sent.
278 $conn->{send_offset} = $offset;
279 # Event handler should already be set, so we will
280 # be called back eventually, and will resume sending
283 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
285 return 0; # fail. Message remains in queue ..
287 } elsif (isdbg('raw')) {
288 my $call = $conn->{call} || 'none';
289 dbgdump('raw', "$call send $bytes_written: ", $msg);
291 $offset += $bytes_written;
292 $bytes_to_write -= $bytes_written;
294 delete $conn->{send_offset};
297 #last unless $flush; # Go back to select and wait
298 # for it to fire again.
300 # Call me back if queue has not been drained.
302 set_event_handler ($sock, write => undef);
303 if (exists $conn->{close_on_empty}) {
304 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
314 my $oldsock = $conn->{sock};
315 my $rc = $rd_callbacks{$oldsock};
316 my $wc = $wt_callbacks{$oldsock};
317 my $ec = $er_callbacks{$oldsock};
318 my $sock = $oldsock->new_from_fd($oldsock, "w+");
320 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
321 $conn->{sock} = $sock;
322 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
327 sub _err_will_block {
328 return 0 unless $blocking_supported;
329 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
335 $conn->{close_on_empty} = 1;
338 #-----------------------------------------------------------------
339 # Receive side routines
342 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
343 my ($pkg, $my_host, $my_port, $login_proc) = @_;
344 my $self = $pkg->new($login_proc);
346 $self->{sock} = IO::Socket::INET->new (
347 LocalAddr => "$my_host:$my_port",
348 # LocalPort => $my_port,
353 die "Could not create socket: $! \n" unless $self->{sock};
354 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
362 if ($conn->{msg} =~ /\n/) {
363 my @lines = split /\r?\n/, $conn->{msg};
364 if ($conn->{msg} =~ /\n$/) {
367 $conn->{msg} = pop @lines;
370 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
375 sub _rcv { # Complement to _send
376 my $conn = shift; # $rcv_now complement of $flush
377 # Find out how much has already been received, if at all
378 my ($msg, $offset, $bytes_to_read, $bytes_read);
379 my $sock = $conn->{sock};
380 return unless defined($sock);
383 if ($conn->{blocking}) {
385 $conn->{blocking} = 0;
387 $bytes_read = sysread ($sock, $msg, 1024, 0);
388 if (defined ($bytes_read)) {
389 if ($bytes_read > 0) {
391 my $call = $conn->{call} || 'none';
392 dbgdump('raw', "$call read $bytes_read: ", $msg);
395 my @ch = split //, $msg;
400 $conn->{msg} =~ s/.$//;
407 set_event_handler ($sock, write => sub{$conn->_send(0)});
408 push @{$conn->{outqueue}}, $out;
411 $conn->{msg} .= $msg;
415 if (_err_will_block($!)) {
423 if (defined $bytes_read && $bytes_read == 0) {
424 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
427 unless ($conn->{disable_read}) {
428 $conn->dequeue if exists $conn->{msg};
434 my $server_conn = shift;
435 my $sock = $server_conn->{sock}->accept();
437 my $conn = $server_conn->new($server_conn->{rproc});
438 $conn->{sock} = $sock;
440 $conn->{blocking} = 0;
441 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
442 $conn->{sort} = 'Incoming';
444 $conn->{eproc} = $eproc;
445 set_event_handler ($sock, error => $eproc);
448 $conn->{rproc} = $rproc;
449 my $callback = sub {$conn->_rcv};
450 set_event_handler ($sock, read => $callback);
451 } else { # Login failed
452 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
456 dbg("Msg: error on accept ($!)") if isdbg('err');
463 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
464 $conn->{sock}->close;
467 # close all clients (this is for forking really)
468 sub close_all_clients
470 foreach my $conn (values %conns) {
478 set_event_handler ($conn->{sock}, read => undef);
479 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
483 #----------------------------------------------------
484 # Event loop routines used by both client and server
486 sub set_event_handler {
487 shift unless ref($_[0]); # shift if first arg is package name
488 my ($handle, %args) = @_;
490 if (exists $args{'write'}) {
491 $callback = $args{'write'};
493 $wt_callbacks{$handle} = $callback;
494 $wt_handles->add($handle);
496 delete $wt_callbacks{$handle};
497 $wt_handles->remove($handle);
500 if (exists $args{'read'}) {
501 $callback = $args{'read'};
503 $rd_callbacks{$handle} = $callback;
504 $rd_handles->add($handle);
506 delete $rd_callbacks{$handle};
507 $rd_handles->remove($handle);
510 if (exists $args{'error'}) {
511 $callback = $args{'error'};
513 $er_callbacks{$handle} = $callback;
514 $er_handles->add($handle);
516 delete $er_callbacks{$handle};
517 $er_handles->remove($handle);
523 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
524 my ($conn, $r, $w, $e, $rset, $wset, $eset);
527 # Quit the loop if no handles left to process
528 last unless ($rd_handles->count() || $wt_handles->count());
530 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
532 foreach $e (@$eset) {
533 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
535 foreach $r (@$rset) {
536 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
538 foreach $w (@$wset) {
539 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
544 if (defined($loop_count)) {
545 last unless --$loop_count;
552 my ($pkg, $interval) = @_;
554 while (time - $now < $interval) {
555 $pkg->event_loop(10, 0.01);
562 my $call = $conn->{call} || 'unallocated';
563 my $host = $conn->{peerhost} || '';
564 my $port = $conn->{peerport} || '';
565 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');