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;
73 dbg('connll', "Connection created ($noconns)");
74 return bless $conn, $class;
81 $conn->{eproc} = $callback;
82 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
89 $conn->{rproc} = $callback;
94 return unless $blocking_supported;
96 my $flags = fcntl ($_[0], F_GETFL, 0);
98 $flags &= ~O_NONBLOCK;
100 $flags |= O_NONBLOCK;
102 fcntl ($_[0], F_SETFL, $flags);
113 $call = $pkg->{call} unless $call;
114 return undef unless $call;
115 confess "changing $pkg->{call} to $call" if exists $pkg->{call} && $call ne $pkg->{call};
116 $pkg->{call} = $call;
117 $ref = $conns{$call} = $pkg;
118 dbg('connll', "Connection $call stored");
120 $ref = $conns{$call};
125 # this is only called by any dependent processes going away unexpectedly
128 my ($pkg, $pid) = @_;
130 my @pid = grep {$_->{pid} == $pid} values %conns;
132 &{$_->{eproc}}($_, "$pid has gorn") if exists $_->{eproc};
137 #-----------------------------------------------------------------
140 my ($pkg, $to_host, $to_port, $rproc) = @_;
142 # Create a connection end-point object
145 $conn = $pkg->new($rproc);
147 $conn->{peerhost} = $to_host;
148 $conn->{peerport} = $to_port;
149 $conn->{sort} = 'Outgoing';
151 # Create a new internet socket
152 my $sock = IO::Socket::INET->new();
153 return undef unless $sock;
155 my $proto = getprotobyname('tcp');
156 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
158 if ($conn->{blocking}) {
160 $conn->{blocking} = 0;
163 my $ip = gethostbyname($to_host);
164 # my $r = $sock->connect($to_port, $ip);
165 my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
166 return undef unless $r || _err_will_block($!);
168 $conn->{sock} = $sock;
170 if ($conn->{rproc}) {
171 my $callback = sub {$conn->_rcv};
172 set_event_handler ($sock, read => $callback);
179 return if exists $conn->{disconnecting};
181 $conn->{disconnecting} = 1;
182 my $sock = delete $conn->{sock};
183 $conn->{state} = 'E';
184 $conn->{timeout}->del if $conn->{timeout};
186 # be careful to delete the correct one
188 if ($call = $conn->{call}) {
189 my $ref = $conns{$call};
190 delete $conns{$call} if $ref && $ref == $conn;
192 $call ||= 'unallocated';
193 dbg('connll', "Connection $call disconnected");
195 unless ($^O =~ /^MS/i) {
196 kill 'TERM', $conn->{pid} if exists $conn->{pid};
199 # get rid of any references
201 if (ref($conn->{$_})) {
206 return unless defined($sock);
207 set_event_handler ($sock, read => undef, write => undef, error => undef);
213 my ($conn, $msg) = @_;
214 $conn->enqueue($msg);
215 $conn->_send (1); # 1 ==> flush
219 my ($conn, $msg) = @_;
220 $conn->enqueue($msg);
221 my $sock = $conn->{sock};
222 return unless defined($sock);
223 set_event_handler ($sock, write => sub {$conn->_send(0)});
228 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
232 my ($conn, $flush) = @_;
233 my $sock = $conn->{sock};
234 return unless defined($sock);
235 my $rq = $conn->{outqueue};
237 # If $flush is set, set the socket to blocking, and send all
238 # messages in the queue - return only if there's an error
239 # If $flush is 0 (deferred mode) make the socket non-blocking, and
240 # return to the event loop only after every message, or if it
241 # is likely to block in the middle of a message.
243 if ($conn->{blocking} != $flush) {
244 blocking($sock, $flush);
245 $conn->{blocking} = $flush;
247 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
251 my $mlth = length($msg);
252 my $bytes_to_write = $mlth - $offset;
253 my $bytes_written = 0;
254 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
255 while ($bytes_to_write > 0) {
256 $bytes_written = syswrite ($sock, $msg,
257 $bytes_to_write, $offset);
258 if (!defined($bytes_written)) {
259 if (_err_will_block($!)) {
260 # Should happen only in deferred mode. Record how
261 # much we have already sent.
262 $conn->{send_offset} = $offset;
263 # Event handler should already be set, so we will
264 # be called back eventually, and will resume sending
267 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
269 return 0; # fail. Message remains in queue ..
272 $offset += $bytes_written;
273 $bytes_to_write -= $bytes_written;
275 delete $conn->{send_offset};
278 last unless $flush; # Go back to select and wait
279 # for it to fire again.
281 # Call me back if queue has not been drained.
283 set_event_handler ($sock, write => sub {$conn->_send(0)});
285 set_event_handler ($sock, write => undef);
286 if (exists $conn->{close_on_empty}) {
287 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
297 my $oldsock = $conn->{sock};
298 my $rc = $rd_callbacks{$oldsock};
299 my $wc = $wt_callbacks{$oldsock};
300 my $ec = $er_callbacks{$oldsock};
301 my $sock = $oldsock->new_from_fd($oldsock, "w+");
303 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
304 $conn->{sock} = $sock;
305 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
310 sub _err_will_block {
311 return 0 unless $blocking_supported;
312 return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
318 $conn->{close_on_empty} = 1;
321 #-----------------------------------------------------------------
322 # Receive side routines
325 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
326 my ($pkg, $my_host, $my_port, $login_proc) = @_;
327 my $self = $pkg->new($login_proc);
329 $self->{sock} = IO::Socket::INET->new (
330 LocalAddr => $my_host,
331 LocalPort => $my_port,
335 die "Could not create socket: $! \n" unless $self->{sock};
336 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
344 if ($conn->{msg} =~ /\n/) {
345 my @lines = split /\r?\n/, $conn->{msg};
346 if ($conn->{msg} =~ /\n$/) {
349 $conn->{msg} = pop @lines;
352 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
357 sub _rcv { # Complement to _send
358 my $conn = shift; # $rcv_now complement of $flush
359 # Find out how much has already been received, if at all
360 my ($msg, $offset, $bytes_to_read, $bytes_read);
361 my $sock = $conn->{sock};
362 return unless defined($sock);
365 if ($conn->{blocking}) {
367 $conn->{blocking} = 0;
369 $bytes_read = sysread ($sock, $msg, 1024, 0);
370 if (defined ($bytes_read)) {
371 if ($bytes_read > 0) {
372 $conn->{msg} .= $msg;
375 if (_err_will_block($!)) {
383 if (defined $bytes_read && $bytes_read == 0) {
384 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
387 $conn->dequeue if exists $conn->{msg};
392 my $server_conn = shift;
393 my $sock = $server_conn->{sock}->accept();
394 my $conn = $server_conn->new($server_conn->{rproc});
395 $conn->{sock} = $sock;
396 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
397 $conn->{sort} = 'Incoming';
399 $conn->{eproc} = $eproc;
400 set_event_handler ($sock, error => $eproc);
403 $conn->{rproc} = $rproc;
404 my $callback = sub {$conn->_rcv};
405 set_event_handler ($sock, read => $callback);
406 } else { # Login failed
407 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
415 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
416 $conn->{sock}->close;
419 # close all clients (this is for forking really)
420 sub close_all_clients
422 for (values %conns) {
428 #----------------------------------------------------
429 # Event loop routines used by both client and server
431 sub set_event_handler {
432 shift unless ref($_[0]); # shift if first arg is package name
433 my ($handle, %args) = @_;
435 if (exists $args{'write'}) {
436 $callback = $args{'write'};
438 $wt_callbacks{$handle} = $callback;
439 $wt_handles->add($handle);
441 delete $wt_callbacks{$handle};
442 $wt_handles->remove($handle);
445 if (exists $args{'read'}) {
446 $callback = $args{'read'};
448 $rd_callbacks{$handle} = $callback;
449 $rd_handles->add($handle);
451 delete $rd_callbacks{$handle};
452 $rd_handles->remove($handle);
455 if (exists $args{'error'}) {
456 $callback = $args{'error'};
458 $er_callbacks{$handle} = $callback;
459 $er_handles->add($handle);
461 delete $er_callbacks{$handle};
462 $er_handles->remove($handle);
468 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
469 my ($conn, $r, $w, $e, $rset, $wset, $eset);
472 # Quit the loop if no handles left to process
473 last unless ($rd_handles->count() || $wt_handles->count());
475 ($rset, $wset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
477 foreach $e (@$eset) {
478 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
480 foreach $r (@$rset) {
481 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
483 foreach $w (@$wset) {
484 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
489 if (defined($loop_count)) {
490 last unless --$loop_count;
497 my ($pkg, $interval) = @_;
499 while (time - $now < $interval) {
500 $pkg->event_loop(10, 0.01);
507 my $call = $conn->{call} || 'unallocated';
508 dbg('connll', "Connection $call being destroyed ($noconns)");