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)
19 use vars qw(%rd_callbacks %wt_callbacks %er_callbacks $rd_handles $wt_handles $er_handles $now %conns $noconns $blocking_supported);
24 $rd_handles = IO::Select->new();
25 $wt_handles = IO::Select->new();
26 $er_handles = IO::Select->new();
31 # Checks if blocking is supported
33 require POSIX; POSIX->import(qw(O_NONBLOCK F_SETFL F_GETFL))
35 if ($@ || $main::is_win) {
36 print STDERR "POSIX Blocking *** NOT *** supported $@\n";
37 $blocking_supported = 0;
39 $blocking_supported = 1;
40 print STDERR "POSIX Blocking enabled\n";
44 # import as many of these errno values as are available
46 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
52 my $eagain = eval {EAGAIN()};
53 my $einprogress = eval {EINPROGRESS()};
54 my $ewouldblock = eval {EWOULDBLOCK()};
58 #-----------------------------------------------------------------
59 # Generalised initializer
63 my ($pkg, $rproc) = @_;
65 my $class = $obj || $pkg;
79 dbg('connll', "Connection created ($noconns)");
80 return bless $conn, $class;
87 $conn->{eproc} = $callback;
88 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
95 $conn->{rproc} = $callback;
100 return unless $blocking_supported;
102 my $flags = fcntl ($_[0], F_GETFL, 0);
104 $flags &= ~O_NONBLOCK;
106 $flags |= O_NONBLOCK;
108 fcntl ($_[0], F_SETFL, $flags);
119 $call = $pkg->{call} unless $call;
120 return undef unless $call;
121 confess "changing $pkg->{call} to $call" if exists $pkg->{call} && $call ne $pkg->{call};
122 $pkg->{call} = $call;
123 $ref = $conns{$call} = $pkg;
124 dbg('connll', "Connection $call stored");
126 $ref = $conns{$call};
131 # this is only called by any dependent processes going away unexpectedly
134 my ($pkg, $pid) = @_;
136 my @pid = grep {$_->{pid} == $pid} values %conns;
138 &{$_->{eproc}}($_, "$pid has gorn") if exists $_->{eproc};
143 #-----------------------------------------------------------------
146 my ($pkg, $to_host, $to_port, $rproc) = @_;
148 # Create a connection end-point object
151 $conn = $pkg->new($rproc);
153 $conn->{peerhost} = $to_host;
154 $conn->{peerport} = $to_port;
155 $conn->{sort} = 'Outgoing';
157 # Create a new internet socket
158 my $sock = IO::Socket::INET->new();
159 return undef unless $sock;
161 my $proto = getprotobyname('tcp');
162 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
165 $conn->{blocking} = 0;
167 my $ip = gethostbyname($to_host);
168 # my $r = $sock->connect($to_port, $ip);
169 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
170 return undef unless $r || _err_will_block($!);
172 $conn->{sock} = $sock;
174 if ($conn->{rproc}) {
175 my $callback = sub {$conn->_rcv};
176 set_event_handler ($sock, read => $callback);
183 return if exists $conn->{disconnecting};
185 $conn->{disconnecting} = 1;
186 my $sock = delete $conn->{sock};
187 $conn->{state} = 'E';
188 $conn->{timeout}->del if $conn->{timeout};
190 # be careful to delete the correct one
192 if ($call = $conn->{call}) {
193 my $ref = $conns{$call};
194 delete $conns{$call} if $ref && $ref == $conn;
196 $call ||= 'unallocated';
197 dbg('connll', "Connection $call disconnected");
199 unless ($main::is_win) {
200 kill 'TERM', $conn->{pid} if exists $conn->{pid};
203 # get rid of any references
205 if (ref($conn->{$_})) {
210 return unless defined($sock);
211 set_event_handler ($sock, read => undef, write => undef, error => undef);
217 my ($conn, $msg) = @_;
218 $conn->enqueue($msg);
219 $conn->_send (1); # 1 ==> flush
223 my ($conn, $msg) = @_;
224 $conn->enqueue($msg);
225 my $sock = $conn->{sock};
226 return unless defined($sock);
227 set_event_handler ($sock, write => sub {$conn->_send(0)});
232 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
236 my ($conn, $flush) = @_;
237 my $sock = $conn->{sock};
238 return unless defined($sock);
239 my $rq = $conn->{outqueue};
241 # If $flush is set, set the socket to blocking, and send all
242 # messages in the queue - return only if there's an error
243 # If $flush is 0 (deferred mode) make the socket non-blocking, and
244 # return to the event loop only after every message, or if it
245 # is likely to block in the middle of a message.
247 if ($conn->{blocking} != $flush) {
248 blocking($sock, $flush);
249 $conn->{blocking} = $flush;
251 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
255 my $mlth = length($msg);
256 my $bytes_to_write = $mlth - $offset;
257 my $bytes_written = 0;
258 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
259 while ($bytes_to_write > 0) {
260 $bytes_written = syswrite ($sock, $msg,
261 $bytes_to_write, $offset);
262 if (!defined($bytes_written)) {
263 if (_err_will_block($!)) {
264 # Should happen only in deferred mode. Record how
265 # much we have already sent.
266 $conn->{send_offset} = $offset;
267 # Event handler should already be set, so we will
268 # be called back eventually, and will resume sending
271 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
273 return 0; # fail. Message remains in queue ..
276 $offset += $bytes_written;
277 $bytes_to_write -= $bytes_written;
279 delete $conn->{send_offset};
282 last unless $flush; # Go back to select and wait
283 # for it to fire again.
285 # Call me back if queue has not been drained.
287 set_event_handler ($sock, write => sub {$conn->_send(0)});
289 set_event_handler ($sock, write => undef);
290 if (exists $conn->{close_on_empty}) {
291 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
301 my $oldsock = $conn->{sock};
302 my $rc = $rd_callbacks{$oldsock};
303 my $wc = $wt_callbacks{$oldsock};
304 my $ec = $er_callbacks{$oldsock};
305 my $sock = $oldsock->new_from_fd($oldsock, "w+");
307 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
308 $conn->{sock} = $sock;
309 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
314 sub _err_will_block {
315 return 0 unless $blocking_supported;
316 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
322 $conn->{close_on_empty} = 1;
325 #-----------------------------------------------------------------
326 # Receive side routines
329 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
330 my ($pkg, $my_host, $my_port, $login_proc) = @_;
331 my $self = $pkg->new($login_proc);
333 $self->{sock} = IO::Socket::INET->new (
334 LocalAddr => $my_host,
335 LocalPort => $my_port,
339 die "Could not create socket: $! \n" unless $self->{sock};
340 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
348 if ($conn->{msg} =~ /\n/) {
349 my @lines = split /\r?\n/, $conn->{msg};
350 if ($conn->{msg} =~ /\n$/) {
353 $conn->{msg} = pop @lines;
356 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
361 sub _rcv { # Complement to _send
362 my $conn = shift; # $rcv_now complement of $flush
363 # Find out how much has already been received, if at all
364 my ($msg, $offset, $bytes_to_read, $bytes_read);
365 my $sock = $conn->{sock};
366 return unless defined($sock);
369 if ($conn->{blocking}) {
371 $conn->{blocking} = 0;
373 $bytes_read = sysread ($sock, $msg, 1024, 0);
374 if (defined ($bytes_read)) {
375 if ($bytes_read > 0) {
376 $conn->{msg} .= $msg;
379 if (_err_will_block($!)) {
387 if (defined $bytes_read && $bytes_read == 0) {
388 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
391 $conn->dequeue if exists $conn->{msg};
396 my $server_conn = shift;
397 my $sock = $server_conn->{sock}->accept();
399 my $conn = $server_conn->new($server_conn->{rproc});
400 $conn->{sock} = $sock;
402 $conn->{blocking} = 0;
403 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
404 $conn->{sort} = 'Incoming';
406 $conn->{eproc} = $eproc;
407 set_event_handler ($sock, error => $eproc);
410 $conn->{rproc} = $rproc;
411 my $callback = sub {$conn->_rcv};
412 set_event_handler ($sock, read => $callback);
413 } else { # Login failed
414 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
418 dbg('err', "Msg: error on accept ($!)");
425 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
426 $conn->{sock}->close;
429 # close all clients (this is for forking really)
430 sub close_all_clients
432 for (values %conns) {
438 #----------------------------------------------------
439 # Event loop routines used by both client and server
441 sub set_event_handler {
442 shift unless ref($_[0]); # shift if first arg is package name
443 my ($handle, %args) = @_;
445 if (exists $args{'write'}) {
446 $callback = $args{'write'};
448 $wt_callbacks{$handle} = $callback;
449 $wt_handles->add($handle);
451 delete $wt_callbacks{$handle};
452 $wt_handles->remove($handle);
455 if (exists $args{'read'}) {
456 $callback = $args{'read'};
458 $rd_callbacks{$handle} = $callback;
459 $rd_handles->add($handle);
461 delete $rd_callbacks{$handle};
462 $rd_handles->remove($handle);
465 if (exists $args{'error'}) {
466 $callback = $args{'error'};
468 $er_callbacks{$handle} = $callback;
469 $er_handles->add($handle);
471 delete $er_callbacks{$handle};
472 $er_handles->remove($handle);
478 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
479 my ($conn, $r, $w, $e, $rset, $wset, $eset);
482 # Quit the loop if no handles left to process
483 last unless ($rd_handles->count() || $wt_handles->count());
485 ($rset, $wset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
487 foreach $e (@$eset) {
488 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
490 foreach $r (@$rset) {
491 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
493 foreach $w (@$wset) {
494 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
499 if (defined($loop_count)) {
500 last unless --$loop_count;
507 my ($pkg, $interval) = @_;
509 while (time - $now < $interval) {
510 $pkg->event_loop(10, 0.01);
517 my $call = $conn->{call} || 'unallocated';
518 dbg('connll', "Connection $call being destroyed ($noconns)");