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};
67 my $flags = fcntl ($_[0], F_GETFL, 0);
69 $flags &= ~O_NONBLOCK;
73 fcntl ($_[0], F_SETFL, $flags);
84 $call = $pkg->{call} unless $call;
85 return undef unless $call;
86 confess "changing $pkg->{call} to $call" if exists $pkg->{call} && $call ne $pkg->{call};
88 $ref = $conns{$call} = $pkg;
89 dbg('connll', "Connection $call stored");
96 # this is only called by any dependent processes going away unexpectedly
101 my @pid = grep {$_->{pid} == $pid} values %conns;
103 &{$_->{eproc}}($_, "$pid has gorn") if exists $_->{eproc};
108 #-----------------------------------------------------------------
111 my ($pkg, $to_host, $to_port, $rproc) = @_;
113 # Create a connection end-point object
116 $conn = $pkg->new($rproc);
118 $conn->{peerhost} = $to_host;
119 $conn->{peerport} = $to_port;
120 $conn->{sort} = 'Outgoing';
122 # Create a new internet socket
123 my $sock = IO::Socket::INET->new();
124 return undef unless $sock;
126 my $proto = getprotobyname('tcp');
127 $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
130 my $ip = gethostbyname($to_host);
131 my $r = $sock->connect($to_port, $ip);
133 return undef unless $! == EINPROGRESS;
136 $conn->{sock} = $sock;
138 if ($conn->{rproc}) {
139 my $callback = sub {_rcv($conn)};
140 set_event_handler ($sock, "read" => $callback);
147 return if exists $conn->{disconnecting};
149 $conn->{disconnecting} = 1;
150 my $sock = delete $conn->{sock};
151 $conn->{state} = 'E';
153 delete $conn->{eproc};
154 delete $conn->{rproc};
155 $conn->{timeout}->del if $conn->{timeout};
157 # be careful to delete the correct one
159 if ($call = $conn->{call}) {
160 my $ref = $conns{$call};
161 delete $conns{$call} if $ref && $ref == $conn;
163 $call ||= 'unallocated';
164 dbg('connll', "Connection $call disconnected");
166 set_event_handler ($sock, read => undef, write => undef, error => undef);
167 unless ($^O =~ /^MS/i) {
168 kill 'TERM', $conn->{pid} if exists $conn->{pid};
170 return unless defined($sock);
176 my ($conn, $msg) = @_;
177 $conn->enqueue($msg);
178 $conn->_send (1); # 1 ==> flush
182 my ($conn, $msg) = @_;
183 $conn->enqueue($msg);
184 my $sock = $conn->{sock};
185 return unless defined($sock);
186 set_event_handler ($sock, "write" => sub {$conn->_send(0)});
191 push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
195 my ($conn, $flush) = @_;
196 my $sock = $conn->{sock};
197 return unless defined($sock);
198 my $rq = $conn->{outqueue};
200 # If $flush is set, set the socket to blocking, and send all
201 # messages in the queue - return only if there's an error
202 # If $flush is 0 (deferred mode) make the socket non-blocking, and
203 # return to the event loop only after every message, or if it
204 # is likely to block in the middle of a message.
206 blocking($sock, $flush);
207 my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
211 my $mlth = length($msg);
212 my $bytes_to_write = $mlth - $offset;
213 my $bytes_written = 0;
214 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
215 while ($bytes_to_write > 0) {
216 $bytes_written = syswrite ($sock, $msg,
217 $bytes_to_write, $offset);
218 if (!defined($bytes_written)) {
219 if (_err_will_block($!)) {
220 # Should happen only in deferred mode. Record how
221 # much we have already sent.
222 $conn->{send_offset} = $offset;
223 # Event handler should already be set, so we will
224 # be called back eventually, and will resume sending
227 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
229 return 0; # fail. Message remains in queue ..
232 $offset += $bytes_written;
233 $bytes_to_write -= $bytes_written;
235 delete $conn->{send_offset};
238 last unless $flush; # Go back to select and wait
239 # for it to fire again.
241 # Call me back if queue has not been drained.
243 set_event_handler ($sock, "write" => sub {$conn->_send(0)});
245 set_event_handler ($sock, "write" => undef);
246 if (exists $conn->{close_on_empty}) {
247 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
254 sub _err_will_block {
255 return ($_[0] == EAGAIN || $_[0] == EWOULDBLOCK || $_[0] == EINPROGRESS);
261 $conn->{close_on_empty} = 1;
264 #-----------------------------------------------------------------
265 # Receive side routines
268 @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
269 my ($pkg, $my_host, $my_port, $login_proc) = @_;
270 my $self = $pkg->new($login_proc);
272 $self->{sock} = IO::Socket::INET->new (
273 LocalAddr => $my_host,
274 LocalPort => $my_port,
278 die "Could not create socket: $! \n" unless $self->{sock};
279 set_event_handler ($self->{sock}, "read" => sub { $self->new_client } );
287 if ($conn->{msg} =~ /\n/) {
288 my @lines = split /\r?\n/, $conn->{msg};
289 if ($conn->{msg} =~ /\n$/) {
292 $conn->{msg} = pop @lines;
295 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
300 sub _rcv { # Complement to _send
301 my $conn = shift; # $rcv_now complement of $flush
302 # Find out how much has already been received, if at all
303 my ($msg, $offset, $bytes_to_read, $bytes_read);
304 my $sock = $conn->{sock};
305 return unless defined($sock);
309 $bytes_read = sysread ($sock, $msg, 1024, 0);
310 if (defined ($bytes_read)) {
311 if ($bytes_read > 0) {
312 $conn->{msg} .= $msg;
315 if (_err_will_block($!)) {
323 if (defined $bytes_read && $bytes_read == 0) {
324 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
327 $conn->dequeue if exists $conn->{msg};
332 my $server_conn = shift;
333 my $sock = $server_conn->{sock}->accept();
334 my $conn = $server_conn->new($server_conn->{rproc});
335 $conn->{sock} = $sock;
336 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
337 $conn->{sort} = 'Incoming';
339 $conn->{eproc} = $eproc;
340 set_event_handler ($sock, "error" => $eproc);
343 $conn->{rproc} = $rproc;
344 my $callback = sub {_rcv($conn)};
345 set_event_handler ($sock, "read" => $callback);
346 } else { # Login failed
347 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
355 set_event_handler ($conn->{sock}, "read" => undef);
356 $conn->{sock}->close;
359 # close all clients (this is for forking really)
360 sub close_all_clients
362 for (values %conns) {
367 #----------------------------------------------------
368 # Event loop routines used by both client and server
370 sub set_event_handler {
371 shift unless ref($_[0]); # shift if first arg is package name
372 my ($handle, %args) = @_;
374 if (exists $args{'write'}) {
375 $callback = $args{'write'};
377 $wt_callbacks{$handle} = $callback;
378 $wt_handles->add($handle);
380 delete $wt_callbacks{$handle};
381 $wt_handles->remove($handle);
384 if (exists $args{'read'}) {
385 $callback = $args{'read'};
387 $rd_callbacks{$handle} = $callback;
388 $rd_handles->add($handle);
390 delete $rd_callbacks{$handle};
391 $rd_handles->remove($handle);
394 if (exists $args{'error'}) {
395 $callback = $args{'error'};
397 $er_callbacks{$handle} = $callback;
398 $er_handles->add($handle);
400 delete $er_callbacks{$handle};
401 $er_handles->remove($handle);
407 my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
408 my ($conn, $r, $w, $e, $rset, $wset, $eset);
411 # Quit the loop if no handles left to process
412 last unless ($rd_handles->count() || $wt_handles->count());
414 ($rset, $wset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
417 foreach $e (@$eset) {
418 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
420 foreach $r (@$rset) {
421 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
423 foreach $w (@$wset) {
424 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
429 if (defined($loop_count)) {
430 last unless --$loop_count;
438 my $call = $conn->{call} || 'unallocated';
439 dbg('connll', "Connection $call being destroyed ($noconns)");