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 $cnum);
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()};
60 #-----------------------------------------------------------------
61 # Generalised initializer
65 my ($pkg, $rproc) = @_;
67 my $class = $obj || $pkg;
78 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
83 dbg("Connection created ($noconns)") if isdbg('connll');
84 return bless $conn, $class;
91 $conn->{eproc} = $callback;
92 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
99 $conn->{rproc} = $callback;
104 return unless $blocking_supported;
106 my $flags = fcntl ($_[0], F_GETFL, 0);
108 $flags &= ~O_NONBLOCK;
110 $flags |= O_NONBLOCK;
112 fcntl ($_[0], F_SETFL, $flags);
123 $call = $pkg->{call} unless $call;
124 return undef unless $call;
125 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
126 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
127 $pkg->{call} = $call;
128 $ref = $conns{$call} = $pkg;
129 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
131 $ref = $conns{$call};
136 # this is only called by any dependent processes going away unexpectedly
139 my ($pkg, $pid) = @_;
141 my @pid = grep {$_->{pid} == $pid} values %conns;
142 foreach my $p (@pid) {
143 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
148 #-----------------------------------------------------------------
151 my ($pkg, $to_host, $to_port, $rproc) = @_;
153 # Create a connection end-point object
156 $conn = $pkg->new($rproc);
158 $conn->{peerhost} = $to_host;
159 $conn->{peerport} = $to_port;
160 $conn->{sort} = 'Outgoing';
162 # Create a new internet socket
163 my $sock = IO::Socket::INET->new();
164 return undef unless $sock;
166 my $proto = getprotobyname('tcp');
167 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
170 $conn->{blocking} = 0;
172 my $ip = gethostbyname($to_host);
173 # my $r = $sock->connect($to_port, $ip);
174 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
175 return undef unless $r || _err_will_block($!);
177 $conn->{sock} = $sock;
179 if ($conn->{rproc}) {
180 my $callback = sub {$conn->_rcv};
181 set_event_handler ($sock, read => $callback);
188 return if exists $conn->{disconnecting};
190 $conn->{disconnecting} = 1;
191 my $sock = delete $conn->{sock};
192 $conn->{state} = 'E';
193 $conn->{timeout}->del if $conn->{timeout};
195 # be careful to delete the correct one
197 if ($call = $conn->{call}) {
198 my $ref = $conns{$call};
199 delete $conns{$call} if $ref && $ref == $conn;
201 $call ||= 'unallocated';
202 dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
204 unless ($main::is_win) {
205 kill 'TERM', $conn->{pid} if exists $conn->{pid};
208 # get rid of any references
210 if (ref($conn->{$_})) {
215 return unless defined($sock);
216 set_event_handler ($sock, read => undef, write => undef, error => undef);
222 my ($conn, $msg) = @_;
223 $conn->enqueue($msg);
224 $conn->_send (1); # 1 ==> flush
228 my ($conn, $msg) = @_;
229 $conn->enqueue($msg);
230 my $sock = $conn->{sock};
231 return unless defined($sock);
232 set_event_handler ($sock, write => sub {$conn->_send(0)});
237 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
241 my ($conn, $flush) = @_;
242 my $sock = $conn->{sock};
243 return unless defined($sock);
244 my $rq = $conn->{outqueue};
246 # If $flush is set, set the socket to blocking, and send all
247 # messages in the queue - return only if there's an error
248 # If $flush is 0 (deferred mode) make the socket non-blocking, and
249 # return to the event loop only after every message, or if it
250 # is likely to block in the middle of a message.
252 if ($conn->{blocking} != $flush) {
253 blocking($sock, $flush);
254 $conn->{blocking} = $flush;
256 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
260 my $mlth = length($msg);
261 my $bytes_to_write = $mlth - $offset;
262 my $bytes_written = 0;
263 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
264 while ($bytes_to_write > 0) {
265 $bytes_written = syswrite ($sock, $msg,
266 $bytes_to_write, $offset);
267 if (!defined($bytes_written)) {
268 if (_err_will_block($!)) {
269 # Should happen only in deferred mode. Record how
270 # much we have already sent.
271 $conn->{send_offset} = $offset;
272 # Event handler should already be set, so we will
273 # be called back eventually, and will resume sending
276 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
278 return 0; # fail. Message remains in queue ..
280 } elsif (isdbg('raw')) {
281 my $call = $conn->{call} || 'none';
282 dbgdump('raw', "$call send $bytes_written: ", $msg);
284 $offset += $bytes_written;
285 $bytes_to_write -= $bytes_written;
287 delete $conn->{send_offset};
290 #last unless $flush; # Go back to select and wait
291 # for it to fire again.
293 # Call me back if queue has not been drained.
295 set_event_handler ($sock, write => undef);
296 if (exists $conn->{close_on_empty}) {
297 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
307 my $oldsock = $conn->{sock};
308 my $rc = $rd_callbacks{$oldsock};
309 my $wc = $wt_callbacks{$oldsock};
310 my $ec = $er_callbacks{$oldsock};
311 my $sock = $oldsock->new_from_fd($oldsock, "w+");
313 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
314 $conn->{sock} = $sock;
315 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
320 sub _err_will_block {
321 return 0 unless $blocking_supported;
322 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
328 $conn->{close_on_empty} = 1;
331 #-----------------------------------------------------------------
332 # Receive side routines
335 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
336 my ($pkg, $my_host, $my_port, $login_proc) = @_;
337 my $self = $pkg->new($login_proc);
339 $self->{sock} = IO::Socket::INET->new (
340 LocalAddr => $my_host,
341 LocalPort => $my_port,
345 die "Could not create socket: $! \n" unless $self->{sock};
346 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
354 if ($conn->{msg} =~ /\n/) {
355 my @lines = split /\r?\n/, $conn->{msg};
356 if ($conn->{msg} =~ /\n$/) {
359 $conn->{msg} = pop @lines;
362 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
367 sub _rcv { # Complement to _send
368 my $conn = shift; # $rcv_now complement of $flush
369 # Find out how much has already been received, if at all
370 my ($msg, $offset, $bytes_to_read, $bytes_read);
371 my $sock = $conn->{sock};
372 return unless defined($sock);
375 if ($conn->{blocking}) {
377 $conn->{blocking} = 0;
379 $bytes_read = sysread ($sock, $msg, 1024, 0);
380 if (defined ($bytes_read)) {
381 if ($bytes_read > 0) {
382 $conn->{msg} .= $msg;
384 my $call = $conn->{call} || 'none';
385 dbgdump('raw', "$call read $bytes_read: ", $msg);
389 if (_err_will_block($!)) {
397 if (defined $bytes_read && $bytes_read == 0) {
398 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
401 unless ($conn->{disable_read}) {
402 $conn->dequeue if exists $conn->{msg};
408 my $server_conn = shift;
409 my $sock = $server_conn->{sock}->accept();
411 my $conn = $server_conn->new($server_conn->{rproc});
412 $conn->{sock} = $sock;
414 $conn->{blocking} = 0;
415 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
416 $conn->{sort} = 'Incoming';
418 $conn->{eproc} = $eproc;
419 set_event_handler ($sock, error => $eproc);
422 $conn->{rproc} = $rproc;
423 my $callback = sub {$conn->_rcv};
424 set_event_handler ($sock, read => $callback);
425 } else { # Login failed
426 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
430 dbg("Msg: error on accept ($!)") if isdbg('err');
437 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
438 $conn->{sock}->close;
441 # close all clients (this is for forking really)
442 sub close_all_clients
444 foreach my $conn (values %conns) {
452 set_event_handler ($conn->{sock}, read => undef);
453 return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
457 #----------------------------------------------------
458 # Event loop routines used by both client and server
460 sub set_event_handler {
461 shift unless ref($_[0]); # shift if first arg is package name
462 my ($handle, %args) = @_;
464 if (exists $args{'write'}) {
465 $callback = $args{'write'};
467 $wt_callbacks{$handle} = $callback;
468 $wt_handles->add($handle);
470 delete $wt_callbacks{$handle};
471 $wt_handles->remove($handle);
474 if (exists $args{'read'}) {
475 $callback = $args{'read'};
477 $rd_callbacks{$handle} = $callback;
478 $rd_handles->add($handle);
480 delete $rd_callbacks{$handle};
481 $rd_handles->remove($handle);
484 if (exists $args{'error'}) {
485 $callback = $args{'error'};
487 $er_callbacks{$handle} = $callback;
488 $er_handles->add($handle);
490 delete $er_callbacks{$handle};
491 $er_handles->remove($handle);
497 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
498 my ($conn, $r, $w, $e, $rset, $wset, $eset);
501 # Quit the loop if no handles left to process
502 last unless ($rd_handles->count() || $wt_handles->count());
504 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
506 foreach $e (@$eset) {
507 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
509 foreach $r (@$rset) {
510 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
512 foreach $w (@$wset) {
513 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
518 if (defined($loop_count)) {
519 last unless --$loop_count;
526 my ($pkg, $interval) = @_;
528 while (time - $now < $interval) {
529 $pkg->event_loop(10, 0.01);
536 my $call = $conn->{call} || 'unallocated';
537 my $host = $conn->{peerhost} || '';
538 my $port = $conn->{peerport} || '';
539 dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');