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);
24 $rd_handles = IO::Select->new();
25 $wt_handles = IO::Select->new();
26 $er_handles = IO::Select->new();
29 my $blocking_supported = 0;
32 # Checks if blocking is supported
34 require POSIX; POSIX->import(qw (F_SETFL F_GETFL O_NONBLOCK));
36 $blocking_supported = 1 unless $@;
38 # import as many of these errno values as are available
40 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
46 my $eagain = eval {EAGAIN()};
47 my $einprogress = eval {EINPROGRESS()};
48 my $ewouldblock = eval {EWOULDBLOCK()};
52 #-----------------------------------------------------------------
53 # Generalised initializer
57 my ($pkg, $rproc) = @_;
59 my $class = $obj || $pkg;
72 dbg('connll', "Connection created ($noconns)");
73 return bless $conn, $class;
80 $conn->{eproc} = $callback;
81 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
88 $conn->{rproc} = $callback;
93 return unless $blocking_supported;
95 my $flags = fcntl ($_[0], F_GETFL, 0);
97 $flags &= ~O_NONBLOCK;
101 fcntl ($_[0], F_SETFL, $flags);
112 $call = $pkg->{call} unless $call;
113 return undef unless $call;
114 confess "changing $pkg->{call} to $call" if exists $pkg->{call} && $call ne $pkg->{call};
115 $pkg->{call} = $call;
116 $ref = $conns{$call} = $pkg;
117 dbg('connll', "Connection $call stored");
119 $ref = $conns{$call};
124 # this is only called by any dependent processes going away unexpectedly
127 my ($pkg, $pid) = @_;
129 my @pid = grep {$_->{pid} == $pid} values %conns;
131 &{$_->{eproc}}($_, "$pid has gorn") if exists $_->{eproc};
136 #-----------------------------------------------------------------
139 my ($pkg, $to_host, $to_port, $rproc) = @_;
141 # Create a connection end-point object
144 $conn = $pkg->new($rproc);
146 $conn->{peerhost} = $to_host;
147 $conn->{peerport} = $to_port;
148 $conn->{sort} = 'Outgoing';
150 # Create a new internet socket
151 my $sock = IO::Socket::INET->new();
152 return undef unless $sock;
154 my $proto = getprotobyname('tcp');
155 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
158 my $ip = gethostbyname($to_host);
159 # my $r = $sock->connect($to_port, $ip);
160 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
161 return undef unless $r || _err_will_block($!);
163 $conn->{sock} = $sock;
165 if ($conn->{rproc}) {
166 my $callback = sub {$conn->_rcv};
167 set_event_handler ($sock, read => $callback);
174 return if exists $conn->{disconnecting};
176 $conn->{disconnecting} = 1;
177 my $sock = delete $conn->{sock};
178 $conn->{state} = 'E';
179 $conn->{timeout}->del if $conn->{timeout};
181 # be careful to delete the correct one
183 if ($call = $conn->{call}) {
184 my $ref = $conns{$call};
185 delete $conns{$call} if $ref && $ref == $conn;
187 $call ||= 'unallocated';
188 dbg('connll', "Connection $call disconnected");
190 unless ($^O =~ /^MS/i) {
191 kill 'TERM', $conn->{pid} if exists $conn->{pid};
194 # get rid of any references
196 if (ref($conn->{$_})) {
201 return unless defined($sock);
202 set_event_handler ($sock, read => undef, write => undef, error => undef);
208 my ($conn, $msg) = @_;
209 $conn->enqueue($msg);
210 $conn->_send (1); # 1 ==> flush
214 my ($conn, $msg) = @_;
215 $conn->enqueue($msg);
216 my $sock = $conn->{sock};
217 return unless defined($sock);
218 set_event_handler ($sock, write => sub {$conn->_send(0)});
223 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
227 my ($conn, $flush) = @_;
228 my $sock = $conn->{sock};
229 return unless defined($sock);
230 my $rq = $conn->{outqueue};
232 # If $flush is set, set the socket to blocking, and send all
233 # messages in the queue - return only if there's an error
234 # If $flush is 0 (deferred mode) make the socket non-blocking, and
235 # return to the event loop only after every message, or if it
236 # is likely to block in the middle of a message.
238 blocking($sock, $flush);
239 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
243 my $mlth = length($msg);
244 my $bytes_to_write = $mlth - $offset;
245 my $bytes_written = 0;
246 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
247 while ($bytes_to_write > 0) {
248 $bytes_written = syswrite ($sock, $msg,
249 $bytes_to_write, $offset);
250 if (!defined($bytes_written)) {
251 if (_err_will_block($!)) {
252 # Should happen only in deferred mode. Record how
253 # much we have already sent.
254 $conn->{send_offset} = $offset;
255 # Event handler should already be set, so we will
256 # be called back eventually, and will resume sending
259 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
261 return 0; # fail. Message remains in queue ..
264 $offset += $bytes_written;
265 $bytes_to_write -= $bytes_written;
267 delete $conn->{send_offset};
270 last unless $flush; # Go back to select and wait
271 # for it to fire again.
273 # Call me back if queue has not been drained.
275 set_event_handler ($sock, write => sub {$conn->_send(0)});
277 set_event_handler ($sock, write => undef);
278 if (exists $conn->{close_on_empty}) {
279 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
286 sub _err_will_block {
287 return 0 unless $blocking_supported;
288 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
294 $conn->{close_on_empty} = 1;
297 #-----------------------------------------------------------------
298 # Receive side routines
301 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
302 my ($pkg, $my_host, $my_port, $login_proc) = @_;
303 my $self = $pkg->new($login_proc);
305 $self->{sock} = IO::Socket::INET->new (
306 LocalAddr => $my_host,
307 LocalPort => $my_port,
311 die "Could not create socket: $! \n" unless $self->{sock};
312 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
320 if ($conn->{msg} =~ /\n/) {
321 my @lines = split /\r?\n/, $conn->{msg};
322 if ($conn->{msg} =~ /\n$/) {
325 $conn->{msg} = pop @lines;
328 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
333 sub _rcv { # Complement to _send
334 my $conn = shift; # $rcv_now complement of $flush
335 # Find out how much has already been received, if at all
336 my ($msg, $offset, $bytes_to_read, $bytes_read);
337 my $sock = $conn->{sock};
338 return unless defined($sock);
342 $bytes_read = sysread ($sock, $msg, 1024, 0);
343 if (defined ($bytes_read)) {
344 if ($bytes_read > 0) {
345 $conn->{msg} .= $msg;
348 if (_err_will_block($!)) {
356 if (defined $bytes_read && $bytes_read == 0) {
357 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
360 $conn->dequeue if exists $conn->{msg};
365 my $server_conn = shift;
366 my $sock = $server_conn->{sock}->accept();
367 my $conn = $server_conn->new($server_conn->{rproc});
368 $conn->{sock} = $sock;
369 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
370 $conn->{sort} = 'Incoming';
372 $conn->{eproc} = $eproc;
373 set_event_handler ($sock, error => $eproc);
376 $conn->{rproc} = $rproc;
377 my $callback = sub {$conn->_rcv};
378 set_event_handler ($sock, read => $callback);
379 } else { # Login failed
380 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
388 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
389 $conn->{sock}->close;
392 # close all clients (this is for forking really)
393 sub close_all_clients
395 for (values %conns) {
400 #----------------------------------------------------
401 # Event loop routines used by both client and server
403 sub set_event_handler {
404 shift unless ref($_[0]); # shift if first arg is package name
405 my ($handle, %args) = @_;
407 if (exists $args{'write'}) {
408 $callback = $args{'write'};
410 $wt_callbacks{$handle} = $callback;
411 $wt_handles->add($handle);
413 delete $wt_callbacks{$handle};
414 $wt_handles->remove($handle);
417 if (exists $args{'read'}) {
418 $callback = $args{'read'};
420 $rd_callbacks{$handle} = $callback;
421 $rd_handles->add($handle);
423 delete $rd_callbacks{$handle};
424 $rd_handles->remove($handle);
427 if (exists $args{'error'}) {
428 $callback = $args{'error'};
430 $er_callbacks{$handle} = $callback;
431 $er_handles->add($handle);
433 delete $er_callbacks{$handle};
434 $er_handles->remove($handle);
440 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
441 my ($conn, $r, $w, $e, $rset, $wset, $eset);
444 # Quit the loop if no handles left to process
445 last unless ($rd_handles->count() || $wt_handles->count());
447 ($rset, $wset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
449 foreach $e (@$eset) {
450 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
452 foreach $r (@$rset) {
453 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
455 foreach $w (@$wset) {
456 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
461 if (defined($loop_count)) {
462 last unless --$loop_count;
470 my $call = $conn->{call} || 'unallocated';
471 dbg('connll', "Connection $call being destroyed ($noconns)");