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)
18 use Errno qw(EWOULDBLOCK EAGAIN EINPROGRESS);
19 use POSIX qw(F_GETFL F_SETFL O_NONBLOCK);
21 use vars qw(%rd_callbacks %wt_callbacks %er_callbacks $rd_handles $wt_handles $er_handles $now %conns $noconns);
26 $rd_handles = IO::Select->new();
27 $wt_handles = IO::Select->new();
28 $er_handles = IO::Select->new();
33 #-----------------------------------------------------------------
34 # Generalised initializer
38 my ($pkg, $rproc) = @_;
40 my $class = $obj || $pkg;
53 dbg('connll', "Connection created ($noconns)");
54 return bless $conn, $class;
61 $conn->{eproc} = $callback;
62 set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
69 $conn->{rproc} = $callback;
74 my $flags = fcntl ($_[0], F_GETFL, 0);
76 $flags &= ~O_NONBLOCK;
80 fcntl ($_[0], F_SETFL, $flags);
91 $call = $pkg->{call} unless $call;
92 return undef unless $call;
93 confess "changing $pkg->{call} to $call" if exists $pkg->{call} && $call ne $pkg->{call};
95 $ref = $conns{$call} = $pkg;
96 dbg('connll', "Connection $call stored");
103 # this is only called by any dependent processes going away unexpectedly
106 my ($pkg, $pid) = @_;
108 my @pid = grep {$_->{pid} == $pid} values %conns;
110 &{$_->{eproc}}($_, "$pid has gorn") if exists $_->{eproc};
115 #-----------------------------------------------------------------
118 my ($pkg, $to_host, $to_port, $rproc) = @_;
120 # Create a connection end-point object
123 $conn = $pkg->new($rproc);
125 $conn->{peerhost} = $to_host;
126 $conn->{peerport} = $to_port;
127 $conn->{sort} = 'Outgoing';
129 # Create a new internet socket
130 my $sock = IO::Socket::INET->new();
131 return undef unless $sock;
133 my $proto = getprotobyname('tcp');
134 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
137 my $ip = gethostbyname($to_host);
138 my $r = $sock->connect($to_port, $ip);
140 return undef unless $! == EINPROGRESS;
143 $conn->{sock} = $sock;
145 if ($conn->{rproc}) {
146 my $callback = sub {$conn->_rcv};
147 set_event_handler ($sock, read => $callback);
154 return if exists $conn->{disconnecting};
156 $conn->{disconnecting} = 1;
157 my $sock = delete $conn->{sock};
158 $conn->{state} = 'E';
159 $conn->{timeout}->del if $conn->{timeout};
161 # be careful to delete the correct one
163 if ($call = $conn->{call}) {
164 my $ref = $conns{$call};
165 delete $conns{$call} if $ref && $ref == $conn;
167 $call ||= 'unallocated';
168 dbg('connll', "Connection $call disconnected");
170 set_event_handler ($sock, read => undef, write => undef, error => undef);
172 unless ($^O =~ /^MS/i) {
173 kill 'TERM', $conn->{pid} if exists $conn->{pid};
176 # get rid of any references
178 if (ref($conn->{$_})) {
183 return unless defined($sock);
189 my ($conn, $msg) = @_;
190 $conn->enqueue($msg);
191 $conn->_send (1); # 1 ==> flush
195 my ($conn, $msg) = @_;
196 $conn->enqueue($msg);
197 my $sock = $conn->{sock};
198 return unless defined($sock);
199 set_event_handler ($sock, write => sub {$conn->_send(0)});
204 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
208 my ($conn, $flush) = @_;
209 my $sock = $conn->{sock};
210 return unless defined($sock);
211 my $rq = $conn->{outqueue};
213 # If $flush is set, set the socket to blocking, and send all
214 # messages in the queue - return only if there's an error
215 # If $flush is 0 (deferred mode) make the socket non-blocking, and
216 # return to the event loop only after every message, or if it
217 # is likely to block in the middle of a message.
219 blocking($sock, $flush);
220 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
224 my $mlth = length($msg);
225 my $bytes_to_write = $mlth - $offset;
226 my $bytes_written = 0;
227 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
228 while ($bytes_to_write > 0) {
229 $bytes_written = syswrite ($sock, $msg,
230 $bytes_to_write, $offset);
231 if (!defined($bytes_written)) {
232 if (_err_will_block($!)) {
233 # Should happen only in deferred mode. Record how
234 # much we have already sent.
235 $conn->{send_offset} = $offset;
236 # Event handler should already be set, so we will
237 # be called back eventually, and will resume sending
240 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
242 return 0; # fail. Message remains in queue ..
245 $offset += $bytes_written;
246 $bytes_to_write -= $bytes_written;
248 delete $conn->{send_offset};
251 last unless $flush; # Go back to select and wait
252 # for it to fire again.
254 # Call me back if queue has not been drained.
256 set_event_handler ($sock, write => sub {$conn->_send(0)});
258 set_event_handler ($sock, write => undef);
259 if (exists $conn->{close_on_empty}) {
260 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
267 sub _err_will_block {
268 return ($_[0] == EAGAIN || $_[0] == EWOULDBLOCK || $_[0] == EINPROGRESS);
274 $conn->{close_on_empty} = 1;
277 #-----------------------------------------------------------------
278 # Receive side routines
281 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
282 my ($pkg, $my_host, $my_port, $login_proc) = @_;
283 my $self = $pkg->new($login_proc);
285 $self->{sock} = IO::Socket::INET->new (
286 LocalAddr => $my_host,
287 LocalPort => $my_port,
291 die "Could not create socket: $! \n" unless $self->{sock};
292 set_event_handler ($self->{sock}, read => sub { $self->new_client } );
300 if ($conn->{msg} =~ /\n/) {
301 my @lines = split /\r?\n/, $conn->{msg};
302 if ($conn->{msg} =~ /\n$/) {
305 $conn->{msg} = pop @lines;
308 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
313 sub _rcv { # Complement to _send
314 my $conn = shift; # $rcv_now complement of $flush
315 # Find out how much has already been received, if at all
316 my ($msg, $offset, $bytes_to_read, $bytes_read);
317 my $sock = $conn->{sock};
318 return unless defined($sock);
322 $bytes_read = sysread ($sock, $msg, 1024, 0);
323 if (defined ($bytes_read)) {
324 if ($bytes_read > 0) {
325 $conn->{msg} .= $msg;
328 if (_err_will_block($!)) {
336 if (defined $bytes_read && $bytes_read == 0) {
337 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
340 $conn->dequeue if exists $conn->{msg};
345 my $server_conn = shift;
346 my $sock = $server_conn->{sock}->accept();
347 my $conn = $server_conn->new($server_conn->{rproc});
348 $conn->{sock} = $sock;
349 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
350 $conn->{sort} = 'Incoming';
352 $conn->{eproc} = $eproc;
353 set_event_handler ($sock, error => $eproc);
356 $conn->{rproc} = $rproc;
357 my $callback = sub {$conn->_rcv};
358 set_event_handler ($sock, read => $callback);
359 } else { # Login failed
360 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
368 set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
369 $conn->{sock}->close;
372 # close all clients (this is for forking really)
373 sub close_all_clients
375 for (values %conns) {
380 #----------------------------------------------------
381 # Event loop routines used by both client and server
383 sub set_event_handler {
384 shift unless ref($_[0]); # shift if first arg is package name
385 my ($handle, %args) = @_;
387 if (exists $args{'write'}) {
388 $callback = $args{'write'};
390 $wt_callbacks{$handle} = $callback;
391 $wt_handles->add($handle);
393 delete $wt_callbacks{$handle};
394 $wt_handles->remove($handle);
397 if (exists $args{'read'}) {
398 $callback = $args{'read'};
400 $rd_callbacks{$handle} = $callback;
401 $rd_handles->add($handle);
403 delete $rd_callbacks{$handle};
404 $rd_handles->remove($handle);
407 if (exists $args{'error'}) {
408 $callback = $args{'error'};
410 $er_callbacks{$handle} = $callback;
411 $er_handles->add($handle);
413 delete $er_callbacks{$handle};
414 $er_handles->remove($handle);
420 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
421 my ($conn, $r, $w, $e, $rset, $wset, $eset);
424 # Quit the loop if no handles left to process
425 last unless ($rd_handles->count() || $wt_handles->count());
427 ($rset, $wset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
430 foreach $e (@$eset) {
431 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
433 foreach $r (@$rset) {
434 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
436 foreach $w (@$wset) {
437 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
442 if (defined($loop_count)) {
443 last unless --$loop_count;
451 my $call = $conn->{call} || 'unallocated';
452 dbg('connll', "Connection $call being destroyed ($noconns)");